diff --git a/client/metrics.go b/client/metrics.go index 6e4804b537..d6d404b14f 100644 --- a/client/metrics.go +++ b/client/metrics.go @@ -34,3 +34,11 @@ func (c *WaspClient) GetChainConsensusWorkflowStatus(chID *iscp.ChainID) (*model } return ncmm, nil } + +func (c *WaspClient) GetChainConsensusPipeMetrics(chID *iscp.ChainID) (*model.ConsensusPipeMetrics, error) { + ncmm := &model.ConsensusPipeMetrics{} + if err := c.do(http.MethodGet, routes.GetChainConsensusPipeMetrics(chID.Base58()), nil, ncmm); err != nil { + return nil, err + } + return ncmm, nil +} diff --git a/contracts/wasm/core_build.cmd b/contracts/wasm/core_build.cmd index b6c208ba50..53f3f1720a 100644 --- a/contracts/wasm/core_build.cmd +++ b/contracts/wasm/core_build.cmd @@ -1,8 +1,9 @@ @echo off -cd ..\..\packages\vm\wasmlib +go install ../../tools/schema +cd ..\..\packages\wasmvm\wasmlib schema -core -go -rust -ts -client -force del /s /q d:\work\node_modules\wasmlib\*.* >nul: del /s /q d:\work\node_modules\wasmclient\*.* >nul: -xcopy /s /q d:\Work\go\github.com\iotaledger\wasp\packages\vm\wasmlib\ts\wasmclient d:\work\node_modules\wasmclient -xcopy /s /q d:\Work\go\github.com\iotaledger\wasp\packages\vm\wasmlib\ts\wasmlib d:\work\node_modules\wasmlib +xcopy /s /q d:\Work\go\github.com\iotaledger\wasp\packages\wasmvm\wasmlib\ts\wasmclient d:\work\node_modules\wasmclient +xcopy /s /q d:\Work\go\github.com\iotaledger\wasp\packages\wasmvm\wasmlib\ts\wasmlib d:\work\node_modules\wasmlib cd ..\..\..\contracts\wasm diff --git a/contracts/wasm/dividend/Cargo.toml b/contracts/wasm/dividend/Cargo.toml index 5a603fb952..2efc543b4e 100644 --- a/contracts/wasm/dividend/Cargo.toml +++ b/contracts/wasm/dividend/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/dividend/go/dividend/consts.go b/contracts/wasm/dividend/go/dividend/consts.go index 2e90e341e5..e5c66a5b75 100644 --- a/contracts/wasm/dividend/go/dividend/consts.go +++ b/contracts/wasm/dividend/go/dividend/consts.go @@ -7,12 +7,12 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "dividend" ScDescription = "Simple dividend smart contract" - HScName = wasmlib.ScHname(0xcce2e239) + HScName = wasmtypes.ScHname(0xcce2e239) ) const ( @@ -43,10 +43,10 @@ const ( ) const ( - HFuncDivide = wasmlib.ScHname(0xc7878107) - HFuncInit = wasmlib.ScHname(0x1f44d644) - HFuncMember = wasmlib.ScHname(0xc07da2cb) - HFuncSetOwner = wasmlib.ScHname(0x2a15fe7b) - HViewGetFactor = wasmlib.ScHname(0x0ee668fe) - HViewGetOwner = wasmlib.ScHname(0x137107a6) + HFuncDivide = wasmtypes.ScHname(0xc7878107) + HFuncInit = wasmtypes.ScHname(0x1f44d644) + HFuncMember = wasmtypes.ScHname(0xc07da2cb) + HFuncSetOwner = wasmtypes.ScHname(0x2a15fe7b) + HViewGetFactor = wasmtypes.ScHname(0x0ee668fe) + HViewGetOwner = wasmtypes.ScHname(0x137107a6) ) diff --git a/contracts/wasm/dividend/go/dividend/contract.go b/contracts/wasm/dividend/go/dividend/contract.go index 603f113e47..3efc3fb14a 100644 --- a/contracts/wasm/dividend/go/dividend/contract.go +++ b/contracts/wasm/dividend/go/dividend/contract.go @@ -7,7 +7,7 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type DivideCall struct { Func *wasmlib.ScFunc @@ -48,31 +48,32 @@ func (sc Funcs) Divide(ctx wasmlib.ScFuncCallContext) *DivideCall { } func (sc Funcs) Init(ctx wasmlib.ScFuncCallContext) *InitCall { - f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit, keyMap[:], idxMap[:])} - f.Func.SetPtrs(&f.Params.id, nil) + f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Member(ctx wasmlib.ScFuncCallContext) *MemberCall { f := &MemberCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMember)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetOwner(ctx wasmlib.ScFuncCallContext) *SetOwnerCall { f := &SetOwnerCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetOwner)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GetFactor(ctx wasmlib.ScViewCallContext) *GetFactorCall { f := &GetFactorCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetFactor)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetOwner(ctx wasmlib.ScViewCallContext) *GetOwnerCall { f := &GetOwnerCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetOwner)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/dividend/go/dividend/dividend.go b/contracts/wasm/dividend/go/dividend/dividend.go index 7752295c0d..c397b30f97 100644 --- a/contracts/wasm/dividend/go/dividend/dividend.go +++ b/contracts/wasm/dividend/go/dividend/dividend.go @@ -15,7 +15,8 @@ package dividend import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) // 'init' is used as a way to initialize a smart contract. It is an optional @@ -31,7 +32,7 @@ func funcInit(ctx wasmlib.ScFuncContext, f *InitContext) { // First we set up a default value for the owner in case the optional // 'owner' parameter was omitted. - var owner wasmlib.ScAgentID = ctx.ContractCreator() + var owner wasmtypes.ScAgentID = ctx.ContractCreator() // Now we check if the optional 'owner' parameter is present in the params map. if f.Params.Owner().Exists() { @@ -64,33 +65,24 @@ func funcMember(ctx wasmlib.ScFuncContext, f *MemberContext) { // So once we get to this point in the code we can take that as a given. // Since we are sure that the 'factor' parameter actually exists we can - // retrieve its actual value into an int64. Note that we use Go's built-in + // retrieve its actual value into an uint64. Note that we use Go's built-in // data types when manipulating Int64, String, or Bytes value objects. - var factor int64 = f.Params.Factor().Value() - - // As an extra requirement we check that the 'factor' parameter value is not - // negative. If it is, we panic out with an error message. - // Note how we avoid an if expression like this one here: - // if factor < 0 { - // ctx.Panic("negative factor") - // } - // Using the require() method instead reduces typing and enhances readability. - ctx.Require(factor >= 0, "negative factor") + var factor uint64 = f.Params.Factor().Value() // Since we are sure that the 'address' parameter actually exists we can // retrieve its actual value into an ScAddress value type. - var address wasmlib.ScAddress = f.Params.Address().Value() + var address wasmtypes.ScAddress = f.Params.Address().Value() // We will store the address/factor combinations in a key/value sub-map of the // state storage named 'members'. The schema tool has generated an appropriately // type-checked proxy map for us from the schema.json state storage definition. // If there is no 'members' map present yet in state storage an empty map will // automatically be created on the host. - var members MapAddressToMutableInt64 = f.State.Members() + var members MapAddressToMutableUint64 = f.State.Members() - // Now we create an ScMutableInt64 proxy for the value stored in the 'members' + // Now we create an ScMutableUint64 proxy for the value stored in the 'members' // map under the key defined by the 'address' parameter we retrieved earlier. - var currentFactor wasmlib.ScMutableInt64 = members.GetInt64(address) + var currentFactor wasmtypes.ScMutableUint64 = members.GetUint64(address) // We check to see if this key/value combination exists in the 'members' map. if !currentFactor.Exists() { @@ -102,12 +94,9 @@ func funcMember(ctx wasmlib.ScFuncContext, f *MemberContext) { var memberList ArrayOfMutableAddress = f.State.MemberList() // Now we will append the new address to the memberList array. - // First we determine the current length of the array. - var length int32 = memberList.Length() - - // Next we create an ScMutableAddress proxy to the address value that lives - // at that index in the memberList array (no value, since we're appending). - var newAddress wasmlib.ScMutableAddress = memberList.GetAddress(length) + // We create an ScMutableAddress proxy to an address value that lives + // at the end of the memberList array (no value yet, since we're appending). + var newAddress wasmtypes.ScMutableAddress = memberList.AppendAddress() // And finally we append the new address to the array by telling the proxy // to update the value it refers to with the 'address' parameter. @@ -117,10 +106,10 @@ func funcMember(ctx wasmlib.ScFuncContext, f *MemberContext) { // memberList.GetAddress(memberList.Length()).SetValue(&address) } - // Create an ScMutableInt64 proxy named 'totalFactor' for an Int64 value in + // Create an ScMutableUint64 proxy named 'totalFactor' for an Uint64 value in // state storage. Note that we don't care whether this value exists or not, // because WasmLib will treat it as if it has the default value of zero. - var totalFactor wasmlib.ScMutableInt64 = f.State.TotalFactor() + var totalFactor wasmtypes.ScMutableUint64 = f.State.TotalFactor() // Now we calculate the new running total sum of factors by first getting the // current value of 'totalFactor' from the state storage, then subtracting the @@ -128,7 +117,7 @@ func funcMember(ctx wasmlib.ScFuncContext, f *MemberContext) { // exists. Again, if the associated value doesn't exist, WasmLib will assume it // to be zero. Finally we add the factor retrieved from the parameters, // resulting in the new totalFactor. - var newTotalFactor int64 = totalFactor.Value() - currentFactor.Value() + factor + var newTotalFactor uint64 = totalFactor.Value() - currentFactor.Value() + factor // Now we store the new totalFactor in the state storage. totalFactor.SetValue(newTotalFactor) @@ -154,31 +143,31 @@ func funcDivide(ctx wasmlib.ScFuncContext, f *DivideContext) { var balances wasmlib.ScBalances = ctx.Balances() // Retrieve the amount of plain iota tokens from the account balance - var amount int64 = balances.Balance(wasmlib.IOTA) + var amount uint64 = balances.Balance(wasmtypes.IOTA) // Retrieve the pre-calculated totalFactor value from the state storage. - var totalFactor int64 = f.State.TotalFactor().Value() + var totalFactor uint64 = f.State.TotalFactor().Value() // Get the proxy to the 'members' map in the state storage. - var members MapAddressToMutableInt64 = f.State.Members() + var members MapAddressToMutableUint64 = f.State.Members() // Get the proxy to the 'memberList' array in the state storage. var memberList ArrayOfMutableAddress = f.State.MemberList() // Determine the current length of the memberList array. - var size int32 = memberList.Length() + var size uint32 = memberList.Length() // Loop through all indexes of the memberList array. - for i := int32(0); i < size; i++ { + for i := uint32(0); i < size; i++ { // Retrieve the next indexed address from the memberList array. - var address wasmlib.ScAddress = memberList.GetAddress(i).Value() + var address wasmtypes.ScAddress = memberList.GetAddress(i).Value() // Retrieve the factor associated with the address from the members map. - var factor int64 = members.GetInt64(address).Value() + var factor uint64 = members.GetUint64(address).Value() // Calculate the fair share of iotas to disperse to this member based on the // factor we just retrieved. Note that the result will been truncated. - var share int64 = amount * factor / totalFactor + var share uint64 = amount * factor / totalFactor // Is there anything to disperse to this member? if share > 0 { @@ -194,7 +183,7 @@ func funcDivide(ctx wasmlib.ScFuncContext, f *DivideContext) { // member address. The transfer_to_address() method receives the address // value and the proxy to the new transfers map on the host, and will // call the corresponding host sandbox function with these values. - ctx.TransferToAddress(address, transfers) + ctx.Send(address, transfers) } } } @@ -218,15 +207,15 @@ func funcSetOwner(ctx wasmlib.ScFuncContext, f *SetOwnerContext) { func viewGetFactor(ctx wasmlib.ScViewContext, f *GetFactorContext) { // Since we are sure that the 'address' parameter actually exists we can // retrieve its actual value into an ScAddress value type. - var address wasmlib.ScAddress = f.Params.Address().Value() + var address wasmtypes.ScAddress = f.Params.Address().Value() // Create an ScImmutableMap proxy to the 'members' map in the state storage. // Note that for views this is an *immutable* map as opposed to the *mutable* // map we can access from the *mutable* state that gets passed to funcs. - var members MapAddressToImmutableInt64 = f.State.Members() + var members MapAddressToImmutableUint64 = f.State.Members() // Retrieve the factor associated with the address parameter. - var factor int64 = members.GetInt64(address).Value() + var factor uint64 = members.GetUint64(address).Value() // Set the factor in the results map of the function context. // The contents of this results map is returned to the caller of the function. diff --git a/contracts/wasm/dividend/go/dividend/keys.go b/contracts/wasm/dividend/go/dividend/keys.go deleted file mode 100644 index d195ce5296..0000000000 --- a/contracts/wasm/dividend/go/dividend/keys.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package dividend - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamAddress = 0 - IdxParamFactor = 1 - IdxParamOwner = 2 - - IdxResultFactor = 3 - IdxResultOwner = 4 - - IdxStateMemberList = 5 - IdxStateMembers = 6 - IdxStateOwner = 7 - IdxStateTotalFactor = 8 -) - -const keyMapLen = 9 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamAddress, - ParamFactor, - ParamOwner, - ResultFactor, - ResultOwner, - StateMemberList, - StateMembers, - StateOwner, - StateTotalFactor, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/dividend/go/dividend/lib.go b/contracts/wasm/dividend/go/dividend/lib.go index ea83c8abb5..860fe4660f 100644 --- a/contracts/wasm/dividend/go/dividend/lib.go +++ b/contracts/wasm/dividend/go/dividend/lib.go @@ -7,20 +7,36 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncDivide, funcDivideThunk) - exports.AddFunc(FuncInit, funcInitThunk) - exports.AddFunc(FuncMember, funcMemberThunk) - exports.AddFunc(FuncSetOwner, funcSetOwnerThunk) - exports.AddView(ViewGetFactor, viewGetFactorThunk) - exports.AddView(ViewGetOwner, viewGetOwnerThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncDivide, + FuncInit, + FuncMember, + FuncSetOwner, + ViewGetFactor, + ViewGetOwner, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcDivideThunk, + funcInitThunk, + funcMemberThunk, + funcSetOwnerThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetFactorThunk, + viewGetOwnerThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type DivideContext struct { @@ -31,7 +47,7 @@ func funcDivideThunk(ctx wasmlib.ScFuncContext) { ctx.Log("dividend.funcDivide") f := &DivideContext{ State: MutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcDivide(ctx, f) @@ -47,10 +63,10 @@ func funcInitThunk(ctx wasmlib.ScFuncContext) { ctx.Log("dividend.funcInit") f := &InitContext{ Params: ImmutableInitParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcInit(ctx, f) @@ -64,20 +80,20 @@ type MemberContext struct { func funcMemberThunk(ctx wasmlib.ScFuncContext) { ctx.Log("dividend.funcMember") - - // only defined owner of contract can add members - access := ctx.State().GetAgentID(wasmlib.Key("owner")) - ctx.Require(access.Exists(), "access not set: owner") - ctx.Require(ctx.Caller() == access.Value(), "no permission") - f := &MemberContext{ Params: ImmutableMemberParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only defined owner of contract can add members + access := f.State.Owner() + ctx.Require(access.Exists(), "access not set: owner") + ctx.Require(ctx.Caller() == access.Value(), "no permission") + ctx.Require(f.Params.Address().Exists(), "missing mandatory address") ctx.Require(f.Params.Factor().Exists(), "missing mandatory factor") funcMember(ctx, f) @@ -91,20 +107,20 @@ type SetOwnerContext struct { func funcSetOwnerThunk(ctx wasmlib.ScFuncContext) { ctx.Log("dividend.funcSetOwner") - - // only defined owner of contract can change owner - access := ctx.State().GetAgentID(wasmlib.Key("owner")) - ctx.Require(access.Exists(), "access not set: owner") - ctx.Require(ctx.Caller() == access.Value(), "no permission") - f := &SetOwnerContext{ Params: ImmutableSetOwnerParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only defined owner of contract can change owner + access := f.State.Owner() + ctx.Require(access.Exists(), "access not set: owner") + ctx.Require(ctx.Caller() == access.Value(), "no permission") + ctx.Require(f.Params.Owner().Exists(), "missing mandatory owner") funcSetOwner(ctx, f) ctx.Log("dividend.funcSetOwner ok") @@ -118,19 +134,21 @@ type GetFactorContext struct { func viewGetFactorThunk(ctx wasmlib.ScViewContext) { ctx.Log("dividend.viewGetFactor") + results := wasmlib.NewScDict() f := &GetFactorContext{ Params: ImmutableGetFactorParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableGetFactorResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Address().Exists(), "missing mandatory address") viewGetFactor(ctx, f) + ctx.Results(results) ctx.Log("dividend.viewGetFactor ok") } @@ -141,14 +159,16 @@ type GetOwnerContext struct { func viewGetOwnerThunk(ctx wasmlib.ScViewContext) { ctx.Log("dividend.viewGetOwner") + results := wasmlib.NewScDict() f := &GetOwnerContext{ Results: MutableGetOwnerResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableDividendState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetOwner(ctx, f) + ctx.Results(results) ctx.Log("dividend.viewGetOwner ok") } diff --git a/contracts/wasm/dividend/go/dividend/params.go b/contracts/wasm/dividend/go/dividend/params.go index 55d5460569..3e5c7c3513 100644 --- a/contracts/wasm/dividend/go/dividend/params.go +++ b/contracts/wasm/dividend/go/dividend/params.go @@ -7,76 +7,76 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableInitParams) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, idxMap[IdxParamOwner]) +func (s ImmutableInitParams) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOwner)) } type MutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableInitParams) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, idxMap[IdxParamOwner]) +func (s MutableInitParams) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOwner)) } type ImmutableMemberParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMemberParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutableMemberParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } -func (s ImmutableMemberParams) Factor() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamFactor)) +func (s ImmutableMemberParams) Factor() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamFactor)) } type MutableMemberParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMemberParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutableMemberParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } -func (s MutableMemberParams) Factor() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamFactor)) +func (s MutableMemberParams) Factor() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamFactor)) } type ImmutableSetOwnerParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSetOwnerParams) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s ImmutableSetOwnerParams) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOwner)) } type MutableSetOwnerParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSetOwnerParams) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s MutableSetOwnerParams) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOwner)) } type ImmutableGetFactorParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetFactorParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutableGetFactorParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } type MutableGetFactorParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetFactorParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutableGetFactorParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } diff --git a/contracts/wasm/dividend/go/dividend/results.go b/contracts/wasm/dividend/go/dividend/results.go index 987b0fec57..963b7b9208 100644 --- a/contracts/wasm/dividend/go/dividend/results.go +++ b/contracts/wasm/dividend/go/dividend/results.go @@ -7,36 +7,36 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableGetFactorResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetFactorResults) Factor() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultFactor)) +func (s ImmutableGetFactorResults) Factor() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultFactor)) } type MutableGetFactorResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetFactorResults) Factor() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultFactor)) +func (s MutableGetFactorResults) Factor() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultFactor)) } type ImmutableGetOwnerResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetOwnerResults) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultOwner)) +func (s ImmutableGetOwnerResults) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultOwner)) } type MutableGetOwnerResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetOwnerResults) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultOwner)) +func (s MutableGetOwnerResults) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultOwner)) } diff --git a/contracts/wasm/dividend/go/dividend/state.go b/contracts/wasm/dividend/go/dividend/state.go index b63408d3a3..8473370307 100644 --- a/contracts/wasm/dividend/go/dividend/state.go +++ b/contracts/wasm/dividend/go/dividend/state.go @@ -7,80 +7,82 @@ package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableAddress struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableAddress) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableAddress) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableAddress) GetAddress(index int32) wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(a.objID, wasmlib.Key32(index)) +func (a ArrayOfImmutableAddress) GetAddress(index uint32) wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(a.proxy.Index(index)) } -type MapAddressToImmutableInt64 struct { - objID int32 +type MapAddressToImmutableUint64 struct { + proxy wasmtypes.Proxy } -func (m MapAddressToImmutableInt64) GetInt64(key wasmlib.ScAddress) wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(m.objID, key.KeyID()) +func (m MapAddressToImmutableUint64) GetUint64(key wasmtypes.ScAddress) wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(m.proxy.Key(wasmtypes.AddressToBytes(key))) } type ImmutableDividendState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableDividendState) MemberList() ArrayOfImmutableAddress { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMemberList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_ADDRESS) - return ArrayOfImmutableAddress{objID: arrID} + return ArrayOfImmutableAddress{proxy: s.proxy.Root(StateMemberList)} } -func (s ImmutableDividendState) Members() MapAddressToImmutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMembers), wasmlib.TYPE_MAP) - return MapAddressToImmutableInt64{objID: mapID} +func (s ImmutableDividendState) Members() MapAddressToImmutableUint64 { + return MapAddressToImmutableUint64{proxy: s.proxy.Root(StateMembers)} } -func (s ImmutableDividendState) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(StateOwner)) +func (s ImmutableDividendState) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(StateOwner)) } -func (s ImmutableDividendState) TotalFactor() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateTotalFactor)) +func (s ImmutableDividendState) TotalFactor() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateTotalFactor)) } type ArrayOfMutableAddress struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableAddress) AppendAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(a.proxy.Append()) } func (a ArrayOfMutableAddress) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableAddress) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableAddress) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableAddress) GetAddress(index int32) wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(a.objID, wasmlib.Key32(index)) +func (a ArrayOfMutableAddress) GetAddress(index uint32) wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(a.proxy.Index(index)) } -type MapAddressToMutableInt64 struct { - objID int32 +type MapAddressToMutableUint64 struct { + proxy wasmtypes.Proxy } -func (m MapAddressToMutableInt64) Clear() { - wasmlib.Clear(m.objID) +func (m MapAddressToMutableUint64) Clear() { + m.proxy.ClearMap() } -func (m MapAddressToMutableInt64) GetInt64(key wasmlib.ScAddress) wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(m.objID, key.KeyID()) +func (m MapAddressToMutableUint64) GetUint64(key wasmtypes.ScAddress) wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(m.proxy.Key(wasmtypes.AddressToBytes(key))) } type MutableDividendState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableDividendState) AsImmutable() ImmutableDividendState { @@ -88,19 +90,17 @@ func (s MutableDividendState) AsImmutable() ImmutableDividendState { } func (s MutableDividendState) MemberList() ArrayOfMutableAddress { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMemberList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_ADDRESS) - return ArrayOfMutableAddress{objID: arrID} + return ArrayOfMutableAddress{proxy: s.proxy.Root(StateMemberList)} } -func (s MutableDividendState) Members() MapAddressToMutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMembers), wasmlib.TYPE_MAP) - return MapAddressToMutableInt64{objID: mapID} +func (s MutableDividendState) Members() MapAddressToMutableUint64 { + return MapAddressToMutableUint64{proxy: s.proxy.Root(StateMembers)} } -func (s MutableDividendState) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(StateOwner)) +func (s MutableDividendState) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(StateOwner)) } -func (s MutableDividendState) TotalFactor() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateTotalFactor)) +func (s MutableDividendState) TotalFactor() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateTotalFactor)) } diff --git a/contracts/wasm/dividend/go/main.go b/contracts/wasm/dividend/go/main.go index 2b86f655a4..1c55a3a713 100644 --- a/contracts/wasm/dividend/go/main.go +++ b/contracts/wasm/dividend/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/dividend/go/dividend" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + dividend.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - dividend.OnLoad() + dividend.OnLoad(-1) } diff --git a/contracts/wasm/dividend/schema.yaml b/contracts/wasm/dividend/schema.yaml index 6b06220315..14e2f41a76 100644 --- a/contracts/wasm/dividend/schema.yaml +++ b/contracts/wasm/dividend/schema.yaml @@ -4,9 +4,9 @@ structs: {} typedefs: {} state: memberList: Address[] // array with all the recipients of this dividend - members: map[Address]Int64 // map with all the recipient factors of this dividend + members: map[Address]Uint64 // map with all the recipient factors of this dividend owner: AgentID // owner of contract, the only one who can call 'member' func - totalFactor: Int64 // sum of all recipient factors + totalFactor: Uint64 // sum of all recipient factors funcs: divide: {} init: @@ -16,7 +16,7 @@ funcs: access: owner // only defined owner of contract can add members params: address: Address // address of dividend recipient - factor: Int64 // relative division factor + factor: Uint64 // relative division factor setOwner: access: owner // only defined owner of contract can change owner params: @@ -26,7 +26,7 @@ views: params: address: Address // address of dividend recipient results: - factor: Int64 // relative division factor + factor: Uint64 // relative division factor getOwner: results: owner: AgentID // current owner of this smart contract diff --git a/contracts/wasm/dividend/src/contract.rs b/contracts/wasm/dividend/src/contract.rs index 794ea5c465..05adf83dbc 100644 --- a/contracts/wasm/dividend/src/contract.rs +++ b/contracts/wasm/dividend/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct DivideCall { pub func: ScFunc, @@ -49,55 +44,56 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn divide(_ctx: & dyn ScFuncCallContext) -> DivideCall { + pub fn divide(_ctx: &dyn ScFuncCallContext) -> DivideCall { DivideCall { func: ScFunc::new(HSC_NAME, HFUNC_DIVIDE), } } - pub fn init(_ctx: & dyn ScFuncCallContext) -> InitCall { + pub fn init(_ctx: &dyn ScFuncCallContext) -> InitCall { let mut f = InitCall { func: ScInitFunc::new(HSC_NAME, HFUNC_INIT), - params: MutableInitParams { id: 0 }, + params: MutableInitParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScInitFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn member(_ctx: & dyn ScFuncCallContext) -> MemberCall { + pub fn member(_ctx: &dyn ScFuncCallContext) -> MemberCall { let mut f = MemberCall { func: ScFunc::new(HSC_NAME, HFUNC_MEMBER), - params: MutableMemberParams { id: 0 }, + params: MutableMemberParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_owner(_ctx: & dyn ScFuncCallContext) -> SetOwnerCall { + pub fn set_owner(_ctx: &dyn ScFuncCallContext) -> SetOwnerCall { let mut f = SetOwnerCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_OWNER), - params: MutableSetOwnerParams { id: 0 }, + params: MutableSetOwnerParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn get_factor(_ctx: & dyn ScViewCallContext) -> GetFactorCall { + pub fn get_factor(_ctx: &dyn ScViewCallContext) -> GetFactorCall { let mut f = GetFactorCall { func: ScView::new(HSC_NAME, HVIEW_GET_FACTOR), - params: MutableGetFactorParams { id: 0 }, - results: ImmutableGetFactorResults { id: 0 }, + params: MutableGetFactorParams { proxy: Proxy::nil() }, + results: ImmutableGetFactorResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_owner(_ctx: & dyn ScViewCallContext) -> GetOwnerCall { + pub fn get_owner(_ctx: &dyn ScViewCallContext) -> GetOwnerCall { let mut f = GetOwnerCall { func: ScView::new(HSC_NAME, HVIEW_GET_OWNER), - results: ImmutableGetOwnerResults { id: 0 }, + results: ImmutableGetOwnerResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/dividend/src/dividend.rs b/contracts/wasm/dividend/src/dividend.rs index 929463cca4..3baabb030f 100644 --- a/contracts/wasm/dividend/src/dividend.rs +++ b/contracts/wasm/dividend/src/dividend.rs @@ -55,7 +55,7 @@ pub fn func_init(ctx: &ScFuncContext, f: &InitContext) { // The 'member' function will save the address/factor combination in state storage // and also calculate and store a running sum of all factors so that the 'divide' // function can simply start using these precalculated values when called. -pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { +pub fn func_member(_ctx: &ScFuncContext, f: &MemberContext) { // Note that the schema tool has already dealt with making sure that this function // can only be called by the owner and that the required parameters are present. // So once we get to this point in the code we can take that as a given. @@ -63,16 +63,7 @@ pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { // Since we are sure that the 'factor' parameter actually exists we can // retrieve its actual value into an i64. Note that we use Rust's built-in // data types when manipulating Int64, String, or Bytes value objects. - let factor: i64 = f.params.factor().value(); - - // As an extra requirement we check that the 'factor' parameter value is not - // negative. If it is, we panic out with an error message. - // Note how we avoid an if expression like this one here: - // if factor < 0 { - // ctx.panic("negative factor"); - // } - // Using the require() method instead reduces typing and enhances readability. - ctx.require(factor >= 0, "negative factor"); + let factor: u64 = f.params.factor().value(); // Since we are sure that the 'address' parameter actually exists we can // retrieve its actual value into an ScAddress value type. @@ -83,11 +74,11 @@ pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { // type-checked proxy map for us from the schema.json state storage definition. // If there is no 'members' map present yet in state storage an empty map will // automatically be created on the host. - let members: MapAddressToMutableInt64 = f.state.members(); + let members: MapAddressToMutableUint64 = f.state.members(); - // Now we create an ScMutableInt64 proxy for the value stored in the 'members' + // Now we create an ScMutableUint64 proxy for the value stored in the 'members' // map under the key defined by the 'address' parameter we retrieved earlier. - let current_factor: ScMutableInt64 = members.get_int64(&address); + let current_factor: ScMutableUint64 = members.get_uint64(&address); // We check to see if this key/value combination exists in the 'members' map. if !current_factor.exists() { @@ -99,12 +90,9 @@ pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { let member_list: ArrayOfMutableAddress = f.state.member_list(); // Now we will append the new address to the memberList array. - // First we determine the current length of the array. - let length: i32 = member_list.length(); - - // Next we create an ScMutableAddress proxy to the address value that lives - // at that index in the memberList array (no value, since we're appending). - let new_address: ScMutableAddress = member_list.get_address(length); + // We create an ScMutableAddress proxy to an address value that lives + // at the end of the memberList array (no value yet, since we're appending). + let new_address: ScMutableAddress = member_list.append_address(); // And finally we append the new address to the array by telling the proxy // to update the value it refers to with the 'address' parameter. @@ -114,10 +102,10 @@ pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { // member_list.get_address(member_list.length()).set_value(&address); } - // Create an ScMutableInt64 proxy named 'totalFactor' for an Int64 value in + // Create an ScMutableUint64 proxy named 'totalFactor' for an Int64 value in // state storage. Note that we don't care whether this value exists or not, // because WasmLib will treat it as if it has the default value of zero. - let total_factor: ScMutableInt64 = f.state.total_factor(); + let total_factor: ScMutableUint64 = f.state.total_factor(); // Now we calculate the new running total sum of factors by first getting the // current value of 'totalFactor' from the state storage, then subtracting the @@ -125,7 +113,7 @@ pub fn func_member(ctx: &ScFuncContext, f: &MemberContext) { // exists. Again, if the associated value doesn't exist, WasmLib will assume it // to be zero. Finally we add the factor retrieved from the parameters, // resulting in the new totalFactor. - let new_total_factor: i64 = total_factor.value() - current_factor.value() + factor; + let new_total_factor: u64 = total_factor.value() - current_factor.value() + factor; // Now we store the new totalFactor in the state storage. total_factor.set_value(new_total_factor); @@ -152,19 +140,19 @@ pub fn func_divide(ctx: &ScFuncContext, f: &DivideContext) { let balances: ScBalances = ctx.balances(); // Retrieve the amount of plain iota tokens from the account balance. - let amount: i64 = balances.balance(&ScColor::IOTA); + let amount: u64 = balances.balance(&ScColor::IOTA); // Retrieve the pre-calculated totalFactor value from the state storage. - let total_factor: i64 = f.state.total_factor().value(); + let total_factor: u64 = f.state.total_factor().value(); // Get the proxy to the 'members' map in the state storage. - let members: MapAddressToMutableInt64 = f.state.members(); + let members: MapAddressToMutableUint64 = f.state.members(); // Get the proxy to the 'memberList' array in the state storage. let member_list: ArrayOfMutableAddress = f.state.member_list(); // Determine the current length of the memberList array. - let size: i32 = member_list.length(); + let size: u32 = member_list.length(); // Loop through all indexes of the memberList array. for i in 0..size { @@ -172,11 +160,11 @@ pub fn func_divide(ctx: &ScFuncContext, f: &DivideContext) { let address: ScAddress = member_list.get_address(i).value(); // Retrieve the factor associated with the address from the members map. - let factor: i64 = members.get_int64(&address).value(); + let factor: u64 = members.get_uint64(&address).value(); // Calculate the fair share of iotas to disperse to this member based on the // factor we just retrieved. Note that the result will be truncated. - let share: i64 = amount * factor / total_factor; + let share: u64 = amount * factor / total_factor; // Is there anything to disperse to this member? if share > 0 { @@ -192,7 +180,7 @@ pub fn func_divide(ctx: &ScFuncContext, f: &DivideContext) { // member address. The transfer_to_address() method receives the address // value and the proxy to the new transfers map on the host, and will // call the corresponding host sandbox function with these values. - ctx.transfer_to_address(&address, transfers); + ctx.send(&address, &transfers); } } } @@ -222,10 +210,10 @@ pub fn view_get_factor(_ctx: &ScViewContext, f: &GetFactorContext) { // Create an ScImmutableMap proxy to the 'members' map in the state storage. // Note that for views this is an *immutable* map as opposed to the *mutable* // map we can access from the *mutable* state that gets passed to funcs. - let members: MapAddressToImmutableInt64 = f.state.members(); + let members: MapAddressToImmutableUint64 = f.state.members(); // Retrieve the factor associated with the address parameter. - let factor: i64 = members.get_int64(&address).value(); + let factor: u64 = members.get_uint64(&address).value(); // Set the factor in the results map of the function context. // The contents of this results map is returned to the caller of the function. diff --git a/contracts/wasm/dividend/src/keys.rs b/contracts/wasm/dividend/src/keys.rs deleted file mode 100644 index f15d21bcd6..0000000000 --- a/contracts/wasm/dividend/src/keys.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_ADDRESS : usize = 0; -pub(crate) const IDX_PARAM_FACTOR : usize = 1; -pub(crate) const IDX_PARAM_OWNER : usize = 2; - -pub(crate) const IDX_RESULT_FACTOR : usize = 3; -pub(crate) const IDX_RESULT_OWNER : usize = 4; - -pub(crate) const IDX_STATE_MEMBER_LIST : usize = 5; -pub(crate) const IDX_STATE_MEMBERS : usize = 6; -pub(crate) const IDX_STATE_OWNER : usize = 7; -pub(crate) const IDX_STATE_TOTAL_FACTOR : usize = 8; - -pub const KEY_MAP_LEN: usize = 9; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_ADDRESS, - PARAM_FACTOR, - PARAM_OWNER, - RESULT_FACTOR, - RESULT_OWNER, - STATE_MEMBER_LIST, - STATE_MEMBERS, - STATE_OWNER, - STATE_TOTAL_FACTOR, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/dividend/src/lib.rs b/contracts/wasm/dividend/src/lib.rs index 58f053d384..ef99d10f89 100644 --- a/contracts/wasm/dividend/src/lib.rs +++ b/contracts/wasm/dividend/src/lib.rs @@ -10,37 +10,49 @@ use dividend::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; mod consts; mod contract; -mod keys; mod params; mod results; mod state; + mod dividend; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_DIVIDE, + FUNC_INIT, + FUNC_MEMBER, + FUNC_SET_OWNER, + VIEW_GET_FACTOR, + VIEW_GET_OWNER, + ], + funcs: &[ + func_divide_thunk, + func_init_thunk, + func_member_thunk, + func_set_owner_thunk, + ], + views: &[ + view_get_factor_thunk, + view_get_owner_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_DIVIDE, func_divide_thunk); - exports.add_func(FUNC_INIT, func_init_thunk); - exports.add_func(FUNC_MEMBER, func_member_thunk); - exports.add_func(FUNC_SET_OWNER, func_set_owner_thunk); - exports.add_view(VIEW_GET_FACTOR, view_get_factor_thunk); - exports.add_view(VIEW_GET_OWNER, view_get_owner_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct DivideContext { @@ -50,9 +62,7 @@ pub struct DivideContext { fn func_divide_thunk(ctx: &ScFuncContext) { ctx.log("dividend.funcDivide"); let f = DivideContext { - state: MutableDividendState { - id: OBJ_ID_STATE, - }, + state: MutableDividendState { proxy: state_proxy() }, }; func_divide(ctx, &f); ctx.log("dividend.funcDivide ok"); @@ -66,12 +76,8 @@ pub struct InitContext { fn func_init_thunk(ctx: &ScFuncContext) { ctx.log("dividend.funcInit"); let f = InitContext { - params: ImmutableInitParams { - id: OBJ_ID_PARAMS, - }, - state: MutableDividendState { - id: OBJ_ID_STATE, - }, + params: ImmutableInitParams { proxy: params_proxy() }, + state: MutableDividendState { proxy: state_proxy() }, }; func_init(ctx, &f); ctx.log("dividend.funcInit ok"); @@ -84,20 +90,16 @@ pub struct MemberContext { fn func_member_thunk(ctx: &ScFuncContext) { ctx.log("dividend.funcMember"); + let f = MemberContext { + params: ImmutableMemberParams { proxy: params_proxy() }, + state: MutableDividendState { proxy: state_proxy() }, + }; // only defined owner of contract can add members - let access = ctx.state().get_agent_id("owner"); + let access = f.state.owner(); ctx.require(access.exists(), "access not set: owner"); ctx.require(ctx.caller() == access.value(), "no permission"); - let f = MemberContext { - params: ImmutableMemberParams { - id: OBJ_ID_PARAMS, - }, - state: MutableDividendState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.factor().exists(), "missing mandatory factor"); func_member(ctx, &f); @@ -111,20 +113,16 @@ pub struct SetOwnerContext { fn func_set_owner_thunk(ctx: &ScFuncContext) { ctx.log("dividend.funcSetOwner"); + let f = SetOwnerContext { + params: ImmutableSetOwnerParams { proxy: params_proxy() }, + state: MutableDividendState { proxy: state_proxy() }, + }; // only defined owner of contract can change owner - let access = ctx.state().get_agent_id("owner"); + let access = f.state.owner(); ctx.require(access.exists(), "access not set: owner"); ctx.require(ctx.caller() == access.value(), "no permission"); - let f = SetOwnerContext { - params: ImmutableSetOwnerParams { - id: OBJ_ID_PARAMS, - }, - state: MutableDividendState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.owner().exists(), "missing mandatory owner"); func_set_owner(ctx, &f); ctx.log("dividend.funcSetOwner ok"); @@ -139,18 +137,13 @@ pub struct GetFactorContext { fn view_get_factor_thunk(ctx: &ScViewContext) { ctx.log("dividend.viewGetFactor"); let f = GetFactorContext { - params: ImmutableGetFactorParams { - id: OBJ_ID_PARAMS, - }, - results: MutableGetFactorResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableDividendState { - id: OBJ_ID_STATE, - }, + params: ImmutableGetFactorParams { proxy: params_proxy() }, + results: MutableGetFactorResults { proxy: results_proxy() }, + state: ImmutableDividendState { proxy: state_proxy() }, }; ctx.require(f.params.address().exists(), "missing mandatory address"); view_get_factor(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("dividend.viewGetFactor ok"); } @@ -162,13 +155,10 @@ pub struct GetOwnerContext { fn view_get_owner_thunk(ctx: &ScViewContext) { ctx.log("dividend.viewGetOwner"); let f = GetOwnerContext { - results: MutableGetOwnerResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableDividendState { - id: OBJ_ID_STATE, - }, + results: MutableGetOwnerResults { proxy: results_proxy() }, + state: ImmutableDividendState { proxy: state_proxy() }, }; view_get_owner(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("dividend.viewGetOwner ok"); } diff --git a/contracts/wasm/dividend/src/params.rs b/contracts/wasm/dividend/src/params.rs index abea99eece..616425efe4 100644 --- a/contracts/wasm/dividend/src/params.rs +++ b/contracts/wasm/dividend/src/params.rs @@ -9,103 +9,100 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableInitParams { pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, idx_map(IDX_PARAM_OWNER)) + ScImmutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableInitParams { pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, idx_map(IDX_PARAM_OWNER)) + ScMutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMemberParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMemberParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } - pub fn factor(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_FACTOR.get_key_id()) + pub fn factor(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_FACTOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMemberParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMemberParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } - pub fn factor(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_FACTOR.get_key_id()) + pub fn factor(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_FACTOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetOwnerParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetOwnerParams { pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetOwnerParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetOwnerParams { pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetFactorParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetFactorParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetFactorParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetFactorParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } } diff --git a/contracts/wasm/dividend/src/results.rs b/contracts/wasm/dividend/src/results.rs index 9e6680e864..c380d19b56 100644 --- a/contracts/wasm/dividend/src/results.rs +++ b/contracts/wasm/dividend/src/results.rs @@ -9,51 +9,48 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetFactorResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetFactorResults { - pub fn factor(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_FACTOR.get_key_id()) + pub fn factor(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_FACTOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetFactorResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetFactorResults { - pub fn factor(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_FACTOR.get_key_id()) + pub fn factor(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_FACTOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetOwnerResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetOwnerResults { pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetOwnerResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetOwnerResults { pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_OWNER)) } } diff --git a/contracts/wasm/dividend/src/state.rs b/contracts/wasm/dividend/src/state.rs index 4cb5424635..0618671e5b 100644 --- a/contracts/wasm/dividend/src/state.rs +++ b/contracts/wasm/dividend/src/state.rs @@ -9,121 +9,119 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableAddress { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableAddress { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_address(&self, index: i32) -> ScImmutableAddress { - ScImmutableAddress::new(self.obj_id, Key32(index)) + pub fn get_address(&self, index: u32) -> ScImmutableAddress { + ScImmutableAddress::new(self.proxy.index(index)) } } -#[derive(Clone, Copy)] -pub struct MapAddressToImmutableInt64 { - pub(crate) obj_id: i32, +#[derive(Clone)] +pub struct MapAddressToImmutableUint64 { + pub(crate) proxy: Proxy, } -impl MapAddressToImmutableInt64 { - pub fn get_int64(&self, key: &ScAddress) -> ScImmutableInt64 { - ScImmutableInt64::new(self.obj_id, key.get_key_id()) +impl MapAddressToImmutableUint64 { + pub fn get_uint64(&self, key: &ScAddress) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.key(&address_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDividendState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDividendState { pub fn member_list(&self) -> ArrayOfImmutableAddress { - let arr_id = get_object_id(self.id, STATE_MEMBER_LIST.get_key_id(), TYPE_ARRAY | TYPE_ADDRESS); - ArrayOfImmutableAddress { obj_id: arr_id } + ArrayOfImmutableAddress { proxy: self.proxy.root(STATE_MEMBER_LIST) } } - pub fn members(&self) -> MapAddressToImmutableInt64 { - let map_id = get_object_id(self.id, STATE_MEMBERS.get_key_id(), TYPE_MAP); - MapAddressToImmutableInt64 { obj_id: map_id } + pub fn members(&self) -> MapAddressToImmutableUint64 { + MapAddressToImmutableUint64 { proxy: self.proxy.root(STATE_MEMBERS) } } pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, STATE_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(STATE_OWNER)) } - pub fn total_factor(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_TOTAL_FACTOR.get_key_id()) + pub fn total_factor(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_TOTAL_FACTOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableAddress { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableAddress { - pub fn clear(&self) { - clear(self.obj_id); + pub fn append_address(&self) -> ScMutableAddress { + ScMutableAddress::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_address(&self, index: i32) -> ScMutableAddress { - ScMutableAddress::new(self.obj_id, Key32(index)) + pub fn get_address(&self, index: u32) -> ScMutableAddress { + ScMutableAddress::new(self.proxy.index(index)) } } -#[derive(Clone, Copy)] -pub struct MapAddressToMutableInt64 { - pub(crate) obj_id: i32, +#[derive(Clone)] +pub struct MapAddressToMutableUint64 { + pub(crate) proxy: Proxy, } -impl MapAddressToMutableInt64 { +impl MapAddressToMutableUint64 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } - pub fn get_int64(&self, key: &ScAddress) -> ScMutableInt64 { - ScMutableInt64::new(self.obj_id, key.get_key_id()) + pub fn get_uint64(&self, key: &ScAddress) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.key(&address_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDividendState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDividendState { pub fn as_immutable(&self) -> ImmutableDividendState { - ImmutableDividendState { id: self.id } + ImmutableDividendState { proxy: self.proxy.root("") } } pub fn member_list(&self) -> ArrayOfMutableAddress { - let arr_id = get_object_id(self.id, STATE_MEMBER_LIST.get_key_id(), TYPE_ARRAY | TYPE_ADDRESS); - ArrayOfMutableAddress { obj_id: arr_id } + ArrayOfMutableAddress { proxy: self.proxy.root(STATE_MEMBER_LIST) } } - pub fn members(&self) -> MapAddressToMutableInt64 { - let map_id = get_object_id(self.id, STATE_MEMBERS.get_key_id(), TYPE_MAP); - MapAddressToMutableInt64 { obj_id: map_id } + pub fn members(&self) -> MapAddressToMutableUint64 { + MapAddressToMutableUint64 { proxy: self.proxy.root(STATE_MEMBERS) } } pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, STATE_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(STATE_OWNER)) } - pub fn total_factor(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_TOTAL_FACTOR.get_key_id()) + pub fn total_factor(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_TOTAL_FACTOR)) } } diff --git a/contracts/wasm/dividend/test/dividend_bg.wasm b/contracts/wasm/dividend/test/dividend_bg.wasm index d7848e5e3c..e658cd8185 100644 Binary files a/contracts/wasm/dividend/test/dividend_bg.wasm and b/contracts/wasm/dividend/test/dividend_bg.wasm differ diff --git a/contracts/wasm/dividend/test/dividend_test.go b/contracts/wasm/dividend/test/dividend_test.go index 919a41df64..f7da833e81 100644 --- a/contracts/wasm/dividend/test/dividend_test.go +++ b/contracts/wasm/dividend/test/dividend_test.go @@ -4,28 +4,27 @@ package test import ( - "strings" "testing" "github.com/iotaledger/wasp/contracts/wasm/dividend/go/dividend" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) -func dividendMember(ctx *wasmsolo.SoloContext, agent *wasmsolo.SoloAgent, factor int64) { +func dividendMember(ctx *wasmsolo.SoloContext, agent *wasmsolo.SoloAgent, factor uint64) { member := dividend.ScFuncs.Member(ctx) member.Params.Address().SetValue(agent.ScAddress()) member.Params.Factor().SetValue(factor) - member.Func.TransferIotas(1).Post() + member.Func.Post() } -func dividendDivide(ctx *wasmsolo.SoloContext, amount int64) { +func dividendDivide(ctx *wasmsolo.SoloContext, amount uint64) { divide := dividend.ScFuncs.Divide(ctx) divide.Func.TransferIotas(amount).Post() } -func dividendGetFactor(ctx *wasmsolo.SoloContext, member *wasmsolo.SoloAgent) int64 { +func dividendGetFactor(ctx *wasmsolo.SoloContext, member *wasmsolo.SoloAgent) uint64 { getFactor := dividend.ScFuncs.GetFactor(ctx) getFactor.Params.Address().SetValue(member.ScAddress()) getFactor.Func.Call() @@ -51,9 +50,9 @@ func TestAddMemberFailMissingAddress(t *testing.T) { member := dividend.ScFuncs.Member(ctx) member.Params.Factor().SetValue(100) - member.Func.TransferIotas(1).Post() + member.Func.Post() require.Error(t, ctx.Err) - require.True(t, strings.HasSuffix(ctx.Err.Error(), "missing mandatory address")) + require.Contains(t, ctx.Err.Error(), "missing mandatory address") } func TestAddMemberFailMissingFactor(t *testing.T) { @@ -62,9 +61,9 @@ func TestAddMemberFailMissingFactor(t *testing.T) { member1 := ctx.NewSoloAgent() member := dividend.ScFuncs.Member(ctx) member.Params.Address().SetValue(member1.ScAddress()) - member.Func.TransferIotas(1).Post() + member.Func.Post() require.Error(t, ctx.Err) - require.True(t, strings.HasSuffix(ctx.Err.Error(), "missing mandatory factor")) + require.Contains(t, ctx.Err.Error(), "missing mandatory factor") } func TestDivide1Member(t *testing.T) { diff --git a/contracts/wasm/dividend/ts/dividend/consts.ts b/contracts/wasm/dividend/ts/dividend/consts.ts index 4368c1405e..1d3cf98eee 100644 --- a/contracts/wasm/dividend/ts/dividend/consts.ts +++ b/contracts/wasm/dividend/ts/dividend/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "dividend"; export const ScDescription = "Simple dividend smart contract"; -export const HScName = new wasmlib.ScHname(0xcce2e239); +export const HScName = new wasmtypes.ScHname(0xcce2e239); export const ParamAddress = "address"; export const ParamFactor = "factor"; @@ -30,9 +30,9 @@ export const FuncSetOwner = "setOwner"; export const ViewGetFactor = "getFactor"; export const ViewGetOwner = "getOwner"; -export const HFuncDivide = new wasmlib.ScHname(0xc7878107); -export const HFuncInit = new wasmlib.ScHname(0x1f44d644); -export const HFuncMember = new wasmlib.ScHname(0xc07da2cb); -export const HFuncSetOwner = new wasmlib.ScHname(0x2a15fe7b); -export const HViewGetFactor = new wasmlib.ScHname(0x0ee668fe); -export const HViewGetOwner = new wasmlib.ScHname(0x137107a6); +export const HFuncDivide = new wasmtypes.ScHname(0xc7878107); +export const HFuncInit = new wasmtypes.ScHname(0x1f44d644); +export const HFuncMember = new wasmtypes.ScHname(0xc07da2cb); +export const HFuncSetOwner = new wasmtypes.ScHname(0x2a15fe7b); +export const HViewGetFactor = new wasmtypes.ScHname(0x0ee668fe); +export const HViewGetOwner = new wasmtypes.ScHname(0x137107a6); diff --git a/contracts/wasm/dividend/ts/dividend/contract.ts b/contracts/wasm/dividend/ts/dividend/contract.ts index 929d85e4ac..02296cb0ea 100644 --- a/contracts/wasm/dividend/ts/dividend/contract.ts +++ b/contracts/wasm/dividend/ts/dividend/contract.ts @@ -13,93 +13,94 @@ export class DivideCall { } export class DivideContext { - state: sc.MutableDividendState = new sc.MutableDividendState(); + state: sc.MutableDividendState = new sc.MutableDividendState(wasmlib.ScState.proxy()); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); - params: sc.MutableInitParams = new sc.MutableInitParams(); + params: sc.MutableInitParams = new sc.MutableInitParams(wasmlib.ScView.nilProxy); } export class InitContext { - params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); - state: sc.MutableDividendState = new sc.MutableDividendState(); + params: sc.ImmutableInitParams = new sc.ImmutableInitParams(wasmlib.paramsProxy()); + state: sc.MutableDividendState = new sc.MutableDividendState(wasmlib.ScState.proxy()); } export class MemberCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMember); - params: sc.MutableMemberParams = new sc.MutableMemberParams(); + params: sc.MutableMemberParams = new sc.MutableMemberParams(wasmlib.ScView.nilProxy); } export class MemberContext { - params: sc.ImmutableMemberParams = new sc.ImmutableMemberParams(); - state: sc.MutableDividendState = new sc.MutableDividendState(); + params: sc.ImmutableMemberParams = new sc.ImmutableMemberParams(wasmlib.paramsProxy()); + state: sc.MutableDividendState = new sc.MutableDividendState(wasmlib.ScState.proxy()); } export class SetOwnerCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetOwner); - params: sc.MutableSetOwnerParams = new sc.MutableSetOwnerParams(); + params: sc.MutableSetOwnerParams = new sc.MutableSetOwnerParams(wasmlib.ScView.nilProxy); } export class SetOwnerContext { - params: sc.ImmutableSetOwnerParams = new sc.ImmutableSetOwnerParams(); - state: sc.MutableDividendState = new sc.MutableDividendState(); + params: sc.ImmutableSetOwnerParams = new sc.ImmutableSetOwnerParams(wasmlib.paramsProxy()); + state: sc.MutableDividendState = new sc.MutableDividendState(wasmlib.ScState.proxy()); } export class GetFactorCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetFactor); - params: sc.MutableGetFactorParams = new sc.MutableGetFactorParams(); - results: sc.ImmutableGetFactorResults = new sc.ImmutableGetFactorResults(); + params: sc.MutableGetFactorParams = new sc.MutableGetFactorParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetFactorResults = new sc.ImmutableGetFactorResults(wasmlib.ScView.nilProxy); } export class GetFactorContext { - params: sc.ImmutableGetFactorParams = new sc.ImmutableGetFactorParams(); - results: sc.MutableGetFactorResults = new sc.MutableGetFactorResults(); - state: sc.ImmutableDividendState = new sc.ImmutableDividendState(); + params: sc.ImmutableGetFactorParams = new sc.ImmutableGetFactorParams(wasmlib.paramsProxy()); + results: sc.MutableGetFactorResults = new sc.MutableGetFactorResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableDividendState = new sc.ImmutableDividendState(wasmlib.ScState.proxy()); } export class GetOwnerCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetOwner); - results: sc.ImmutableGetOwnerResults = new sc.ImmutableGetOwnerResults(); + results: sc.ImmutableGetOwnerResults = new sc.ImmutableGetOwnerResults(wasmlib.ScView.nilProxy); } export class GetOwnerContext { - results: sc.MutableGetOwnerResults = new sc.MutableGetOwnerResults(); - state: sc.ImmutableDividendState = new sc.ImmutableDividendState(); + results: sc.MutableGetOwnerResults = new sc.MutableGetOwnerResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableDividendState = new sc.ImmutableDividendState(wasmlib.ScState.proxy()); } export class ScFuncs { - static divide(ctx: wasmlib.ScFuncCallContext): DivideCall { - return new DivideCall(); - } - - static init(ctx: wasmlib.ScFuncCallContext): InitCall { - let f = new InitCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static member(ctx: wasmlib.ScFuncCallContext): MemberCall { - let f = new MemberCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setOwner(ctx: wasmlib.ScFuncCallContext): SetOwnerCall { - let f = new SetOwnerCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static getFactor(ctx: wasmlib.ScViewCallContext): GetFactorCall { - let f = new GetFactorCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getOwner(ctx: wasmlib.ScViewCallContext): GetOwnerCall { - let f = new GetOwnerCall(); - f.func.setPtrs(null, f.results); - return f; - } + static divide(_ctx: wasmlib.ScFuncCallContext): DivideCall { + return new DivideCall(); + } + + static init(_ctx: wasmlib.ScFuncCallContext): InitCall { + const f = new InitCall(); + f.params = new sc.MutableInitParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static member(_ctx: wasmlib.ScFuncCallContext): MemberCall { + const f = new MemberCall(); + f.params = new sc.MutableMemberParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setOwner(_ctx: wasmlib.ScFuncCallContext): SetOwnerCall { + const f = new SetOwnerCall(); + f.params = new sc.MutableSetOwnerParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static getFactor(_ctx: wasmlib.ScViewCallContext): GetFactorCall { + const f = new GetFactorCall(); + f.params = new sc.MutableGetFactorParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetFactorResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getOwner(_ctx: wasmlib.ScViewCallContext): GetOwnerCall { + const f = new GetOwnerCall(); + f.results = new sc.ImmutableGetOwnerResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/dividend/ts/dividend/dividend.ts b/contracts/wasm/dividend/ts/dividend/dividend.ts index 62cd68dbca..11cbc72322 100644 --- a/contracts/wasm/dividend/ts/dividend/dividend.ts +++ b/contracts/wasm/dividend/ts/dividend/dividend.ts @@ -49,7 +49,7 @@ export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { // smart contract's 'divide' function. The 'member' function takes 2 parameters, // which are both required: // - 'address', which is an Address to use as member in the group, and -// - 'factor', which is an Int64 relative dispersal factor associated with +// - 'factor', which is an Uint64 relative dispersal factor associated with // that address // The 'member' function will save the address/factor combination in state storage // and also calculate and store a running sum of all factors so that the 'divide' @@ -60,18 +60,9 @@ export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): voi // So once we get to this point in the code we can take that as a given. // Since we are sure that the 'factor' parameter actually exists we can - // retrieve its actual value into an i64. Note that we use Rust's built-in - // data types when manipulating Int64, String, or Bytes value objects. - let factor: i64 = f.params.factor().value(); - - // As an extra requirement we check that the 'factor' parameter value is not - // negative. If it is, we panic out with an error message. - // Note how we avoid an if expression like this one here: - // if (factor < 0) { - // ctx.panic("negative factor"); - // } - // Using the require() method instead reduces typing and enhances readability. - ctx.require(factor >= 0, "negative factor"); + // retrieve its actual value into an u64. Note that we use Rust's built-in + // data types when manipulating Uint64, String, or Bytes value objects. + let factor: u64 = f.params.factor().value(); // Since we are sure that the 'address' parameter actually exists we can // retrieve its actual value into an ScAddress value type. @@ -82,11 +73,11 @@ export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): voi // type-checked proxy map for us from the schema.json state storage definition. // If there is no 'members' map present yet in state storage an empty map will // automatically be created on the host. - let members: sc.MapAddressToMutableInt64 = f.state.members(); + let members: sc.MapAddressToMutableUint64 = f.state.members(); - // Now we create an ScMutableInt64 proxy for the value stored in the 'members' + // Now we create an ScMutableUint64 proxy for the value stored in the 'members' // map under the key defined by the 'address' parameter we retrieved earlier. - let currentFactor: wasmlib.ScMutableInt64 = members.getInt64(address); + let currentFactor: wasmlib.ScMutableUint64 = members.getUint64(address); // We check to see if this key/value combination exists in the 'members' map. if (!currentFactor.exists()) { @@ -98,12 +89,9 @@ export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): voi let memberList: sc.ArrayOfMutableAddress = f.state.memberList(); // Now we will append the new address to the memberList array. - // First we determine the current length of the array. - let length: i32 = memberList.length(); - - // Next we create an ScMutableAddress proxy to the address value that lives - // at that index in the memberList array (no value, since we're appending). - let newAddress: wasmlib.ScMutableAddress = memberList.getAddress(length); + // We create an ScMutableAddress proxy to an address value that lives + // at the end of the memberList array (no value yet, since we're appending). + let newAddress: wasmlib.ScMutableAddress = memberList.appendAddress(); // And finally we append the new address to the array by telling the proxy // to update the value it refers to with the 'address' parameter. @@ -113,10 +101,10 @@ export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): voi // memberList.getAddress(memberList.length()).setValue(address); } - // Create an ScMutableInt64 proxy named 'totalFactor' for an Int64 value in + // Create an ScMutableUint64 proxy named 'totalFactor' for an Uint64 value in // state storage. Note that we don't care whether this value exists or not, // because WasmLib will treat it as if it has the default value of zero. - let totalFactor: wasmlib.ScMutableInt64 = f.state.totalFactor(); + let totalFactor: wasmlib.ScMutableUint64 = f.state.totalFactor(); // Now we calculate the new running total sum of factors by first getting the // current value of 'totalFactor' from the state storage, then subtracting the @@ -124,7 +112,7 @@ export function funcMember(ctx: wasmlib.ScFuncContext, f: sc.MemberContext): voi // exists. Again, if the associated value doesn't exist, WasmLib will assume it // to be zero. Finally we add the factor retrieved from the parameters, // resulting in the new totalFactor. - let newTotalFactor: i64 = totalFactor.value() - currentFactor.value() + factor; + let newTotalFactor: u64 = totalFactor.value() - currentFactor.value() + factor; // Now we store the new totalFactor in the state storage. totalFactor.setValue(newTotalFactor); @@ -151,31 +139,31 @@ export function funcDivide(ctx: wasmlib.ScFuncContext, f: sc.DivideContext): voi let balances: wasmlib.ScBalances = ctx.balances(); // Retrieve the amount of plain iota tokens from the account balance. - let amount: i64 = balances.balance(wasmlib.ScColor.IOTA); + let amount: u64 = balances.balance(wasmlib.IOTA); // Retrieve the pre-calculated totalFactor value from the state storage. - let totalFactor: i64 = f.state.totalFactor().value(); + let totalFactor: u64 = f.state.totalFactor().value(); // Get the proxy to the 'members' map in the state storage. - let members: sc.MapAddressToMutableInt64 = f.state.members(); + let members: sc.MapAddressToMutableUint64 = f.state.members(); // Get the proxy to the 'memberList' array in the state storage. let memberList: sc.ArrayOfMutableAddress = f.state.memberList(); // Determine the current length of the memberList array. - let size: i32 = memberList.length(); + let size: u32 = memberList.length(); // Loop through all indexes of the memberList array. - for (let i = 0; i < size; i++) { + for (let i: u32 = 0; i < size; i++) { // Retrieve the next indexed address from the memberList array. let address: wasmlib.ScAddress = memberList.getAddress(i).value(); // Retrieve the factor associated with the address from the members map. - let factor: i64 = members.getInt64(address).value(); + let factor: u64 = members.getUint64(address).value(); // Calculate the fair share of iotas to disperse to this member based on the // factor we just retrieved. Note that the result will be truncated. - let share: i64 = amount * factor / totalFactor; + let share: u64 = amount * factor / totalFactor; // Is there anything to disperse to this member? if (share > 0) { @@ -191,7 +179,7 @@ export function funcDivide(ctx: wasmlib.ScFuncContext, f: sc.DivideContext): voi // member address. The transferToAddress() method receives the address // value and the proxy to the new transfers map on the host, and will // call the corresponding host sandbox function with these values. - ctx.transferToAddress(address, transfers); + ctx.send(address, transfers); } } } @@ -221,10 +209,10 @@ export function viewGetFactor(ctx: wasmlib.ScViewContext, f: sc.GetFactorContext // Create an ScImmutableMap proxy to the 'members' map in the state storage. // Note that for views this is an *immutable* map as opposed to the *mutable* // map we can access from the *mutable* state that gets passed to funcs. - let members: sc.MapAddressToImmutableInt64 = f.state.members(); + let members: sc.MapAddressToImmutableUint64 = f.state.members(); // Retrieve the factor associated with the address parameter. - let factor: i64 = members.getInt64(address).value(); + let factor: u64 = members.getUint64(address).value(); // Set the factor in the results map of the function context. // The contents of this results map is returned to the caller of the function. diff --git a/contracts/wasm/dividend/ts/dividend/index.ts b/contracts/wasm/dividend/ts/dividend/index.ts index cf9a259fc4..f9071d3503 100644 --- a/contracts/wasm/dividend/ts/dividend/index.ts +++ b/contracts/wasm/dividend/ts/dividend/index.ts @@ -9,7 +9,6 @@ export * from "./dividend"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/dividend/ts/dividend/keys.ts b/contracts/wasm/dividend/ts/dividend/keys.ts deleted file mode 100644 index 8f3a026043..0000000000 --- a/contracts/wasm/dividend/ts/dividend/keys.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamAddress = 0; -export const IdxParamFactor = 1; -export const IdxParamOwner = 2; - -export const IdxResultFactor = 3; -export const IdxResultOwner = 4; - -export const IdxStateMemberList = 5; -export const IdxStateMembers = 6; -export const IdxStateOwner = 7; -export const IdxStateTotalFactor = 8; - -export let keyMap: string[] = [ - sc.ParamAddress, - sc.ParamFactor, - sc.ParamOwner, - sc.ResultFactor, - sc.ResultOwner, - sc.StateMemberList, - sc.StateMembers, - sc.StateOwner, - sc.StateTotalFactor, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/dividend/ts/dividend/lib.ts b/contracts/wasm/dividend/ts/dividend/lib.ts index 6d2710649e..e08399e7f5 100644 --- a/contracts/wasm/dividend/ts/dividend/lib.ts +++ b/contracts/wasm/dividend/ts/dividend/lib.ts @@ -8,28 +8,38 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncDivide, + sc.FuncInit, + sc.FuncMember, + sc.FuncSetOwner, + sc.ViewGetFactor, + sc.ViewGetOwner, + ], + funcs: [ + funcDivideThunk, + funcInitThunk, + funcMemberThunk, + funcSetOwnerThunk, + ], + views: [ + viewGetFactorThunk, + viewGetOwnerThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncDivide, funcDivideThunk); - exports.addFunc(sc.FuncInit, funcInitThunk); - exports.addFunc(sc.FuncMember, funcMemberThunk); - exports.addFunc(sc.FuncSetOwner, funcSetOwnerThunk); - exports.addView(sc.ViewGetFactor, viewGetFactorThunk); - exports.addView(sc.ViewGetOwner, viewGetOwnerThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcDivideThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("dividend.funcDivide"); let f = new sc.DivideContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcDivide(ctx, f); ctx.log("dividend.funcDivide ok"); } @@ -37,23 +47,19 @@ function funcDivideThunk(ctx: wasmlib.ScFuncContext): void { function funcInitThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("dividend.funcInit"); let f = new sc.InitContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcInit(ctx, f); ctx.log("dividend.funcInit ok"); } function funcMemberThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("dividend.funcMember"); + let f = new sc.MemberContext(); // only defined owner of contract can add members - let access = ctx.state().getAgentID(wasmlib.Key32.fromString("owner")); + const access = f.state.owner(); ctx.require(access.exists(), "access not set: owner"); ctx.require(ctx.caller().equals(access.value()), "no permission"); - let f = new sc.MemberContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.factor().exists(), "missing mandatory factor"); sc.funcMember(ctx, f); @@ -62,15 +68,13 @@ function funcMemberThunk(ctx: wasmlib.ScFuncContext): void { function funcSetOwnerThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("dividend.funcSetOwner"); + let f = new sc.SetOwnerContext(); // only defined owner of contract can change owner - let access = ctx.state().getAgentID(wasmlib.Key32.fromString("owner")); + const access = f.state.owner(); ctx.require(access.exists(), "access not set: owner"); ctx.require(ctx.caller().equals(access.value()), "no permission"); - let f = new sc.SetOwnerContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.owner().exists(), "missing mandatory owner"); sc.funcSetOwner(ctx, f); ctx.log("dividend.funcSetOwner ok"); @@ -79,19 +83,20 @@ function funcSetOwnerThunk(ctx: wasmlib.ScFuncContext): void { function viewGetFactorThunk(ctx: wasmlib.ScViewContext): void { ctx.log("dividend.viewGetFactor"); let f = new sc.GetFactorContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetFactorResults(results.asProxy()); ctx.require(f.params.address().exists(), "missing mandatory address"); sc.viewGetFactor(ctx, f); + ctx.results(results); ctx.log("dividend.viewGetFactor ok"); } function viewGetOwnerThunk(ctx: wasmlib.ScViewContext): void { ctx.log("dividend.viewGetOwner"); let f = new sc.GetOwnerContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetOwnerResults(results.asProxy()); sc.viewGetOwner(ctx, f); + ctx.results(results); ctx.log("dividend.viewGetOwner ok"); } diff --git a/contracts/wasm/dividend/ts/dividend/params.ts b/contracts/wasm/dividend/ts/dividend/params.ts index 7186afa1ec..d7f2212400 100644 --- a/contracts/wasm/dividend/ts/dividend/params.ts +++ b/contracts/wasm/dividend/ts/dividend/params.ts @@ -5,61 +5,61 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableInitParams extends wasmlib.ScMapID { - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, sc.idxMap[sc.IdxParamOwner]); +export class ImmutableInitParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class MutableInitParams extends wasmlib.ScMapID { - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, sc.idxMap[sc.IdxParamOwner]); +export class MutableInitParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class ImmutableMemberParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutableMemberParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } - factor(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamFactor)); + factor(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamFactor)); } } -export class MutableMemberParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutableMemberParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } - factor(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamFactor)); + factor(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamFactor)); } } -export class ImmutableSetOwnerParams extends wasmlib.ScMapID { - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); +export class ImmutableSetOwnerParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class MutableSetOwnerParams extends wasmlib.ScMapID { - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); +export class MutableSetOwnerParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class ImmutableGetFactorParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutableGetFactorParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } } -export class MutableGetFactorParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutableGetFactorParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } } diff --git a/contracts/wasm/dividend/ts/dividend/results.ts b/contracts/wasm/dividend/ts/dividend/results.ts index bf8821b726..23c17ba7d7 100644 --- a/contracts/wasm/dividend/ts/dividend/results.ts +++ b/contracts/wasm/dividend/ts/dividend/results.ts @@ -5,29 +5,29 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableGetFactorResults extends wasmlib.ScMapID { - factor(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultFactor)); +export class ImmutableGetFactorResults extends wasmtypes.ScProxy { + factor(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultFactor)); } } -export class MutableGetFactorResults extends wasmlib.ScMapID { - factor(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultFactor)); +export class MutableGetFactorResults extends wasmtypes.ScProxy { + factor(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultFactor)); } } -export class ImmutableGetOwnerResults extends wasmlib.ScMapID { - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultOwner)); +export class ImmutableGetOwnerResults extends wasmtypes.ScProxy { + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultOwner)); } } -export class MutableGetOwnerResults extends wasmlib.ScMapID { - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultOwner)); +export class MutableGetOwnerResults extends wasmtypes.ScProxy { + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultOwner)); } } diff --git a/contracts/wasm/dividend/ts/dividend/state.ts b/contracts/wasm/dividend/ts/dividend/state.ts index 0bd4aed4b3..9541d02597 100644 --- a/contracts/wasm/dividend/ts/dividend/state.ts +++ b/contracts/wasm/dividend/ts/dividend/state.ts @@ -5,115 +5,93 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableAddress { - objID: i32; +export class ArrayOfImmutableAddress extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getAddress(index: i32): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.objID, new wasmlib.Key32(index)); - } + getAddress(index: u32): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.index(index)); + } } -export class MapAddressToImmutableInt64 { - objID: i32; +export class MapAddressToImmutableUint64 extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getInt64(key: wasmlib.ScAddress): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAddress): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.key(wasmtypes.addressToBytes(key))); + } } -export class ImmutableDividendState extends wasmlib.ScMapID { - memberList(): sc.ArrayOfImmutableAddress { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMemberList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_ADDRESS); - return new sc.ArrayOfImmutableAddress(arrID); +export class ImmutableDividendState extends wasmtypes.ScProxy { + memberList(): sc.ArrayOfImmutableAddress { + return new sc.ArrayOfImmutableAddress(this.proxy.root(sc.StateMemberList)); } - members(): sc.MapAddressToImmutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMembers), wasmlib.TYPE_MAP); - return new sc.MapAddressToImmutableInt64(mapID); + members(): sc.MapAddressToImmutableUint64 { + return new sc.MapAddressToImmutableUint64(this.proxy.root(sc.StateMembers)); } - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.StateOwner)); + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.StateOwner)); } - totalFactor(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTotalFactor)); + totalFactor(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateTotalFactor)); } } -export class ArrayOfMutableAddress { - objID: i32; +export class ArrayOfMutableAddress extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getAddress(index: i32): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.objID, new wasmlib.Key32(index)); - } + getAddress(index: u32): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.index(index)); + } } -export class MapAddressToMutableInt64 { - objID: i32; +export class MapAddressToMutableUint64 extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getInt64(key: wasmlib.ScAddress): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAddress): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.key(wasmtypes.addressToBytes(key))); + } } -export class MutableDividendState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableDividendState { - const imm = new sc.ImmutableDividendState(); - imm.mapID = this.mapID; - return imm; +export class MutableDividendState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableDividendState { + return new sc.ImmutableDividendState(this.proxy); } - memberList(): sc.ArrayOfMutableAddress { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMemberList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_ADDRESS); - return new sc.ArrayOfMutableAddress(arrID); + memberList(): sc.ArrayOfMutableAddress { + return new sc.ArrayOfMutableAddress(this.proxy.root(sc.StateMemberList)); } - members(): sc.MapAddressToMutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMembers), wasmlib.TYPE_MAP); - return new sc.MapAddressToMutableInt64(mapID); + members(): sc.MapAddressToMutableUint64 { + return new sc.MapAddressToMutableUint64(this.proxy.root(sc.StateMembers)); } - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.StateOwner)); + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.StateOwner)); } - totalFactor(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTotalFactor)); + totalFactor(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateTotalFactor)); } } diff --git a/contracts/wasm/donatewithfeedback/Cargo.toml b/contracts/wasm/donatewithfeedback/Cargo.toml index 4dc25d4110..864d2989f1 100644 --- a/contracts/wasm/donatewithfeedback/Cargo.toml +++ b/contracts/wasm/donatewithfeedback/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/consts.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/consts.go index d6c691a71e..4c8fe93542 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/consts.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/consts.go @@ -7,12 +7,12 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "donatewithfeedback" ScDescription = "" - HScName = wasmlib.ScHname(0x696d7f66) + HScName = wasmtypes.ScHname(0x696d7f66) ) const ( @@ -46,8 +46,8 @@ const ( ) const ( - HFuncDonate = wasmlib.ScHname(0xdc9b133a) - HFuncWithdraw = wasmlib.ScHname(0x9dcc0f41) - HViewDonation = wasmlib.ScHname(0xbdb245ba) - HViewDonationInfo = wasmlib.ScHname(0xc8f7c726) + HFuncDonate = wasmtypes.ScHname(0xdc9b133a) + HFuncWithdraw = wasmtypes.ScHname(0x9dcc0f41) + HViewDonation = wasmtypes.ScHname(0xbdb245ba) + HViewDonationInfo = wasmtypes.ScHname(0xc8f7c726) ) diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/contract.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/contract.go index 11d419e9a6..30a896390d 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/contract.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/contract.go @@ -7,7 +7,7 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type DonateCall struct { Func *wasmlib.ScFunc @@ -36,24 +36,25 @@ var ScFuncs Funcs func (sc Funcs) Donate(ctx wasmlib.ScFuncCallContext) *DonateCall { f := &DonateCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncDonate)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Withdraw(ctx wasmlib.ScFuncCallContext) *WithdrawCall { f := &WithdrawCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncWithdraw)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Donation(ctx wasmlib.ScViewCallContext) *DonationCall { f := &DonationCall{Func: wasmlib.NewScView(ctx, HScName, HViewDonation)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) DonationInfo(ctx wasmlib.ScViewCallContext) *DonationInfoCall { f := &DonationInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewDonationInfo)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go index 4df9cda20d..a44016c186 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go @@ -4,12 +4,14 @@ package donatewithfeedback import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) func funcDonate(ctx wasmlib.ScFuncContext, f *DonateContext) { + amount := ctx.IncomingTransfer().Balance(wasmtypes.IOTA) donation := &Donation{ - Amount: ctx.Incoming().Balance(wasmlib.IOTA), + Amount: amount, Donator: ctx.Caller(), Error: "", Feedback: f.Params.Feedback().Value(), @@ -18,12 +20,12 @@ func funcDonate(ctx wasmlib.ScFuncContext, f *DonateContext) { if donation.Amount == 0 || donation.Feedback == "" { donation.Error = "error: empty feedback or donated amount = 0" if donation.Amount > 0 { - ctx.TransferToAddress(donation.Donator.Address(), wasmlib.NewScTransferIotas(donation.Amount)) + ctx.Send(donation.Donator.Address(), wasmlib.NewScTransferIotas(donation.Amount)) donation.Amount = 0 } } log := f.State.Log() - log.GetDonation(log.Length()).SetValue(donation) + log.AppendDonation().SetValue(donation) largestDonation := f.State.MaxDonation() totalDonated := f.State.TotalDonation() @@ -34,7 +36,7 @@ func funcDonate(ctx wasmlib.ScFuncContext, f *DonateContext) { } func funcWithdraw(ctx wasmlib.ScFuncContext, f *WithdrawContext) { - balance := ctx.Balances().Balance(wasmlib.IOTA) + balance := ctx.Balances().Balance(wasmtypes.IOTA) amount := f.Params.Amount().Value() if amount == 0 || amount > balance { amount = balance @@ -45,11 +47,11 @@ func funcWithdraw(ctx wasmlib.ScFuncContext, f *WithdrawContext) { } scCreator := ctx.ContractCreator().Address() - ctx.TransferToAddress(scCreator, wasmlib.NewScTransferIotas(amount)) + ctx.Send(scCreator, wasmlib.NewScTransferIotas(amount)) } func viewDonation(ctx wasmlib.ScViewContext, f *DonationContext) { - nr := int32(f.Params.Nr().Value()) + nr := f.Params.Nr().Value() donation := f.State.Log().GetDonation(nr).Value() f.Results.Amount().SetValue(donation.Amount) f.Results.Donator().SetValue(donation.Donator) @@ -61,5 +63,5 @@ func viewDonation(ctx wasmlib.ScViewContext, f *DonationContext) { func viewDonationInfo(ctx wasmlib.ScViewContext, f *DonationInfoContext) { f.Results.MaxDonation().SetValue(f.State.MaxDonation().Value()) f.Results.TotalDonation().SetValue(f.State.TotalDonation().Value()) - f.Results.Count().SetValue(int64(f.State.Log().Length())) + f.Results.Count().SetValue(f.State.Log().Length()) } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/keys.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/keys.go deleted file mode 100644 index a6939d46b7..0000000000 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/keys.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package donatewithfeedback - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamAmount = 0 - IdxParamFeedback = 1 - IdxParamNr = 2 - - IdxResultAmount = 3 - IdxResultCount = 4 - IdxResultDonator = 5 - IdxResultError = 6 - IdxResultFeedback = 7 - IdxResultMaxDonation = 8 - IdxResultTimestamp = 9 - IdxResultTotalDonation = 10 - - IdxStateLog = 11 - IdxStateMaxDonation = 12 - IdxStateTotalDonation = 13 -) - -const keyMapLen = 14 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamAmount, - ParamFeedback, - ParamNr, - ResultAmount, - ResultCount, - ResultDonator, - ResultError, - ResultFeedback, - ResultMaxDonation, - ResultTimestamp, - ResultTotalDonation, - StateLog, - StateMaxDonation, - StateTotalDonation, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/lib.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/lib.go index e24d6693b9..e951d92b95 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/lib.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/lib.go @@ -7,18 +7,32 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncDonate, funcDonateThunk) - exports.AddFunc(FuncWithdraw, funcWithdrawThunk) - exports.AddView(ViewDonation, viewDonationThunk) - exports.AddView(ViewDonationInfo, viewDonationInfoThunk) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncDonate, + FuncWithdraw, + ViewDonation, + ViewDonationInfo, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcDonateThunk, + funcWithdrawThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewDonationThunk, + viewDonationInfoThunk, + }, +} - for i, key := range keyMap { - idxMap[i] = key.KeyID() +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type DonateContext struct { @@ -30,10 +44,10 @@ func funcDonateThunk(ctx wasmlib.ScFuncContext) { ctx.Log("donatewithfeedback.funcDonate") f := &DonateContext{ Params: ImmutableDonateParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableDonateWithFeedbackState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcDonate(ctx, f) @@ -47,18 +61,18 @@ type WithdrawContext struct { func funcWithdrawThunk(ctx wasmlib.ScFuncContext) { ctx.Log("donatewithfeedback.funcWithdraw") - - // only SC creator can withdraw donated funds - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &WithdrawContext{ Params: ImmutableWithdrawParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableDonateWithFeedbackState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC creator can withdraw donated funds + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + funcWithdraw(ctx, f) ctx.Log("donatewithfeedback.funcWithdraw ok") } @@ -71,19 +85,21 @@ type DonationContext struct { func viewDonationThunk(ctx wasmlib.ScViewContext) { ctx.Log("donatewithfeedback.viewDonation") + results := wasmlib.NewScDict() f := &DonationContext{ Params: ImmutableDonationParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableDonationResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableDonateWithFeedbackState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Nr().Exists(), "missing mandatory nr") viewDonation(ctx, f) + ctx.Results(results) ctx.Log("donatewithfeedback.viewDonation ok") } @@ -94,14 +110,16 @@ type DonationInfoContext struct { func viewDonationInfoThunk(ctx wasmlib.ScViewContext) { ctx.Log("donatewithfeedback.viewDonationInfo") + results := wasmlib.NewScDict() f := &DonationInfoContext{ Results: MutableDonationInfoResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableDonateWithFeedbackState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewDonationInfo(ctx, f) + ctx.Results(results) ctx.Log("donatewithfeedback.viewDonationInfo ok") } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/params.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/params.go index caa10267bc..50f50d0f2a 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/params.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/params.go @@ -7,52 +7,52 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableDonateParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableDonateParams) Feedback() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamFeedback)) +func (s ImmutableDonateParams) Feedback() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamFeedback)) } type MutableDonateParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableDonateParams) Feedback() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamFeedback)) +func (s MutableDonateParams) Feedback() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamFeedback)) } type ImmutableWithdrawParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableWithdrawParams) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s ImmutableWithdrawParams) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamAmount)) } type MutableWithdrawParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableWithdrawParams) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s MutableWithdrawParams) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamAmount)) } type ImmutableDonationParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableDonationParams) Nr() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamNr)) +func (s ImmutableDonationParams) Nr() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamNr)) } type MutableDonationParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableDonationParams) Nr() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamNr)) +func (s MutableDonationParams) Nr() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamNr)) } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/results.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/results.go index 85fa71ca2c..50ddf93dfe 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/results.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/results.go @@ -7,84 +7,84 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableDonationResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableDonationResults) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s ImmutableDonationResults) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultAmount)) } -func (s ImmutableDonationResults) Donator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultDonator)) +func (s ImmutableDonationResults) Donator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultDonator)) } -func (s ImmutableDonationResults) Error() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultError)) +func (s ImmutableDonationResults) Error() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultError)) } -func (s ImmutableDonationResults) Feedback() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultFeedback)) +func (s ImmutableDonationResults) Feedback() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultFeedback)) } -func (s ImmutableDonationResults) Timestamp() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultTimestamp)) +func (s ImmutableDonationResults) Timestamp() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultTimestamp)) } type MutableDonationResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableDonationResults) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s MutableDonationResults) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultAmount)) } -func (s MutableDonationResults) Donator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultDonator)) +func (s MutableDonationResults) Donator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultDonator)) } -func (s MutableDonationResults) Error() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultError)) +func (s MutableDonationResults) Error() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultError)) } -func (s MutableDonationResults) Feedback() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultFeedback)) +func (s MutableDonationResults) Feedback() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultFeedback)) } -func (s MutableDonationResults) Timestamp() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultTimestamp)) +func (s MutableDonationResults) Timestamp() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultTimestamp)) } type ImmutableDonationInfoResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableDonationInfoResults) Count() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultCount)) +func (s ImmutableDonationInfoResults) Count() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultCount)) } -func (s ImmutableDonationInfoResults) MaxDonation() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultMaxDonation)) +func (s ImmutableDonationInfoResults) MaxDonation() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultMaxDonation)) } -func (s ImmutableDonationInfoResults) TotalDonation() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultTotalDonation)) +func (s ImmutableDonationInfoResults) TotalDonation() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultTotalDonation)) } type MutableDonationInfoResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableDonationInfoResults) Count() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultCount)) +func (s MutableDonationInfoResults) Count() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultCount)) } -func (s MutableDonationInfoResults) MaxDonation() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultMaxDonation)) +func (s MutableDonationInfoResults) MaxDonation() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultMaxDonation)) } -func (s MutableDonationInfoResults) TotalDonation() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultTotalDonation)) +func (s MutableDonationInfoResults) TotalDonation() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultTotalDonation)) } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/state.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/state.go index c74fcc94c1..0610963601 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/state.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/state.go @@ -7,55 +7,58 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableDonation struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableDonation) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableDonation) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableDonation) GetDonation(index int32) ImmutableDonation { - return ImmutableDonation{objID: a.objID, keyID: wasmlib.Key32(index)} +func (a ArrayOfImmutableDonation) GetDonation(index uint32) ImmutableDonation { + return ImmutableDonation{proxy: a.proxy.Index(index)} } type ImmutableDonateWithFeedbackState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableDonateWithFeedbackState) Log() ArrayOfImmutableDonation { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateLog), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES) - return ArrayOfImmutableDonation{objID: arrID} + return ArrayOfImmutableDonation{proxy: s.proxy.Root(StateLog)} } -func (s ImmutableDonateWithFeedbackState) MaxDonation() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateMaxDonation)) +func (s ImmutableDonateWithFeedbackState) MaxDonation() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateMaxDonation)) } -func (s ImmutableDonateWithFeedbackState) TotalDonation() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateTotalDonation)) +func (s ImmutableDonateWithFeedbackState) TotalDonation() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateTotalDonation)) } type ArrayOfMutableDonation struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableDonation) AppendDonation() MutableDonation { + return MutableDonation{proxy: a.proxy.Append()} } func (a ArrayOfMutableDonation) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableDonation) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableDonation) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableDonation) GetDonation(index int32) MutableDonation { - return MutableDonation{objID: a.objID, keyID: wasmlib.Key32(index)} +func (a ArrayOfMutableDonation) GetDonation(index uint32) MutableDonation { + return MutableDonation{proxy: a.proxy.Index(index)} } type MutableDonateWithFeedbackState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableDonateWithFeedbackState) AsImmutable() ImmutableDonateWithFeedbackState { @@ -63,14 +66,13 @@ func (s MutableDonateWithFeedbackState) AsImmutable() ImmutableDonateWithFeedbac } func (s MutableDonateWithFeedbackState) Log() ArrayOfMutableDonation { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateLog), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES) - return ArrayOfMutableDonation{objID: arrID} + return ArrayOfMutableDonation{proxy: s.proxy.Root(StateLog)} } -func (s MutableDonateWithFeedbackState) MaxDonation() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateMaxDonation)) +func (s MutableDonateWithFeedbackState) MaxDonation() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateMaxDonation)) } -func (s MutableDonateWithFeedbackState) TotalDonation() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateTotalDonation)) +func (s MutableDonateWithFeedbackState) TotalDonation() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateTotalDonation)) } diff --git a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/structs.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/structs.go index 40d6b63f13..82ac1341f0 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/structs.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/structs.go @@ -7,68 +7,66 @@ package donatewithfeedback -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type Donation struct { - Amount int64 // amount donated - Donator wasmlib.ScAgentID // who donated - Error string // error to be reported to donator if anything goes wrong - Feedback string // the feedback for the person donated to - Timestamp int64 // when the donation took place + Amount uint64 // amount donated + Donator wasmtypes.ScAgentID // who donated + Error string // error to be reported to donator if anything goes wrong + Feedback string // the feedback for the person donated to + Timestamp uint64 // when the donation took place } -func NewDonationFromBytes(bytes []byte) *Donation { - decode := wasmlib.NewBytesDecoder(bytes) +func NewDonationFromBytes(buf []byte) *Donation { + dec := wasmtypes.NewWasmDecoder(buf) data := &Donation{} - data.Amount = decode.Int64() - data.Donator = decode.AgentID() - data.Error = decode.String() - data.Feedback = decode.String() - data.Timestamp = decode.Int64() - decode.Close() + data.Amount = wasmtypes.Uint64Decode(dec) + data.Donator = wasmtypes.AgentIDDecode(dec) + data.Error = wasmtypes.StringDecode(dec) + data.Feedback = wasmtypes.StringDecode(dec) + data.Timestamp = wasmtypes.Uint64Decode(dec) + dec.Close() return data } func (o *Donation) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Int64(o.Amount). - AgentID(o.Donator). - String(o.Error). - String(o.Feedback). - Int64(o.Timestamp). - Data() + enc := wasmtypes.NewWasmEncoder() + wasmtypes.Uint64Encode(enc, o.Amount) + wasmtypes.AgentIDEncode(enc, o.Donator) + wasmtypes.StringEncode(enc, o.Error) + wasmtypes.StringEncode(enc, o.Feedback) + wasmtypes.Uint64Encode(enc, o.Timestamp) + return enc.Buf() } type ImmutableDonation struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o ImmutableDonation) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o ImmutableDonation) Value() *Donation { - return NewDonationFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewDonationFromBytes(o.proxy.Get()) } type MutableDonation struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o MutableDonation) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } func (o MutableDonation) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o MutableDonation) SetValue(value *Donation) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } func (o MutableDonation) Value() *Donation { - return NewDonationFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewDonationFromBytes(o.proxy.Get()) } diff --git a/contracts/wasm/donatewithfeedback/go/main.go b/contracts/wasm/donatewithfeedback/go/main.go index a263164081..191e448bf3 100644 --- a/contracts/wasm/donatewithfeedback/go/main.go +++ b/contracts/wasm/donatewithfeedback/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/donatewithfeedback/go/donatewithfeedback" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + donatewithfeedback.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - donatewithfeedback.OnLoad() + donatewithfeedback.OnLoad(-1) } diff --git a/contracts/wasm/donatewithfeedback/schema.yaml b/contracts/wasm/donatewithfeedback/schema.yaml index e15fea8721..50a2de738c 100644 --- a/contracts/wasm/donatewithfeedback/schema.yaml +++ b/contracts/wasm/donatewithfeedback/schema.yaml @@ -2,16 +2,16 @@ name: DonateWithFeedback description: "" structs: Donation: - amount: Int64 // amount donated + amount: Uint64 // amount donated donator: AgentID // who donated error: String // error to be reported to donator if anything goes wrong feedback: String // the feedback for the person donated to - timestamp: Int64 // when the donation took place + timestamp: Uint64 // when the donation took place typedefs: {} state: log: Donation[] - maxDonation: Int64 - totalDonation: Int64 + maxDonation: Uint64 + totalDonation: Uint64 funcs: donate: params: @@ -19,19 +19,19 @@ funcs: withdraw: access: creator // only SC creator can withdraw donated funds params: - amount: Int64? // amount to withdraw + amount: Uint64? // amount to withdraw views: donation: params: - nr: Int64 + nr: Uint32 results: - amount: Int64 // amount donated + amount: Uint64 // amount donated donator: AgentID // who donated error: String // error to be reported to donator if anything goes wrong feedback: String // the feedback for the person donated to - timestamp: Int64 // when the donation took place + timestamp: Uint64 // when the donation took place donationInfo: results: - count: Int64 - maxDonation: Int64 - totalDonation: Int64 + count: Uint32 + maxDonation: Uint64 + totalDonation: Uint64 diff --git a/contracts/wasm/donatewithfeedback/src/contract.rs b/contracts/wasm/donatewithfeedback/src/contract.rs index d726d153ca..1139f47a34 100644 --- a/contracts/wasm/donatewithfeedback/src/contract.rs +++ b/contracts/wasm/donatewithfeedback/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct DonateCall { pub func: ScFunc, @@ -40,40 +35,41 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn donate(_ctx: & dyn ScFuncCallContext) -> DonateCall { + pub fn donate(_ctx: &dyn ScFuncCallContext) -> DonateCall { let mut f = DonateCall { func: ScFunc::new(HSC_NAME, HFUNC_DONATE), - params: MutableDonateParams { id: 0 }, + params: MutableDonateParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn withdraw(_ctx: & dyn ScFuncCallContext) -> WithdrawCall { + pub fn withdraw(_ctx: &dyn ScFuncCallContext) -> WithdrawCall { let mut f = WithdrawCall { func: ScFunc::new(HSC_NAME, HFUNC_WITHDRAW), - params: MutableWithdrawParams { id: 0 }, + params: MutableWithdrawParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn donation(_ctx: & dyn ScViewCallContext) -> DonationCall { + pub fn donation(_ctx: &dyn ScViewCallContext) -> DonationCall { let mut f = DonationCall { func: ScView::new(HSC_NAME, HVIEW_DONATION), - params: MutableDonationParams { id: 0 }, - results: ImmutableDonationResults { id: 0 }, + params: MutableDonationParams { proxy: Proxy::nil() }, + results: ImmutableDonationResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn donation_info(_ctx: & dyn ScViewCallContext) -> DonationInfoCall { + pub fn donation_info(_ctx: &dyn ScViewCallContext) -> DonationInfoCall { let mut f = DonationInfoCall { func: ScView::new(HSC_NAME, HVIEW_DONATION_INFO), - results: ImmutableDonationInfoResults { id: 0 }, + results: ImmutableDonationInfoResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs b/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs index 66a15acc75..0a79c1e4c1 100644 --- a/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs +++ b/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs @@ -7,8 +7,9 @@ use crate::*; use crate::structs::*; pub fn func_donate(ctx: &ScFuncContext, f: &DonateContext) { + let amount = ctx.incoming().balance(&ScColor::IOTA); let mut donation = Donation { - amount: ctx.incoming().balance(&ScColor::IOTA), + amount: amount, donator: ctx.caller(), error: String::new(), feedback: f.params.feedback().value(), @@ -17,12 +18,12 @@ pub fn func_donate(ctx: &ScFuncContext, f: &DonateContext) { if donation.amount == 0 || donation.feedback.len() == 0 { donation.error = "error: empty feedback or donated amount = 0".to_string(); if donation.amount > 0 { - ctx.transfer_to_address(&donation.donator.address(), ScTransfers::iotas(donation.amount)); + ctx.send(&donation.donator.address(), &ScTransfers::iotas(donation.amount)); donation.amount = 0; } } let log = f.state.log(); - log.get_donation(log.length()).set_value(&donation); + log.append_donation().set_value(&donation); let largest_donation = f.state.max_donation(); let total_donated = f.state.total_donation(); @@ -44,11 +45,11 @@ pub fn func_withdraw(ctx: &ScFuncContext, f: &WithdrawContext) { } let sc_creator = ctx.contract_creator().address(); - ctx.transfer_to_address(&sc_creator, ScTransfers::iotas(amount)); + ctx.send(&sc_creator, &ScTransfers::iotas(amount)); } pub fn view_donation(_ctx: &ScViewContext, f: &DonationContext) { - let nr = (f.params.nr().value()) as i32; + let nr = f.params.nr().value(); let donation = f.state.log().get_donation(nr).value(); f.results.amount().set_value(donation.amount); f.results.donator().set_value(&donation.donator); @@ -60,5 +61,5 @@ pub fn view_donation(_ctx: &ScViewContext, f: &DonationContext) { pub fn view_donation_info(_ctx: &ScViewContext, f: &DonationInfoContext) { f.results.max_donation().set_value(f.state.max_donation().value()); f.results.total_donation().set_value(f.state.total_donation().value()); - f.results.count().set_value(f.state.log().length() as i64); + f.results.count().set_value(f.state.log().length()); } diff --git a/contracts/wasm/donatewithfeedback/src/keys.rs b/contracts/wasm/donatewithfeedback/src/keys.rs deleted file mode 100644 index 15946701bc..0000000000 --- a/contracts/wasm/donatewithfeedback/src/keys.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_AMOUNT : usize = 0; -pub(crate) const IDX_PARAM_FEEDBACK : usize = 1; -pub(crate) const IDX_PARAM_NR : usize = 2; - -pub(crate) const IDX_RESULT_AMOUNT : usize = 3; -pub(crate) const IDX_RESULT_COUNT : usize = 4; -pub(crate) const IDX_RESULT_DONATOR : usize = 5; -pub(crate) const IDX_RESULT_ERROR : usize = 6; -pub(crate) const IDX_RESULT_FEEDBACK : usize = 7; -pub(crate) const IDX_RESULT_MAX_DONATION : usize = 8; -pub(crate) const IDX_RESULT_TIMESTAMP : usize = 9; -pub(crate) const IDX_RESULT_TOTAL_DONATION : usize = 10; - -pub(crate) const IDX_STATE_LOG : usize = 11; -pub(crate) const IDX_STATE_MAX_DONATION : usize = 12; -pub(crate) const IDX_STATE_TOTAL_DONATION : usize = 13; - -pub const KEY_MAP_LEN: usize = 14; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_AMOUNT, - PARAM_FEEDBACK, - PARAM_NR, - RESULT_AMOUNT, - RESULT_COUNT, - RESULT_DONATOR, - RESULT_ERROR, - RESULT_FEEDBACK, - RESULT_MAX_DONATION, - RESULT_TIMESTAMP, - RESULT_TOTAL_DONATION, - STATE_LOG, - STATE_MAX_DONATION, - STATE_TOTAL_DONATION, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/donatewithfeedback/src/lib.rs b/contracts/wasm/donatewithfeedback/src/lib.rs index feb50f1542..2b3fc09cc7 100644 --- a/contracts/wasm/donatewithfeedback/src/lib.rs +++ b/contracts/wasm/donatewithfeedback/src/lib.rs @@ -10,36 +10,47 @@ use donatewithfeedback::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::structs::*; mod consts; mod contract; -mod keys; mod params; mod results; mod state; mod structs; + mod donatewithfeedback; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_DONATE, + FUNC_WITHDRAW, + VIEW_DONATION, + VIEW_DONATION_INFO, + ], + funcs: &[ + func_donate_thunk, + func_withdraw_thunk, + ], + views: &[ + view_donation_thunk, + view_donation_info_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_DONATE, func_donate_thunk); - exports.add_func(FUNC_WITHDRAW, func_withdraw_thunk); - exports.add_view(VIEW_DONATION, view_donation_thunk); - exports.add_view(VIEW_DONATION_INFO, view_donation_info_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct DonateContext { @@ -50,12 +61,8 @@ pub struct DonateContext { fn func_donate_thunk(ctx: &ScFuncContext) { ctx.log("donatewithfeedback.funcDonate"); let f = DonateContext { - params: ImmutableDonateParams { - id: OBJ_ID_PARAMS, - }, - state: MutableDonateWithFeedbackState { - id: OBJ_ID_STATE, - }, + params: ImmutableDonateParams { proxy: params_proxy() }, + state: MutableDonateWithFeedbackState { proxy: state_proxy() }, }; func_donate(ctx, &f); ctx.log("donatewithfeedback.funcDonate ok"); @@ -68,18 +75,14 @@ pub struct WithdrawContext { fn func_withdraw_thunk(ctx: &ScFuncContext) { ctx.log("donatewithfeedback.funcWithdraw"); + let f = WithdrawContext { + params: ImmutableWithdrawParams { proxy: params_proxy() }, + state: MutableDonateWithFeedbackState { proxy: state_proxy() }, + }; // only SC creator can withdraw donated funds ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = WithdrawContext { - params: ImmutableWithdrawParams { - id: OBJ_ID_PARAMS, - }, - state: MutableDonateWithFeedbackState { - id: OBJ_ID_STATE, - }, - }; func_withdraw(ctx, &f); ctx.log("donatewithfeedback.funcWithdraw ok"); } @@ -93,18 +96,13 @@ pub struct DonationContext { fn view_donation_thunk(ctx: &ScViewContext) { ctx.log("donatewithfeedback.viewDonation"); let f = DonationContext { - params: ImmutableDonationParams { - id: OBJ_ID_PARAMS, - }, - results: MutableDonationResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableDonateWithFeedbackState { - id: OBJ_ID_STATE, - }, + params: ImmutableDonationParams { proxy: params_proxy() }, + results: MutableDonationResults { proxy: results_proxy() }, + state: ImmutableDonateWithFeedbackState { proxy: state_proxy() }, }; ctx.require(f.params.nr().exists(), "missing mandatory nr"); view_donation(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("donatewithfeedback.viewDonation ok"); } @@ -116,13 +114,10 @@ pub struct DonationInfoContext { fn view_donation_info_thunk(ctx: &ScViewContext) { ctx.log("donatewithfeedback.viewDonationInfo"); let f = DonationInfoContext { - results: MutableDonationInfoResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableDonateWithFeedbackState { - id: OBJ_ID_STATE, - }, + results: MutableDonationInfoResults { proxy: results_proxy() }, + state: ImmutableDonateWithFeedbackState { proxy: state_proxy() }, }; view_donation_info(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("donatewithfeedback.viewDonationInfo ok"); } diff --git a/contracts/wasm/donatewithfeedback/src/params.rs b/contracts/wasm/donatewithfeedback/src/params.rs index 9352539ea7..0021442994 100644 --- a/contracts/wasm/donatewithfeedback/src/params.rs +++ b/contracts/wasm/donatewithfeedback/src/params.rs @@ -9,74 +9,70 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonateParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDonateParams { pub fn feedback(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_FEEDBACK.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_FEEDBACK)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonateParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDonateParams { pub fn feedback(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_FEEDBACK.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_FEEDBACK)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableWithdrawParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableWithdrawParams { - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableWithdrawParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableWithdrawParams { - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonationParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDonationParams { - pub fn nr(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_NR.get_key_id()) + pub fn nr(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_NR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonationParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDonationParams { - pub fn nr(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_NR.get_key_id()) + pub fn nr(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_NR)) } } diff --git a/contracts/wasm/donatewithfeedback/src/results.rs b/contracts/wasm/donatewithfeedback/src/results.rs index 22e641f04f..6ca1b5fedd 100644 --- a/contracts/wasm/donatewithfeedback/src/results.rs +++ b/contracts/wasm/donatewithfeedback/src/results.rs @@ -9,100 +9,96 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonationResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDonationResults { - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } pub fn donator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_DONATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_DONATOR)) } pub fn error(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_ERROR.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_ERROR)) } pub fn feedback(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_FEEDBACK.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_FEEDBACK)) } - pub fn timestamp(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_TIMESTAMP.get_key_id()) + pub fn timestamp(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_TIMESTAMP)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonationResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDonationResults { - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } pub fn donator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_DONATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_DONATOR)) } pub fn error(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_ERROR.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_ERROR)) } pub fn feedback(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_FEEDBACK.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_FEEDBACK)) } - pub fn timestamp(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_TIMESTAMP.get_key_id()) + pub fn timestamp(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_TIMESTAMP)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonationInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDonationInfoResults { - pub fn count(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_COUNT.get_key_id()) + pub fn count(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_COUNT)) } - pub fn max_donation(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_MAX_DONATION.get_key_id()) + pub fn max_donation(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_MAX_DONATION)) } - pub fn total_donation(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_TOTAL_DONATION.get_key_id()) + pub fn total_donation(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_TOTAL_DONATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonationInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDonationInfoResults { - pub fn count(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_COUNT.get_key_id()) + pub fn count(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_COUNT)) } - pub fn max_donation(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_MAX_DONATION.get_key_id()) + pub fn max_donation(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_MAX_DONATION)) } - pub fn total_donation(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_TOTAL_DONATION.get_key_id()) + pub fn total_donation(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_TOTAL_DONATION)) } } diff --git a/contracts/wasm/donatewithfeedback/src/state.rs b/contracts/wasm/donatewithfeedback/src/state.rs index 5f8dc08729..f6f0348306 100644 --- a/contracts/wasm/donatewithfeedback/src/state.rs +++ b/contracts/wasm/donatewithfeedback/src/state.rs @@ -9,86 +9,87 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableDonation { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableDonation { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_donation(&self, index: i32) -> ImmutableDonation { - ImmutableDonation { obj_id: self.obj_id, key_id: Key32(index) } + + pub fn get_donation(&self, index: u32) -> ImmutableDonation { + ImmutableDonation { proxy: self.proxy.index(index) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonateWithFeedbackState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDonateWithFeedbackState { pub fn log(&self) -> ArrayOfImmutableDonation { - let arr_id = get_object_id(self.id, STATE_LOG.get_key_id(), TYPE_ARRAY | TYPE_BYTES); - ArrayOfImmutableDonation { obj_id: arr_id } + ArrayOfImmutableDonation { proxy: self.proxy.root(STATE_LOG) } } - pub fn max_donation(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_MAX_DONATION.get_key_id()) + pub fn max_donation(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_MAX_DONATION)) } - pub fn total_donation(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_TOTAL_DONATION.get_key_id()) + pub fn total_donation(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_TOTAL_DONATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableDonation { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableDonation { - pub fn clear(&self) { - clear(self.obj_id); + + pub fn append_donation(&self) -> MutableDonation { + MutableDonation { proxy: self.proxy.append() } + } + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_donation(&self, index: i32) -> MutableDonation { - MutableDonation { obj_id: self.obj_id, key_id: Key32(index) } + + pub fn get_donation(&self, index: u32) -> MutableDonation { + MutableDonation { proxy: self.proxy.index(index) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonateWithFeedbackState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDonateWithFeedbackState { pub fn as_immutable(&self) -> ImmutableDonateWithFeedbackState { - ImmutableDonateWithFeedbackState { id: self.id } + ImmutableDonateWithFeedbackState { proxy: self.proxy.root("") } } pub fn log(&self) -> ArrayOfMutableDonation { - let arr_id = get_object_id(self.id, STATE_LOG.get_key_id(), TYPE_ARRAY | TYPE_BYTES); - ArrayOfMutableDonation { obj_id: arr_id } + ArrayOfMutableDonation { proxy: self.proxy.root(STATE_LOG) } } - pub fn max_donation(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_MAX_DONATION.get_key_id()) + pub fn max_donation(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_MAX_DONATION)) } - pub fn total_donation(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_TOTAL_DONATION.get_key_id()) + pub fn total_donation(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_TOTAL_DONATION)) } } diff --git a/contracts/wasm/donatewithfeedback/src/structs.rs b/contracts/wasm/donatewithfeedback/src/structs.rs index b1ebbda1da..0e71a055a0 100644 --- a/contracts/wasm/donatewithfeedback/src/structs.rs +++ b/contracts/wasm/donatewithfeedback/src/structs.rs @@ -9,76 +9,73 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; #[derive(Clone)] pub struct Donation { - pub amount : i64, // amount donated + pub amount : u64, // amount donated pub donator : ScAgentID, // who donated pub error : String, // error to be reported to donator if anything goes wrong pub feedback : String, // the feedback for the person donated to - pub timestamp : i64, // when the donation took place + pub timestamp : u64, // when the donation took place } impl Donation { pub fn from_bytes(bytes: &[u8]) -> Donation { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); Donation { - amount : decode.int64(), - donator : decode.agent_id(), - error : decode.string(), - feedback : decode.string(), - timestamp : decode.int64(), + amount : uint64_decode(&mut dec), + donator : agent_id_decode(&mut dec), + error : string_decode(&mut dec), + feedback : string_decode(&mut dec), + timestamp : uint64_decode(&mut dec), } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.int64(self.amount); - encode.agent_id(&self.donator); - encode.string(&self.error); - encode.string(&self.feedback); - encode.int64(self.timestamp); - return encode.data(); + let mut enc = WasmEncoder::new(); + uint64_encode(&mut enc, self.amount); + agent_id_encode(&mut enc, &self.donator); + string_encode(&mut enc, &self.error); + string_encode(&mut enc, &self.feedback); + uint64_encode(&mut enc, self.timestamp); + enc.buf() } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDonation { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl ImmutableDonation { pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn value(&self) -> Donation { - Donation::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Donation::from_bytes(&self.proxy.get()) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDonation { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl MutableDonation { pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn set_value(&self, value: &Donation) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } pub fn value(&self) -> Donation { - Donation::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Donation::from_bytes(&self.proxy.get()) } } diff --git a/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm b/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm index 742ef0a8bc..d048e3e6ae 100644 Binary files a/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm and b/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm differ diff --git a/contracts/wasm/donatewithfeedback/test/donatewithfeedback_test.go b/contracts/wasm/donatewithfeedback/test/donatewithfeedback_test.go index 8c3edbf8cc..1f4e3d8c8b 100644 --- a/contracts/wasm/donatewithfeedback/test/donatewithfeedback_test.go +++ b/contracts/wasm/donatewithfeedback/test/donatewithfeedback_test.go @@ -8,7 +8,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/donatewithfeedback/go/donatewithfeedback" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/consts.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/consts.ts index c95c4a93f6..d6d0f9a74c 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/consts.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "donatewithfeedback"; export const ScDescription = ""; -export const HScName = new wasmlib.ScHname(0x696d7f66); +export const HScName = new wasmtypes.ScHname(0x696d7f66); export const ParamAmount = "amount"; export const ParamFeedback = "feedback"; @@ -33,7 +33,7 @@ export const FuncWithdraw = "withdraw"; export const ViewDonation = "donation"; export const ViewDonationInfo = "donationInfo"; -export const HFuncDonate = new wasmlib.ScHname(0xdc9b133a); -export const HFuncWithdraw = new wasmlib.ScHname(0x9dcc0f41); -export const HViewDonation = new wasmlib.ScHname(0xbdb245ba); -export const HViewDonationInfo = new wasmlib.ScHname(0xc8f7c726); +export const HFuncDonate = new wasmtypes.ScHname(0xdc9b133a); +export const HFuncWithdraw = new wasmtypes.ScHname(0x9dcc0f41); +export const HViewDonation = new wasmtypes.ScHname(0xbdb245ba); +export const HViewDonationInfo = new wasmtypes.ScHname(0xc8f7c726); diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/contract.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/contract.ts index c3d9d5a0eb..5d0e0a273b 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/contract.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/contract.ts @@ -10,68 +10,69 @@ import * as sc from "./index"; export class DonateCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDonate); - params: sc.MutableDonateParams = new sc.MutableDonateParams(); + params: sc.MutableDonateParams = new sc.MutableDonateParams(wasmlib.ScView.nilProxy); } export class DonateContext { - params: sc.ImmutableDonateParams = new sc.ImmutableDonateParams(); - state: sc.MutableDonateWithFeedbackState = new sc.MutableDonateWithFeedbackState(); + params: sc.ImmutableDonateParams = new sc.ImmutableDonateParams(wasmlib.paramsProxy()); + state: sc.MutableDonateWithFeedbackState = new sc.MutableDonateWithFeedbackState(wasmlib.ScState.proxy()); } export class WithdrawCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWithdraw); - params: sc.MutableWithdrawParams = new sc.MutableWithdrawParams(); + params: sc.MutableWithdrawParams = new sc.MutableWithdrawParams(wasmlib.ScView.nilProxy); } export class WithdrawContext { - params: sc.ImmutableWithdrawParams = new sc.ImmutableWithdrawParams(); - state: sc.MutableDonateWithFeedbackState = new sc.MutableDonateWithFeedbackState(); + params: sc.ImmutableWithdrawParams = new sc.ImmutableWithdrawParams(wasmlib.paramsProxy()); + state: sc.MutableDonateWithFeedbackState = new sc.MutableDonateWithFeedbackState(wasmlib.ScState.proxy()); } export class DonationCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewDonation); - params: sc.MutableDonationParams = new sc.MutableDonationParams(); - results: sc.ImmutableDonationResults = new sc.ImmutableDonationResults(); + params: sc.MutableDonationParams = new sc.MutableDonationParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableDonationResults = new sc.ImmutableDonationResults(wasmlib.ScView.nilProxy); } export class DonationContext { - params: sc.ImmutableDonationParams = new sc.ImmutableDonationParams(); - results: sc.MutableDonationResults = new sc.MutableDonationResults(); - state: sc.ImmutableDonateWithFeedbackState = new sc.ImmutableDonateWithFeedbackState(); + params: sc.ImmutableDonationParams = new sc.ImmutableDonationParams(wasmlib.paramsProxy()); + results: sc.MutableDonationResults = new sc.MutableDonationResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableDonateWithFeedbackState = new sc.ImmutableDonateWithFeedbackState(wasmlib.ScState.proxy()); } export class DonationInfoCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewDonationInfo); - results: sc.ImmutableDonationInfoResults = new sc.ImmutableDonationInfoResults(); + results: sc.ImmutableDonationInfoResults = new sc.ImmutableDonationInfoResults(wasmlib.ScView.nilProxy); } export class DonationInfoContext { - results: sc.MutableDonationInfoResults = new sc.MutableDonationInfoResults(); - state: sc.ImmutableDonateWithFeedbackState = new sc.ImmutableDonateWithFeedbackState(); + results: sc.MutableDonationInfoResults = new sc.MutableDonationInfoResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableDonateWithFeedbackState = new sc.ImmutableDonateWithFeedbackState(wasmlib.ScState.proxy()); } export class ScFuncs { - static donate(ctx: wasmlib.ScFuncCallContext): DonateCall { - let f = new DonateCall(); - f.func.setPtrs(f.params, null); - return f; - } + static donate(_ctx: wasmlib.ScFuncCallContext): DonateCall { + const f = new DonateCall(); + f.params = new sc.MutableDonateParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } - static withdraw(ctx: wasmlib.ScFuncCallContext): WithdrawCall { - let f = new WithdrawCall(); - f.func.setPtrs(f.params, null); - return f; - } + static withdraw(_ctx: wasmlib.ScFuncCallContext): WithdrawCall { + const f = new WithdrawCall(); + f.params = new sc.MutableWithdrawParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } - static donation(ctx: wasmlib.ScViewCallContext): DonationCall { - let f = new DonationCall(); - f.func.setPtrs(f.params, f.results); - return f; - } + static donation(_ctx: wasmlib.ScViewCallContext): DonationCall { + const f = new DonationCall(); + f.params = new sc.MutableDonationParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableDonationResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } - static donationInfo(ctx: wasmlib.ScViewCallContext): DonationInfoCall { - let f = new DonationInfoCall(); - f.func.setPtrs(null, f.results); - return f; - } + static donationInfo(_ctx: wasmlib.ScViewCallContext): DonationInfoCall { + const f = new DonationInfoCall(); + f.results = new sc.ImmutableDonationInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts index c15e3bda21..2b8fd30250 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts @@ -2,11 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes" import * as sc from "./index"; export function funcDonate(ctx: wasmlib.ScFuncContext, f: sc.DonateContext): void { + const amount = ctx.incoming().balance(wasmtypes.IOTA); let donation = new sc.Donation(); - donation.amount = ctx.incoming().balance(wasmlib.ScColor.IOTA); + donation.amount = amount; donation.donator = ctx.caller(); donation.error = ""; donation.feedback = f.params.feedback().value(); @@ -14,12 +16,12 @@ export function funcDonate(ctx: wasmlib.ScFuncContext, f: sc.DonateContext): voi if (donation.amount == 0 || donation.feedback.length == 0) { donation.error = "error: empty feedback or donated amount = 0".toString(); if (donation.amount > 0) { - ctx.transferToAddress(donation.donator.address(), wasmlib.ScTransfers.iotas(donation.amount)); + ctx.send(donation.donator.address(), wasmlib.ScTransfers.iotas(donation.amount)); donation.amount = 0; } } let log = f.state.log(); - log.getDonation(log.length()).setValue(donation); + log.appendDonation().setValue(donation); let largestDonation = f.state.maxDonation(); let totalDonated = f.state.totalDonation(); @@ -30,7 +32,7 @@ export function funcDonate(ctx: wasmlib.ScFuncContext, f: sc.DonateContext): voi } export function funcWithdraw(ctx: wasmlib.ScFuncContext, f: sc.WithdrawContext): void { - let balance = ctx.balances().balance(wasmlib.ScColor.IOTA); + let balance = ctx.balances().balance(wasmtypes.IOTA); let amount = f.params.amount().value(); if (amount == 0 || amount > balance) { amount = balance; @@ -41,11 +43,11 @@ export function funcWithdraw(ctx: wasmlib.ScFuncContext, f: sc.WithdrawContext): } let scCreator = ctx.contractCreator().address(); - ctx.transferToAddress(scCreator, wasmlib.ScTransfers.iotas(amount)); + ctx.send(scCreator, wasmlib.ScTransfers.iotas(amount)); } export function viewDonation(ctx: wasmlib.ScViewContext, f: sc.DonationContext): void { - let nr = (f.params.nr().value()) as i32; + let nr = f.params.nr().value(); let donation = f.state.log().getDonation(nr).value(); f.results.amount().setValue(donation.amount); f.results.donator().setValue(donation.donator); @@ -57,5 +59,5 @@ export function viewDonation(ctx: wasmlib.ScViewContext, f: sc.DonationContext): export function viewDonationInfo(ctx: wasmlib.ScViewContext, f: sc.DonationInfoContext): void { f.results.maxDonation().setValue(f.state.maxDonation().value()); f.results.totalDonation().setValue(f.state.totalDonation().value()); - f.results.count().setValue(f.state.log().length() as i64); + f.results.count().setValue(f.state.log().length()); } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/index.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/index.ts index e5bfe68faa..3eabebcf92 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/index.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/index.ts @@ -9,7 +9,6 @@ export * from "./donatewithfeedback"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/keys.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/keys.ts deleted file mode 100644 index 16ce9ceed1..0000000000 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/keys.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamAmount = 0; -export const IdxParamFeedback = 1; -export const IdxParamNr = 2; - -export const IdxResultAmount = 3; -export const IdxResultCount = 4; -export const IdxResultDonator = 5; -export const IdxResultError = 6; -export const IdxResultFeedback = 7; -export const IdxResultMaxDonation = 8; -export const IdxResultTimestamp = 9; -export const IdxResultTotalDonation = 10; - -export const IdxStateLog = 11; -export const IdxStateMaxDonation = 12; -export const IdxStateTotalDonation = 13; - -export let keyMap: string[] = [ - sc.ParamAmount, - sc.ParamFeedback, - sc.ParamNr, - sc.ResultAmount, - sc.ResultCount, - sc.ResultDonator, - sc.ResultError, - sc.ResultFeedback, - sc.ResultMaxDonation, - sc.ResultTimestamp, - sc.ResultTotalDonation, - sc.StateLog, - sc.StateMaxDonation, - sc.StateTotalDonation, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/lib.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/lib.ts index ea6080bb30..5d1a1075d0 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/lib.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/lib.ts @@ -8,40 +8,45 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncDonate, + sc.FuncWithdraw, + sc.ViewDonation, + sc.ViewDonationInfo, + ], + funcs: [ + funcDonateThunk, + funcWithdrawThunk, + ], + views: [ + viewDonationThunk, + viewDonationInfoThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncDonate, funcDonateThunk); - exports.addFunc(sc.FuncWithdraw, funcWithdrawThunk); - exports.addView(sc.ViewDonation, viewDonationThunk); - exports.addView(sc.ViewDonationInfo, viewDonationInfoThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcDonateThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("donatewithfeedback.funcDonate"); let f = new sc.DonateContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcDonate(ctx, f); ctx.log("donatewithfeedback.funcDonate ok"); } function funcWithdrawThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("donatewithfeedback.funcWithdraw"); + let f = new sc.WithdrawContext(); // only SC creator can withdraw donated funds ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.WithdrawContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcWithdraw(ctx, f); ctx.log("donatewithfeedback.funcWithdraw ok"); } @@ -49,19 +54,20 @@ function funcWithdrawThunk(ctx: wasmlib.ScFuncContext): void { function viewDonationThunk(ctx: wasmlib.ScViewContext): void { ctx.log("donatewithfeedback.viewDonation"); let f = new sc.DonationContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableDonationResults(results.asProxy()); ctx.require(f.params.nr().exists(), "missing mandatory nr"); sc.viewDonation(ctx, f); + ctx.results(results); ctx.log("donatewithfeedback.viewDonation ok"); } function viewDonationInfoThunk(ctx: wasmlib.ScViewContext): void { ctx.log("donatewithfeedback.viewDonationInfo"); let f = new sc.DonationInfoContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableDonationInfoResults(results.asProxy()); sc.viewDonationInfo(ctx, f); + ctx.results(results); ctx.log("donatewithfeedback.viewDonationInfo ok"); } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/params.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/params.ts index 6e57022c41..453812c418 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/params.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/params.ts @@ -5,41 +5,41 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableDonateParams extends wasmlib.ScMapID { - feedback(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamFeedback)); +export class ImmutableDonateParams extends wasmtypes.ScProxy { + feedback(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamFeedback)); } } -export class MutableDonateParams extends wasmlib.ScMapID { - feedback(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamFeedback)); +export class MutableDonateParams extends wasmtypes.ScProxy { + feedback(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamFeedback)); } } -export class ImmutableWithdrawParams extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); +export class ImmutableWithdrawParams extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamAmount)); } } -export class MutableWithdrawParams extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); +export class MutableWithdrawParams extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamAmount)); } } -export class ImmutableDonationParams extends wasmlib.ScMapID { - nr(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNr)); +export class ImmutableDonationParams extends wasmtypes.ScProxy { + nr(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamNr)); } } -export class MutableDonationParams extends wasmlib.ScMapID { - nr(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNr)); +export class MutableDonationParams extends wasmtypes.ScProxy { + nr(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamNr)); } } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/results.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/results.ts index 308ef3d0b7..0d9a53f98a 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/results.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/results.ts @@ -5,77 +5,77 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableDonationResults extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class ImmutableDonationResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultAmount)); } - donator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultDonator)); + donator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultDonator)); } - error(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultError)); + error(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultError)); } - feedback(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultFeedback)); + feedback(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultFeedback)); } - timestamp(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTimestamp)); + timestamp(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultTimestamp)); } } -export class MutableDonationResults extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class MutableDonationResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultAmount)); } - donator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultDonator)); + donator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultDonator)); } - error(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultError)); + error(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultError)); } - feedback(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultFeedback)); + feedback(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultFeedback)); } - timestamp(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTimestamp)); + timestamp(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultTimestamp)); } } -export class ImmutableDonationInfoResults extends wasmlib.ScMapID { - count(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCount)); +export class ImmutableDonationInfoResults extends wasmtypes.ScProxy { + count(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultCount)); } - maxDonation(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxDonation)); + maxDonation(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultMaxDonation)); } - totalDonation(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTotalDonation)); + totalDonation(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultTotalDonation)); } } -export class MutableDonationInfoResults extends wasmlib.ScMapID { - count(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCount)); +export class MutableDonationInfoResults extends wasmtypes.ScProxy { + count(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultCount)); } - maxDonation(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxDonation)); + maxDonation(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultMaxDonation)); } - totalDonation(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTotalDonation)); + totalDonation(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultTotalDonation)); } } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/state.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/state.ts index 50b1f395d0..2f3dff8918 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/state.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/state.ts @@ -5,77 +5,67 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableDonation { - objID: i32; +export class ArrayOfImmutableDonation extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getDonation(index: i32): sc.ImmutableDonation { - return new sc.ImmutableDonation(this.objID, new wasmlib.Key32(index)); + getDonation(index: u32): sc.ImmutableDonation { + return new sc.ImmutableDonation(this.proxy.index(index)); } } -export class ImmutableDonateWithFeedbackState extends wasmlib.ScMapID { - log(): sc.ArrayOfImmutableDonation { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateLog), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableDonation(arrID); +export class ImmutableDonateWithFeedbackState extends wasmtypes.ScProxy { + log(): sc.ArrayOfImmutableDonation { + return new sc.ArrayOfImmutableDonation(this.proxy.root(sc.StateLog)); } - maxDonation(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateMaxDonation)); + maxDonation(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateMaxDonation)); } - totalDonation(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTotalDonation)); + totalDonation(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateTotalDonation)); } } -export class ArrayOfMutableDonation { - objID: i32; +export class ArrayOfMutableDonation extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendDonation(): sc.MutableDonation { + return new sc.MutableDonation(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getDonation(index: i32): sc.MutableDonation { - return new sc.MutableDonation(this.objID, new wasmlib.Key32(index)); + getDonation(index: u32): sc.MutableDonation { + return new sc.MutableDonation(this.proxy.index(index)); } } -export class MutableDonateWithFeedbackState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableDonateWithFeedbackState { - const imm = new sc.ImmutableDonateWithFeedbackState(); - imm.mapID = this.mapID; - return imm; +export class MutableDonateWithFeedbackState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableDonateWithFeedbackState { + return new sc.ImmutableDonateWithFeedbackState(this.proxy); } - log(): sc.ArrayOfMutableDonation { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateLog), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableDonation(arrID); + log(): sc.ArrayOfMutableDonation { + return new sc.ArrayOfMutableDonation(this.proxy.root(sc.StateLog)); } - maxDonation(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateMaxDonation)); + maxDonation(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateMaxDonation)); } - totalDonation(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTotalDonation)); + totalDonation(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateTotalDonation)); } } diff --git a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/structs.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/structs.ts index 91ecb4b41c..0f765adc1c 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/structs.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/structs.ts @@ -5,78 +5,64 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Donation { - amount : i64 = 0; // amount donated - donator : wasmlib.ScAgentID = new wasmlib.ScAgentID(); // who donated - error : string = ""; // error to be reported to donator if anything goes wrong - feedback : string = ""; // the feedback for the person donated to - timestamp : i64 = 0; // when the donation took place + amount : u64 = 0; // amount donated + donator : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); // who donated + error : string = ""; // error to be reported to donator if anything goes wrong + feedback : string = ""; // the feedback for the person donated to + timestamp : u64 = 0; // when the donation took place - static fromBytes(bytes: u8[]): Donation { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Donation(); - data.amount = decode.int64(); - data.donator = decode.agentID(); - data.error = decode.string(); - data.feedback = decode.string(); - data.timestamp = decode.int64(); - decode.close(); - return data; - } + static fromBytes(buf: u8[]): Donation { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new Donation(); + data.amount = wasmtypes.uint64Decode(dec); + data.donator = wasmtypes.agentIDDecode(dec); + data.error = wasmtypes.stringDecode(dec); + data.feedback = wasmtypes.stringDecode(dec); + data.timestamp = wasmtypes.uint64Decode(dec); + dec.close(); + return data; + } - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - int64(this.amount). - agentID(this.donator). - string(this.error). - string(this.feedback). - int64(this.timestamp). - data(); - } + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint64Encode(enc, this.amount); + wasmtypes.agentIDEncode(enc, this.donator); + wasmtypes.stringEncode(enc, this.error); + wasmtypes.stringEncode(enc, this.feedback); + wasmtypes.uint64Encode(enc, this.timestamp); + return enc.buf(); + } } -export class ImmutableDonation { - objID: i32; - keyID: wasmlib.Key32; +export class ImmutableDonation extends wasmtypes.ScProxy { - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } + exists(): bool { + return this.proxy.exists(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Donation { - return Donation.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Donation { + return Donation.fromBytes(this.proxy.get()); + } } -export class MutableDonation { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class MutableDonation extends wasmtypes.ScProxy { - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } - setValue(value: Donation): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: Donation): void { + this.proxy.set(value.bytes()); + } - value(): Donation { - return Donation.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Donation { + return Donation.fromBytes(this.proxy.get()); + } } diff --git a/contracts/wasm/erc20/Cargo.toml b/contracts/wasm/erc20/Cargo.toml index 41b760cbfc..79f7479434 100644 --- a/contracts/wasm/erc20/Cargo.toml +++ b/contracts/wasm/erc20/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/erc20/go/erc20/consts.go b/contracts/wasm/erc20/go/erc20/consts.go index b958c9f6e4..d6c91bcf3e 100644 --- a/contracts/wasm/erc20/go/erc20/consts.go +++ b/contracts/wasm/erc20/go/erc20/consts.go @@ -7,12 +7,12 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "erc20" ScDescription = "ERC-20 PoC for IOTA Smart Contracts" - HScName = wasmlib.ScHname(0x200e3733) + HScName = wasmtypes.ScHname(0x200e3733) ) const ( @@ -46,11 +46,11 @@ const ( ) const ( - HFuncApprove = wasmlib.ScHname(0xa0661268) - HFuncInit = wasmlib.ScHname(0x1f44d644) - HFuncTransfer = wasmlib.ScHname(0xa15da184) - HFuncTransferFrom = wasmlib.ScHname(0xd5e0a602) - HViewAllowance = wasmlib.ScHname(0x5e16006a) - HViewBalanceOf = wasmlib.ScHname(0x67ef8df4) - HViewTotalSupply = wasmlib.ScHname(0x9505e6ca) + HFuncApprove = wasmtypes.ScHname(0xa0661268) + HFuncInit = wasmtypes.ScHname(0x1f44d644) + HFuncTransfer = wasmtypes.ScHname(0xa15da184) + HFuncTransferFrom = wasmtypes.ScHname(0xd5e0a602) + HViewAllowance = wasmtypes.ScHname(0x5e16006a) + HViewBalanceOf = wasmtypes.ScHname(0x67ef8df4) + HViewTotalSupply = wasmtypes.ScHname(0x9505e6ca) ) diff --git a/contracts/wasm/erc20/go/erc20/contract.go b/contracts/wasm/erc20/go/erc20/contract.go index 7a085bfe48..b86cd07093 100644 --- a/contracts/wasm/erc20/go/erc20/contract.go +++ b/contracts/wasm/erc20/go/erc20/contract.go @@ -7,7 +7,7 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type ApproveCall struct { Func *wasmlib.ScFunc @@ -52,42 +52,44 @@ var ScFuncs Funcs func (sc Funcs) Approve(ctx wasmlib.ScFuncCallContext) *ApproveCall { f := &ApproveCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncApprove)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Init(ctx wasmlib.ScFuncCallContext) *InitCall { - f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit, keyMap[:], idxMap[:])} - f.Func.SetPtrs(&f.Params.id, nil) + f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Transfer(ctx wasmlib.ScFuncCallContext) *TransferCall { f := &TransferCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransfer)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) TransferFrom(ctx wasmlib.ScFuncCallContext) *TransferFromCall { f := &TransferFromCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferFrom)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Allowance(ctx wasmlib.ScViewCallContext) *AllowanceCall { f := &AllowanceCall{Func: wasmlib.NewScView(ctx, HScName, HViewAllowance)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) BalanceOf(ctx wasmlib.ScViewCallContext) *BalanceOfCall { f := &BalanceOfCall{Func: wasmlib.NewScView(ctx, HScName, HViewBalanceOf)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) TotalSupply(ctx wasmlib.ScViewCallContext) *TotalSupplyCall { f := &TotalSupplyCall{Func: wasmlib.NewScView(ctx, HScName, HViewTotalSupply)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/erc20/go/erc20/erc20.go b/contracts/wasm/erc20/go/erc20/erc20.go index fb6ef50a97..6a4882485c 100644 --- a/contracts/wasm/erc20/go/erc20/erc20.go +++ b/contracts/wasm/erc20/go/erc20/erc20.go @@ -7,7 +7,7 @@ package erc20 import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" ) // Sets the allowance value for delegated account @@ -17,11 +17,10 @@ import ( func funcApprove(ctx wasmlib.ScFuncContext, f *ApproveContext) { delegation := f.Params.Delegation().Value() amount := f.Params.Amount().Value() - ctx.Require(amount >= 0, "erc20.approve.fail: wrong 'amount' parameter") // all allowances are in the map under the name of he owner allowances := f.State.AllAllowances().GetAllowancesForAgent(ctx.Caller()) - allowances.GetInt64(delegation).SetValue(amount) + allowances.GetUint64(delegation).SetValue(amount) f.Events.Approval(amount, ctx.Caller(), delegation) } @@ -39,7 +38,7 @@ func funcInit(ctx wasmlib.ScFuncContext, f *InitContext) { // so, owner of the initial supply must be provided as a parameter PARAM_CREATOR to constructor (on_init) // assign the whole supply to creator creator := f.Params.Creator().Value() - f.State.Balances().GetInt64(creator).SetValue(supply) + f.State.Balances().GetUint64(creator).SetValue(supply) t := "erc20.on_init.success. Supply: " + f.Params.Supply().String() + ", creator:" + creator.String() @@ -53,17 +52,14 @@ func funcInit(ctx wasmlib.ScFuncContext, f *InitContext) { // - PARAM_AMOUNT: i64 func funcTransfer(ctx wasmlib.ScFuncContext, f *TransferContext) { amount := f.Params.Amount().Value() - ctx.Require(amount >= 0, "erc20.transfer.fail: wrong 'amount' parameter") balances := f.State.Balances() sourceAgent := ctx.Caller() - sourceBalance := balances.GetInt64(sourceAgent) + sourceBalance := balances.GetUint64(sourceAgent) ctx.Require(sourceBalance.Value() >= amount, "erc20.transfer.fail: not enough funds") targetAgent := f.Params.Account().Value() - targetBalance := balances.GetInt64(targetAgent) - result := targetBalance.Value() + amount - ctx.Require(result >= 0, "erc20.transfer.fail: overflow") + targetBalance := balances.GetUint64(targetAgent) sourceBalance.SetValue(sourceBalance.Value() - amount) targetBalance.SetValue(targetBalance.Value() + amount) @@ -81,22 +77,19 @@ func funcTransfer(ctx wasmlib.ScFuncContext, f *TransferContext) { func funcTransferFrom(ctx wasmlib.ScFuncContext, f *TransferFromContext) { // validate parameters amount := f.Params.Amount().Value() - ctx.Require(amount >= 0, "erc20.transfer_from.fail: wrong 'amount' parameter") // allowances are in the map under the name of the account sourceAgent := f.Params.Account().Value() allowances := f.State.AllAllowances().GetAllowancesForAgent(sourceAgent) - allowance := allowances.GetInt64(ctx.Caller()) + allowance := allowances.GetUint64(ctx.Caller()) ctx.Require(allowance.Value() >= amount, "erc20.transfer_from.fail: not enough allowance") balances := f.State.Balances() - sourceBalance := balances.GetInt64(sourceAgent) + sourceBalance := balances.GetUint64(sourceAgent) ctx.Require(sourceBalance.Value() >= amount, "erc20.transfer_from.fail: not enough funds") targetAgent := f.Params.Recipient().Value() - targetBalance := balances.GetInt64(targetAgent) - result := targetBalance.Value() + amount - ctx.Require(result >= 0, "erc20.transfer_from.fail: overflow") + targetBalance := balances.GetUint64(targetAgent) sourceBalance.SetValue(sourceBalance.Value() - amount) targetBalance.SetValue(targetBalance.Value() + amount) @@ -115,7 +108,7 @@ func funcTransferFrom(ctx wasmlib.ScFuncContext, f *TransferFromContext) { func viewAllowance(ctx wasmlib.ScViewContext, f *AllowanceContext) { // all allowances of the address 'owner' are stored in the map of the same name allowances := f.State.AllAllowances().GetAllowancesForAgent(f.Params.Account().Value()) - allow := allowances.GetInt64(f.Params.Delegation().Value()).Value() + allow := allowances.GetUint64(f.Params.Delegation().Value()).Value() f.Results.Amount().SetValue(allow) } @@ -124,7 +117,7 @@ func viewAllowance(ctx wasmlib.ScViewContext, f *AllowanceContext) { // - PARAM_ACCOUNT: agentID func viewBalanceOf(ctx wasmlib.ScViewContext, f *BalanceOfContext) { balances := f.State.Balances() - balance := balances.GetInt64(f.Params.Account().Value()) + balance := balances.GetUint64(f.Params.Account().Value()) f.Results.Amount().SetValue(balance.Value()) } diff --git a/contracts/wasm/erc20/go/erc20/events.go b/contracts/wasm/erc20/go/erc20/events.go index 7de35ec0a2..087cd28b86 100644 --- a/contracts/wasm/erc20/go/erc20/events.go +++ b/contracts/wasm/erc20/go/erc20/events.go @@ -8,22 +8,25 @@ //nolint:gocritic package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) type Erc20Events struct{} -func (e Erc20Events) Approval(amount int64, owner wasmlib.ScAgentID, spender wasmlib.ScAgentID) { - wasmlib.NewEventEncoder("erc20.approval"). - Int64(amount). - AgentID(owner). - AgentID(spender). - Emit() +func (e Erc20Events) Approval(amount uint64, owner wasmtypes.ScAgentID, spender wasmtypes.ScAgentID) { + evt := wasmlib.NewEventEncoder("erc20.approval") + evt.Encode(wasmtypes.Uint64ToString(amount)) + evt.Encode(wasmtypes.AgentIDToString(owner)) + evt.Encode(wasmtypes.AgentIDToString(spender)) + evt.Emit() } -func (e Erc20Events) Transfer(amount int64, from wasmlib.ScAgentID, to wasmlib.ScAgentID) { - wasmlib.NewEventEncoder("erc20.transfer"). - Int64(amount). - AgentID(from). - AgentID(to). - Emit() +func (e Erc20Events) Transfer(amount uint64, from wasmtypes.ScAgentID, to wasmtypes.ScAgentID) { + evt := wasmlib.NewEventEncoder("erc20.transfer") + evt.Encode(wasmtypes.Uint64ToString(amount)) + evt.Encode(wasmtypes.AgentIDToString(from)) + evt.Encode(wasmtypes.AgentIDToString(to)) + evt.Emit() } diff --git a/contracts/wasm/erc20/go/erc20/keys.go b/contracts/wasm/erc20/go/erc20/keys.go deleted file mode 100644 index d23df24110..0000000000 --- a/contracts/wasm/erc20/go/erc20/keys.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package erc20 - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamAccount = 0 - IdxParamAmount = 1 - IdxParamCreator = 2 - IdxParamDelegation = 3 - IdxParamRecipient = 4 - IdxParamSupply = 5 - - IdxResultAmount = 6 - IdxResultSupply = 7 - - IdxStateAllAllowances = 8 - IdxStateBalances = 9 - IdxStateSupply = 10 -) - -const keyMapLen = 11 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamAccount, - ParamAmount, - ParamCreator, - ParamDelegation, - ParamRecipient, - ParamSupply, - ResultAmount, - ResultSupply, - StateAllAllowances, - StateBalances, - StateSupply, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/erc20/go/erc20/lib.go b/contracts/wasm/erc20/go/erc20/lib.go index 5970c162bd..ee8106b487 100644 --- a/contracts/wasm/erc20/go/erc20/lib.go +++ b/contracts/wasm/erc20/go/erc20/lib.go @@ -7,21 +7,38 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncApprove, funcApproveThunk) - exports.AddFunc(FuncInit, funcInitThunk) - exports.AddFunc(FuncTransfer, funcTransferThunk) - exports.AddFunc(FuncTransferFrom, funcTransferFromThunk) - exports.AddView(ViewAllowance, viewAllowanceThunk) - exports.AddView(ViewBalanceOf, viewBalanceOfThunk) - exports.AddView(ViewTotalSupply, viewTotalSupplyThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncApprove, + FuncInit, + FuncTransfer, + FuncTransferFrom, + ViewAllowance, + ViewBalanceOf, + ViewTotalSupply, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcApproveThunk, + funcInitThunk, + funcTransferThunk, + funcTransferFromThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewAllowanceThunk, + viewBalanceOfThunk, + viewTotalSupplyThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type ApproveContext struct { @@ -34,10 +51,10 @@ func funcApproveThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc20.funcApprove") f := &ApproveContext{ Params: ImmutableApproveParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Amount().Exists(), "missing mandatory amount") @@ -56,10 +73,10 @@ func funcInitThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc20.funcInit") f := &InitContext{ Params: ImmutableInitParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Creator().Exists(), "missing mandatory creator") @@ -78,10 +95,10 @@ func funcTransferThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc20.funcTransfer") f := &TransferContext{ Params: ImmutableTransferParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Account().Exists(), "missing mandatory account") @@ -100,10 +117,10 @@ func funcTransferFromThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc20.funcTransferFrom") f := &TransferFromContext{ Params: ImmutableTransferFromParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Account().Exists(), "missing mandatory account") @@ -121,20 +138,22 @@ type AllowanceContext struct { func viewAllowanceThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc20.viewAllowance") + results := wasmlib.NewScDict() f := &AllowanceContext{ Params: ImmutableAllowanceParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableAllowanceResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Account().Exists(), "missing mandatory account") ctx.Require(f.Params.Delegation().Exists(), "missing mandatory delegation") viewAllowance(ctx, f) + ctx.Results(results) ctx.Log("erc20.viewAllowance ok") } @@ -146,19 +165,21 @@ type BalanceOfContext struct { func viewBalanceOfThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc20.viewBalanceOf") + results := wasmlib.NewScDict() f := &BalanceOfContext{ Params: ImmutableBalanceOfParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableBalanceOfResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Account().Exists(), "missing mandatory account") viewBalanceOf(ctx, f) + ctx.Results(results) ctx.Log("erc20.viewBalanceOf ok") } @@ -169,14 +190,16 @@ type TotalSupplyContext struct { func viewTotalSupplyThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc20.viewTotalSupply") + results := wasmlib.NewScDict() f := &TotalSupplyContext{ Results: MutableTotalSupplyResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc20State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewTotalSupply(ctx, f) + ctx.Results(results) ctx.Log("erc20.viewTotalSupply ok") } diff --git a/contracts/wasm/erc20/go/erc20/params.go b/contracts/wasm/erc20/go/erc20/params.go index 2a1edfa0b7..ad361dd08f 100644 --- a/contracts/wasm/erc20/go/erc20/params.go +++ b/contracts/wasm/erc20/go/erc20/params.go @@ -7,148 +7,148 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableApproveParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableApproveParams) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s ImmutableApproveParams) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamAmount)) } -func (s ImmutableApproveParams) Delegation() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamDelegation)) +func (s ImmutableApproveParams) Delegation() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamDelegation)) } type MutableApproveParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableApproveParams) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s MutableApproveParams) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamAmount)) } -func (s MutableApproveParams) Delegation() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamDelegation)) +func (s MutableApproveParams) Delegation() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamDelegation)) } type ImmutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableInitParams) Creator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, idxMap[IdxParamCreator]) +func (s ImmutableInitParams) Creator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamCreator)) } -func (s ImmutableInitParams) Supply() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, idxMap[IdxParamSupply]) +func (s ImmutableInitParams) Supply() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamSupply)) } type MutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableInitParams) Creator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, idxMap[IdxParamCreator]) +func (s MutableInitParams) Creator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamCreator)) } -func (s MutableInitParams) Supply() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, idxMap[IdxParamSupply]) +func (s MutableInitParams) Supply() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamSupply)) } type ImmutableTransferParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTransferParams) Account() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s ImmutableTransferParams) Account() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAccount)) } -func (s ImmutableTransferParams) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s ImmutableTransferParams) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamAmount)) } type MutableTransferParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTransferParams) Account() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s MutableTransferParams) Account() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAccount)) } -func (s MutableTransferParams) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s MutableTransferParams) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamAmount)) } type ImmutableTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTransferFromParams) Account() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s ImmutableTransferFromParams) Account() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAccount)) } -func (s ImmutableTransferFromParams) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s ImmutableTransferFromParams) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamAmount)) } -func (s ImmutableTransferFromParams) Recipient() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamRecipient)) +func (s ImmutableTransferFromParams) Recipient() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamRecipient)) } type MutableTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTransferFromParams) Account() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s MutableTransferFromParams) Account() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAccount)) } -func (s MutableTransferFromParams) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamAmount)) +func (s MutableTransferFromParams) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamAmount)) } -func (s MutableTransferFromParams) Recipient() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamRecipient)) +func (s MutableTransferFromParams) Recipient() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamRecipient)) } type ImmutableAllowanceParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableAllowanceParams) Account() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s ImmutableAllowanceParams) Account() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAccount)) } -func (s ImmutableAllowanceParams) Delegation() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamDelegation)) +func (s ImmutableAllowanceParams) Delegation() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamDelegation)) } type MutableAllowanceParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableAllowanceParams) Account() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s MutableAllowanceParams) Account() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAccount)) } -func (s MutableAllowanceParams) Delegation() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamDelegation)) +func (s MutableAllowanceParams) Delegation() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamDelegation)) } type ImmutableBalanceOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBalanceOfParams) Account() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s ImmutableBalanceOfParams) Account() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAccount)) } type MutableBalanceOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBalanceOfParams) Account() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAccount)) +func (s MutableBalanceOfParams) Account() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAccount)) } diff --git a/contracts/wasm/erc20/go/erc20/results.go b/contracts/wasm/erc20/go/erc20/results.go index 88b9fb4763..ce2871f763 100644 --- a/contracts/wasm/erc20/go/erc20/results.go +++ b/contracts/wasm/erc20/go/erc20/results.go @@ -7,52 +7,52 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableAllowanceResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableAllowanceResults) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s ImmutableAllowanceResults) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultAmount)) } type MutableAllowanceResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableAllowanceResults) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s MutableAllowanceResults) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultAmount)) } type ImmutableBalanceOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBalanceOfResults) Amount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s ImmutableBalanceOfResults) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultAmount)) } type MutableBalanceOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBalanceOfResults) Amount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultAmount)) +func (s MutableBalanceOfResults) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultAmount)) } type ImmutableTotalSupplyResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTotalSupplyResults) Supply() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultSupply)) +func (s ImmutableTotalSupplyResults) Supply() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultSupply)) } type MutableTotalSupplyResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTotalSupplyResults) Supply() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultSupply)) +func (s MutableTotalSupplyResults) Supply() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultSupply)) } diff --git a/contracts/wasm/erc20/go/erc20/state.go b/contracts/wasm/erc20/go/erc20/state.go index 9d33d8ba92..8bbdfdf1dc 100644 --- a/contracts/wasm/erc20/go/erc20/state.go +++ b/contracts/wasm/erc20/go/erc20/state.go @@ -7,50 +7,46 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type MapAgentIDToImmutableAllowancesForAgent struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableAllowancesForAgent) GetAllowancesForAgent(key wasmlib.ScAgentID) ImmutableAllowancesForAgent { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return ImmutableAllowancesForAgent{objID: subID} +func (m MapAgentIDToImmutableAllowancesForAgent) GetAllowancesForAgent(key wasmtypes.ScAgentID) ImmutableAllowancesForAgent { + return ImmutableAllowancesForAgent{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type ImmutableErc20State struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableErc20State) AllAllowances() MapAgentIDToImmutableAllowancesForAgent { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateAllAllowances), wasmlib.TYPE_MAP) - return MapAgentIDToImmutableAllowancesForAgent{objID: mapID} + return MapAgentIDToImmutableAllowancesForAgent{proxy: s.proxy.Root(StateAllAllowances)} } -func (s ImmutableErc20State) Balances() MapAgentIDToImmutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBalances), wasmlib.TYPE_MAP) - return MapAgentIDToImmutableInt64{objID: mapID} +func (s ImmutableErc20State) Balances() MapAgentIDToImmutableUint64 { + return MapAgentIDToImmutableUint64{proxy: s.proxy.Root(StateBalances)} } -func (s ImmutableErc20State) Supply() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateSupply)) +func (s ImmutableErc20State) Supply() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateSupply)) } type MapAgentIDToMutableAllowancesForAgent struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapAgentIDToMutableAllowancesForAgent) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapAgentIDToMutableAllowancesForAgent) GetAllowancesForAgent(key wasmlib.ScAgentID) MutableAllowancesForAgent { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return MutableAllowancesForAgent{objID: subID} +func (m MapAgentIDToMutableAllowancesForAgent) GetAllowancesForAgent(key wasmtypes.ScAgentID) MutableAllowancesForAgent { + return MutableAllowancesForAgent{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type MutableErc20State struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableErc20State) AsImmutable() ImmutableErc20State { @@ -58,15 +54,13 @@ func (s MutableErc20State) AsImmutable() ImmutableErc20State { } func (s MutableErc20State) AllAllowances() MapAgentIDToMutableAllowancesForAgent { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateAllAllowances), wasmlib.TYPE_MAP) - return MapAgentIDToMutableAllowancesForAgent{objID: mapID} + return MapAgentIDToMutableAllowancesForAgent{proxy: s.proxy.Root(StateAllAllowances)} } -func (s MutableErc20State) Balances() MapAgentIDToMutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBalances), wasmlib.TYPE_MAP) - return MapAgentIDToMutableInt64{objID: mapID} +func (s MutableErc20State) Balances() MapAgentIDToMutableUint64 { + return MapAgentIDToMutableUint64{proxy: s.proxy.Root(StateBalances)} } -func (s MutableErc20State) Supply() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateSupply)) +func (s MutableErc20State) Supply() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateSupply)) } diff --git a/contracts/wasm/erc20/go/erc20/typedefs.go b/contracts/wasm/erc20/go/erc20/typedefs.go index bdbfe132a8..effb2c2047 100644 --- a/contracts/wasm/erc20/go/erc20/typedefs.go +++ b/contracts/wasm/erc20/go/erc20/typedefs.go @@ -7,28 +7,28 @@ package erc20 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" -type MapAgentIDToImmutableInt64 struct { - objID int32 +type MapAgentIDToImmutableUint64 struct { + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableInt64) GetInt64(key wasmlib.ScAgentID) wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(m.objID, key.KeyID()) +func (m MapAgentIDToImmutableUint64) GetUint64(key wasmtypes.ScAgentID) wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } -type ImmutableAllowancesForAgent = MapAgentIDToImmutableInt64 +type ImmutableAllowancesForAgent = MapAgentIDToImmutableUint64 -type MapAgentIDToMutableInt64 struct { - objID int32 +type MapAgentIDToMutableUint64 struct { + proxy wasmtypes.Proxy } -func (m MapAgentIDToMutableInt64) Clear() { - wasmlib.Clear(m.objID) +func (m MapAgentIDToMutableUint64) Clear() { + m.proxy.ClearMap() } -func (m MapAgentIDToMutableInt64) GetInt64(key wasmlib.ScAgentID) wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(m.objID, key.KeyID()) +func (m MapAgentIDToMutableUint64) GetUint64(key wasmtypes.ScAgentID) wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } -type MutableAllowancesForAgent = MapAgentIDToMutableInt64 +type MutableAllowancesForAgent = MapAgentIDToMutableUint64 diff --git a/contracts/wasm/erc20/go/main.go b/contracts/wasm/erc20/go/main.go index ebb45b8642..061a3f242c 100644 --- a/contracts/wasm/erc20/go/main.go +++ b/contracts/wasm/erc20/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/erc20/go/erc20" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + erc20.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - erc20.OnLoad() + erc20.OnLoad(-1) } diff --git a/contracts/wasm/erc20/schema.yaml b/contracts/wasm/erc20/schema.yaml index dc54a60a38..d0ad7cbdb3 100644 --- a/contracts/wasm/erc20/schema.yaml +++ b/contracts/wasm/erc20/schema.yaml @@ -2,37 +2,37 @@ name: Erc20 description: ERC-20 PoC for IOTA Smart Contracts events: approval: - amount: Int64 + amount: Uint64 owner: AgentID spender: AgentID transfer: - amount: Int64 + amount: Uint64 from: AgentID to: AgentID structs: {} typedefs: - AllowancesForAgent: map[AgentID]Int64 + AllowancesForAgent: map[AgentID]Uint64 state: allAllowances=a: map[AgentID]AllowancesForAgent - balances=b: map[AgentID]Int64 // balances per account - supply=s: Int64 // total supply of the token + balances=b: map[AgentID]Uint64 // balances per account + supply=s: Uint64 // total supply of the token funcs: approve: params: - amount=am: Int64 // allowance value for delegated account + amount=am: Uint64 // allowance value for delegated account delegation=d: AgentID // delegated account init: params: creator=c: AgentID // creator/owner of the initial supply - supply=s: Int64 // initial token supply + supply=s: Uint64 // initial token supply transfer: params: account=ac: AgentID // target account - amount=am: Int64 // amount of tokens to transfer + amount=am: Uint64 // amount of tokens to transfer transferFrom: params: account=ac: AgentID // sender account - amount=am: Int64 // amount of tokens to transfer + amount=am: Uint64 // amount of tokens to transfer recipient=r: AgentID // recipient account views: allowance: @@ -40,12 +40,12 @@ views: account=ac: AgentID // sender account delegation=d: AgentID // delegated account results: - amount=am: Int64 + amount=am: Uint64 balanceOf: params: account=ac: AgentID // sender account results: - amount=am: Int64 + amount=am: Uint64 totalSupply: results: - supply=s: Int64 + supply=s: Uint64 diff --git a/contracts/wasm/erc20/src/contract.rs b/contracts/wasm/erc20/src/contract.rs index cc412c413d..2d7cec5958 100644 --- a/contracts/wasm/erc20/src/contract.rs +++ b/contracts/wasm/erc20/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct ApproveCall { pub func: ScFunc, @@ -56,68 +51,70 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn approve(_ctx: & dyn ScFuncCallContext) -> ApproveCall { + pub fn approve(_ctx: &dyn ScFuncCallContext) -> ApproveCall { let mut f = ApproveCall { func: ScFunc::new(HSC_NAME, HFUNC_APPROVE), - params: MutableApproveParams { id: 0 }, + params: MutableApproveParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn init(_ctx: & dyn ScFuncCallContext) -> InitCall { + pub fn init(_ctx: &dyn ScFuncCallContext) -> InitCall { let mut f = InitCall { func: ScInitFunc::new(HSC_NAME, HFUNC_INIT), - params: MutableInitParams { id: 0 }, + params: MutableInitParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScInitFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn transfer(_ctx: & dyn ScFuncCallContext) -> TransferCall { + pub fn transfer(_ctx: &dyn ScFuncCallContext) -> TransferCall { let mut f = TransferCall { func: ScFunc::new(HSC_NAME, HFUNC_TRANSFER), - params: MutableTransferParams { id: 0 }, + params: MutableTransferParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn transfer_from(_ctx: & dyn ScFuncCallContext) -> TransferFromCall { + pub fn transfer_from(_ctx: &dyn ScFuncCallContext) -> TransferFromCall { let mut f = TransferFromCall { func: ScFunc::new(HSC_NAME, HFUNC_TRANSFER_FROM), - params: MutableTransferFromParams { id: 0 }, + params: MutableTransferFromParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn allowance(_ctx: & dyn ScViewCallContext) -> AllowanceCall { + pub fn allowance(_ctx: &dyn ScViewCallContext) -> AllowanceCall { let mut f = AllowanceCall { func: ScView::new(HSC_NAME, HVIEW_ALLOWANCE), - params: MutableAllowanceParams { id: 0 }, - results: ImmutableAllowanceResults { id: 0 }, + params: MutableAllowanceParams { proxy: Proxy::nil() }, + results: ImmutableAllowanceResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn balance_of(_ctx: & dyn ScViewCallContext) -> BalanceOfCall { + pub fn balance_of(_ctx: &dyn ScViewCallContext) -> BalanceOfCall { let mut f = BalanceOfCall { func: ScView::new(HSC_NAME, HVIEW_BALANCE_OF), - params: MutableBalanceOfParams { id: 0 }, - results: ImmutableBalanceOfResults { id: 0 }, + params: MutableBalanceOfParams { proxy: Proxy::nil() }, + results: ImmutableBalanceOfResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn total_supply(_ctx: & dyn ScViewCallContext) -> TotalSupplyCall { + pub fn total_supply(_ctx: &dyn ScViewCallContext) -> TotalSupplyCall { let mut f = TotalSupplyCall { func: ScView::new(HSC_NAME, HVIEW_TOTAL_SUPPLY), - results: ImmutableTotalSupplyResults { id: 0 }, + results: ImmutableTotalSupplyResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/erc20/src/erc20.rs b/contracts/wasm/erc20/src/erc20.rs index f056e80706..958919f791 100644 --- a/contracts/wasm/erc20/src/erc20.rs +++ b/contracts/wasm/erc20/src/erc20.rs @@ -11,15 +11,14 @@ use crate::*; // Sets the allowance value for delegated account // inputs: // - PARAM_DELEGATION: agentID -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 pub fn func_approve(ctx: &ScFuncContext, f: &ApproveContext) { let delegation = f.params.delegation().value(); let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.approve.fail: wrong 'amount' parameter"); // all allowances are in the map under the name of he owner let allowances = f.state.all_allowances().get_allowances_for_agent(&ctx.caller()); - allowances.get_int64(&delegation).set_value(amount); + allowances.get_uint64(&delegation).set_value(amount); f.events.approval(amount, &ctx.caller(), &delegation); } @@ -37,7 +36,7 @@ pub fn func_init(ctx: &ScFuncContext, f: &InitContext) { // so, owner of the initial supply must be provided as a parameter PARAM_CREATOR to constructor (on_init) // assign the whole supply to creator let creator = f.params.creator().value(); - f.state.balances().get_int64(&creator).set_value(supply); + f.state.balances().get_uint64(&creator).set_value(supply); let t = "erc20.on_init.success. Supply: ".to_string() + &supply.to_string() + &", creator:".to_string() + &creator.to_string(); @@ -48,21 +47,17 @@ pub fn func_init(ctx: &ScFuncContext, f: &InitContext) { // This function emits the Transfer event. // Input: // - PARAM_ACCOUNT: agentID -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 pub fn func_transfer(ctx: &ScFuncContext, f: &TransferContext) { let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.transfer.fail: wrong 'amount' parameter"); let balances = f.state.balances(); let source_agent = ctx.caller(); - let source_balance = balances.get_int64(&source_agent); + let source_balance = balances.get_uint64(&source_agent); ctx.require(source_balance.value() >= amount, "erc20.transfer.fail: not enough funds"); let target_agent = f.params.account().value(); - let target_balance = balances.get_int64(&target_agent); - let result = target_balance.value() + amount; - ctx.require(result >= 0, "erc20.transfer.fail: overflow"); - + let target_balance = balances.get_uint64(&target_agent); source_balance.set_value(source_balance.value() - amount); target_balance.set_value(target_balance.value() + amount); @@ -75,26 +70,23 @@ pub fn func_transfer(ctx: &ScFuncContext, f: &TransferContext) { // Input: // - PARAM_ACCOUNT: agentID the spender // - PARAM_RECIPIENT: agentID the target -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 pub fn func_transfer_from(ctx: &ScFuncContext, f: &TransferFromContext) { // validate parameters let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.transfer_from.fail: wrong 'amount' parameter"); // allowances are in the map under the name of the account let source_agent = f.params.account().value(); let allowances = f.state.all_allowances().get_allowances_for_agent(&source_agent); - let allowance = allowances.get_int64(&ctx.caller()); + let allowance = allowances.get_uint64(&ctx.caller()); ctx.require(allowance.value() >= amount, "erc20.transfer_from.fail: not enough allowance"); let balances = f.state.balances(); - let source_balance = balances.get_int64(&source_agent); + let source_balance = balances.get_uint64(&source_agent); ctx.require(source_balance.value() >= amount, "erc20.transfer_from.fail: not enough funds"); let target_agent = f.params.recipient().value(); - let target_balance = balances.get_int64(&target_agent); - let result = target_balance.value() + amount; - ctx.require(result >= 0, "erc20.transfer_from.fail: overflow"); + let target_balance = balances.get_uint64(&target_agent); source_balance.set_value(source_balance.value() - amount); target_balance.set_value(target_balance.value() + amount); @@ -109,11 +101,11 @@ pub fn func_transfer_from(ctx: &ScFuncContext, f: &TransferFromContext) { // - PARAM_ACCOUNT: agentID // - PARAM_DELEGATION: agentID // Output: -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 pub fn view_allowance(_ctx: &ScViewContext, f: &AllowanceContext) { // all allowances of the address 'owner' are stored in the map of the same name let allowances = f.state.all_allowances().get_allowances_for_agent(&f.params.account().value()); - let allow = allowances.get_int64(&f.params.delegation().value()).value(); + let allow = allowances.get_uint64(&f.params.delegation().value()).value(); f.results.amount().set_value(allow); } @@ -122,13 +114,13 @@ pub fn view_allowance(_ctx: &ScViewContext, f: &AllowanceContext) { // - PARAM_ACCOUNT: agentID pub fn view_balance_of(_ctx: &ScViewContext, f: &BalanceOfContext) { let balances = f.state.balances(); - let balance = balances.get_int64(&f.params.account().value()); + let balance = balances.get_uint64(&f.params.account().value()); f.results.amount().set_value(balance.value()); } // the view returns total supply set when creating the contract (a constant). // Output: -// - PARAM_SUPPLY: i64 +// - PARAM_SUPPLY: u64 pub fn view_total_supply(_ctx: &ScViewContext, f: &TotalSupplyContext) { f.results.supply().set_value(f.state.supply().value()); } diff --git a/contracts/wasm/erc20/src/events.rs b/contracts/wasm/erc20/src/events.rs index 74bf775813..5958f115b4 100644 --- a/contracts/wasm/erc20/src/events.rs +++ b/contracts/wasm/erc20/src/events.rs @@ -6,6 +6,7 @@ // Change the json schema instead #![allow(dead_code)] +#![allow(unused_mut)] use wasmlib::*; @@ -14,19 +15,19 @@ pub struct Erc20Events { impl Erc20Events { - pub fn approval(&self, amount: i64, owner: &ScAgentID, spender: &ScAgentID) { - let mut encoder = EventEncoder::new("erc20.approval"); - encoder.int64(amount); - encoder.agent_id(&owner); - encoder.agent_id(&spender); - encoder.emit(); + pub fn approval(&self, amount: u64, owner: &ScAgentID, spender: &ScAgentID) { + let mut evt = EventEncoder::new("erc20.approval"); + evt.encode(&uint64_to_string(amount)); + evt.encode(&agent_id_to_string(&owner)); + evt.encode(&agent_id_to_string(&spender)); + evt.emit(); } - pub fn transfer(&self, amount: i64, from: &ScAgentID, to: &ScAgentID) { - let mut encoder = EventEncoder::new("erc20.transfer"); - encoder.int64(amount); - encoder.agent_id(&from); - encoder.agent_id(&to); - encoder.emit(); + pub fn transfer(&self, amount: u64, from: &ScAgentID, to: &ScAgentID) { + let mut evt = EventEncoder::new("erc20.transfer"); + evt.encode(&uint64_to_string(amount)); + evt.encode(&agent_id_to_string(&from)); + evt.encode(&agent_id_to_string(&to)); + evt.emit(); } } diff --git a/contracts/wasm/erc20/src/keys.rs b/contracts/wasm/erc20/src/keys.rs deleted file mode 100644 index 44095bd456..0000000000 --- a/contracts/wasm/erc20/src/keys.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_ACCOUNT : usize = 0; -pub(crate) const IDX_PARAM_AMOUNT : usize = 1; -pub(crate) const IDX_PARAM_CREATOR : usize = 2; -pub(crate) const IDX_PARAM_DELEGATION : usize = 3; -pub(crate) const IDX_PARAM_RECIPIENT : usize = 4; -pub(crate) const IDX_PARAM_SUPPLY : usize = 5; - -pub(crate) const IDX_RESULT_AMOUNT : usize = 6; -pub(crate) const IDX_RESULT_SUPPLY : usize = 7; - -pub(crate) const IDX_STATE_ALL_ALLOWANCES : usize = 8; -pub(crate) const IDX_STATE_BALANCES : usize = 9; -pub(crate) const IDX_STATE_SUPPLY : usize = 10; - -pub const KEY_MAP_LEN: usize = 11; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_ACCOUNT, - PARAM_AMOUNT, - PARAM_CREATOR, - PARAM_DELEGATION, - PARAM_RECIPIENT, - PARAM_SUPPLY, - RESULT_AMOUNT, - RESULT_SUPPLY, - STATE_ALL_ALLOWANCES, - STATE_BALANCES, - STATE_SUPPLY, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/erc20/src/lib.rs b/contracts/wasm/erc20/src/lib.rs index e3bc083c0b..a2cdcee859 100644 --- a/contracts/wasm/erc20/src/lib.rs +++ b/contracts/wasm/erc20/src/lib.rs @@ -10,41 +10,55 @@ use erc20::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; use crate::events::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::typedefs::*; mod consts; mod contract; mod events; -mod keys; mod params; mod results; mod state; mod typedefs; + mod erc20; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_APPROVE, + FUNC_INIT, + FUNC_TRANSFER, + FUNC_TRANSFER_FROM, + VIEW_ALLOWANCE, + VIEW_BALANCE_OF, + VIEW_TOTAL_SUPPLY, + ], + funcs: &[ + func_approve_thunk, + func_init_thunk, + func_transfer_thunk, + func_transfer_from_thunk, + ], + views: &[ + view_allowance_thunk, + view_balance_of_thunk, + view_total_supply_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_APPROVE, func_approve_thunk); - exports.add_func(FUNC_INIT, func_init_thunk); - exports.add_func(FUNC_TRANSFER, func_transfer_thunk); - exports.add_func(FUNC_TRANSFER_FROM, func_transfer_from_thunk); - exports.add_view(VIEW_ALLOWANCE, view_allowance_thunk); - exports.add_view(VIEW_BALANCE_OF, view_balance_of_thunk); - exports.add_view(VIEW_TOTAL_SUPPLY, view_total_supply_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct ApproveContext { @@ -57,12 +71,8 @@ fn func_approve_thunk(ctx: &ScFuncContext) { ctx.log("erc20.funcApprove"); let f = ApproveContext { events: Erc20Events {}, - params: ImmutableApproveParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableApproveParams { proxy: params_proxy() }, + state: MutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.amount().exists(), "missing mandatory amount"); ctx.require(f.params.delegation().exists(), "missing mandatory delegation"); @@ -80,12 +90,8 @@ fn func_init_thunk(ctx: &ScFuncContext) { ctx.log("erc20.funcInit"); let f = InitContext { events: Erc20Events {}, - params: ImmutableInitParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableInitParams { proxy: params_proxy() }, + state: MutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.creator().exists(), "missing mandatory creator"); ctx.require(f.params.supply().exists(), "missing mandatory supply"); @@ -103,12 +109,8 @@ fn func_transfer_thunk(ctx: &ScFuncContext) { ctx.log("erc20.funcTransfer"); let f = TransferContext { events: Erc20Events {}, - params: ImmutableTransferParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableTransferParams { proxy: params_proxy() }, + state: MutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.amount().exists(), "missing mandatory amount"); @@ -126,12 +128,8 @@ fn func_transfer_from_thunk(ctx: &ScFuncContext) { ctx.log("erc20.funcTransferFrom"); let f = TransferFromContext { events: Erc20Events {}, - params: ImmutableTransferFromParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableTransferFromParams { proxy: params_proxy() }, + state: MutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.amount().exists(), "missing mandatory amount"); @@ -149,19 +147,14 @@ pub struct AllowanceContext { fn view_allowance_thunk(ctx: &ScViewContext) { ctx.log("erc20.viewAllowance"); let f = AllowanceContext { - params: ImmutableAllowanceParams { - id: OBJ_ID_PARAMS, - }, - results: MutableAllowanceResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableAllowanceParams { proxy: params_proxy() }, + results: MutableAllowanceResults { proxy: results_proxy() }, + state: ImmutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.delegation().exists(), "missing mandatory delegation"); view_allowance(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc20.viewAllowance ok"); } @@ -174,18 +167,13 @@ pub struct BalanceOfContext { fn view_balance_of_thunk(ctx: &ScViewContext) { ctx.log("erc20.viewBalanceOf"); let f = BalanceOfContext { - params: ImmutableBalanceOfParams { - id: OBJ_ID_PARAMS, - }, - results: MutableBalanceOfResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc20State { - id: OBJ_ID_STATE, - }, + params: ImmutableBalanceOfParams { proxy: params_proxy() }, + results: MutableBalanceOfResults { proxy: results_proxy() }, + state: ImmutableErc20State { proxy: state_proxy() }, }; ctx.require(f.params.account().exists(), "missing mandatory account"); view_balance_of(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc20.viewBalanceOf ok"); } @@ -197,13 +185,10 @@ pub struct TotalSupplyContext { fn view_total_supply_thunk(ctx: &ScViewContext) { ctx.log("erc20.viewTotalSupply"); let f = TotalSupplyContext { - results: MutableTotalSupplyResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc20State { - id: OBJ_ID_STATE, - }, + results: MutableTotalSupplyResults { proxy: results_proxy() }, + state: ImmutableErc20State { proxy: state_proxy() }, }; view_total_supply(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc20.viewTotalSupply ok"); } diff --git a/contracts/wasm/erc20/src/params.rs b/contracts/wasm/erc20/src/params.rs index a491640560..8c6e884652 100644 --- a/contracts/wasm/erc20/src/params.rs +++ b/contracts/wasm/erc20/src/params.rs @@ -9,188 +9,184 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableApproveParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableApproveParams { - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } pub fn delegation(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_DELEGATION.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_DELEGATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableApproveParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableApproveParams { - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } pub fn delegation(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_DELEGATION.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_DELEGATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableInitParams { pub fn creator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, idx_map(IDX_PARAM_CREATOR)) + ScImmutableAgentID::new(self.proxy.root(PARAM_CREATOR)) } - pub fn supply(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, idx_map(IDX_PARAM_SUPPLY)) + pub fn supply(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableInitParams { pub fn creator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, idx_map(IDX_PARAM_CREATOR)) + ScMutableAgentID::new(self.proxy.root(PARAM_CREATOR)) } - pub fn supply(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, idx_map(IDX_PARAM_SUPPLY)) + pub fn supply(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTransferParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTransferParams { pub fn account(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTransferParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTransferParams { pub fn account(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTransferFromParams { pub fn account(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } pub fn recipient(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_RECIPIENT.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_RECIPIENT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTransferFromParams { pub fn account(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_AMOUNT)) } pub fn recipient(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_RECIPIENT.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_RECIPIENT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableAllowanceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableAllowanceParams { pub fn account(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } pub fn delegation(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_DELEGATION.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_DELEGATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableAllowanceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableAllowanceParams { pub fn account(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } pub fn delegation(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_DELEGATION.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_DELEGATION)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceOfParams { pub fn account(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceOfParams { pub fn account(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_ACCOUNT.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_ACCOUNT)) } } diff --git a/contracts/wasm/erc20/src/results.rs b/contracts/wasm/erc20/src/results.rs index dd77540b94..1e8db6a2be 100644 --- a/contracts/wasm/erc20/src/results.rs +++ b/contracts/wasm/erc20/src/results.rs @@ -9,74 +9,70 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableAllowanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableAllowanceResults { - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableAllowanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableAllowanceResults { - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceOfResults { - pub fn amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceOfResults { - pub fn amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_AMOUNT.get_key_id()) + pub fn amount(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTotalSupplyResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTotalSupplyResults { - pub fn supply(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_SUPPLY.get_key_id()) + pub fn supply(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTotalSupplyResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTotalSupplyResults { - pub fn supply(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_SUPPLY.get_key_id()) + pub fn supply(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_SUPPLY)) } } diff --git a/contracts/wasm/erc20/src/state.rs b/contracts/wasm/erc20/src/state.rs index e1e0ff3283..a027e12ef2 100644 --- a/contracts/wasm/erc20/src/state.rs +++ b/contracts/wasm/erc20/src/state.rs @@ -9,82 +9,73 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableAllowancesForAgent { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableAllowancesForAgent { pub fn get_allowances_for_agent(&self, key: &ScAgentID) -> ImmutableAllowancesForAgent { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ImmutableAllowancesForAgent { obj_id: sub_id } + ImmutableAllowancesForAgent { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableErc20State { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableErc20State { pub fn all_allowances(&self) -> MapAgentIDToImmutableAllowancesForAgent { - let map_id = get_object_id(self.id, STATE_ALL_ALLOWANCES.get_key_id(), TYPE_MAP); - MapAgentIDToImmutableAllowancesForAgent { obj_id: map_id } + MapAgentIDToImmutableAllowancesForAgent { proxy: self.proxy.root(STATE_ALL_ALLOWANCES) } } - pub fn balances(&self) -> MapAgentIDToImmutableInt64 { - let map_id = get_object_id(self.id, STATE_BALANCES.get_key_id(), TYPE_MAP); - MapAgentIDToImmutableInt64 { obj_id: map_id } + pub fn balances(&self) -> MapAgentIDToImmutableUint64 { + MapAgentIDToImmutableUint64 { proxy: self.proxy.root(STATE_BALANCES) } } - pub fn supply(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_SUPPLY.get_key_id()) + pub fn supply(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableAllowancesForAgent { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableAllowancesForAgent { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_allowances_for_agent(&self, key: &ScAgentID) -> MutableAllowancesForAgent { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - MutableAllowancesForAgent { obj_id: sub_id } + MutableAllowancesForAgent { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableErc20State { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableErc20State { pub fn as_immutable(&self) -> ImmutableErc20State { - ImmutableErc20State { id: self.id } + ImmutableErc20State { proxy: self.proxy.root("") } } pub fn all_allowances(&self) -> MapAgentIDToMutableAllowancesForAgent { - let map_id = get_object_id(self.id, STATE_ALL_ALLOWANCES.get_key_id(), TYPE_MAP); - MapAgentIDToMutableAllowancesForAgent { obj_id: map_id } + MapAgentIDToMutableAllowancesForAgent { proxy: self.proxy.root(STATE_ALL_ALLOWANCES) } } - pub fn balances(&self) -> MapAgentIDToMutableInt64 { - let map_id = get_object_id(self.id, STATE_BALANCES.get_key_id(), TYPE_MAP); - MapAgentIDToMutableInt64 { obj_id: map_id } + pub fn balances(&self) -> MapAgentIDToMutableUint64 { + MapAgentIDToMutableUint64 { proxy: self.proxy.root(STATE_BALANCES) } } - pub fn supply(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_SUPPLY.get_key_id()) + pub fn supply(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_SUPPLY)) } } diff --git a/contracts/wasm/erc20/src/typedefs.rs b/contracts/wasm/erc20/src/typedefs.rs index dc638d395a..631a76063a 100644 --- a/contracts/wasm/erc20/src/typedefs.rs +++ b/contracts/wasm/erc20/src/typedefs.rs @@ -8,34 +8,34 @@ #![allow(dead_code)] use wasmlib::*; -use wasmlib::host::*; +use crate::*; -#[derive(Clone, Copy)] -pub struct MapAgentIDToImmutableInt64 { - pub(crate) obj_id: i32, +#[derive(Clone)] +pub struct MapAgentIDToImmutableUint64 { + pub(crate) proxy: Proxy, } -impl MapAgentIDToImmutableInt64 { - pub fn get_int64(&self, key: &ScAgentID) -> ScImmutableInt64 { - ScImmutableInt64::new(self.obj_id, key.get_key_id()) +impl MapAgentIDToImmutableUint64 { + pub fn get_uint64(&self, key: &ScAgentID) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.key(&agent_id_to_bytes(key))) } } -pub type ImmutableAllowancesForAgent = MapAgentIDToImmutableInt64; +pub type ImmutableAllowancesForAgent = MapAgentIDToImmutableUint64; -#[derive(Clone, Copy)] -pub struct MapAgentIDToMutableInt64 { - pub(crate) obj_id: i32, +#[derive(Clone)] +pub struct MapAgentIDToMutableUint64 { + pub(crate) proxy: Proxy, } -impl MapAgentIDToMutableInt64 { +impl MapAgentIDToMutableUint64 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } - pub fn get_int64(&self, key: &ScAgentID) -> ScMutableInt64 { - ScMutableInt64::new(self.obj_id, key.get_key_id()) + pub fn get_uint64(&self, key: &ScAgentID) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.key(&agent_id_to_bytes(key))) } } -pub type MutableAllowancesForAgent = MapAgentIDToMutableInt64; +pub type MutableAllowancesForAgent = MapAgentIDToMutableUint64; diff --git a/contracts/wasm/erc20/test/erc20_bg.wasm b/contracts/wasm/erc20/test/erc20_bg.wasm index cfb81b91db..a885398557 100644 Binary files a/contracts/wasm/erc20/test/erc20_bg.wasm and b/contracts/wasm/erc20/test/erc20_bg.wasm differ diff --git a/contracts/wasm/erc20/test/erc20_test.go b/contracts/wasm/erc20/test/erc20_test.go index 4c9737be4b..e4c1ffd7c1 100644 --- a/contracts/wasm/erc20/test/erc20_test.go +++ b/contracts/wasm/erc20/test/erc20_test.go @@ -6,7 +6,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/erc20/go/erc20" "github.com/iotaledger/wasp/packages/solo" "github.com/iotaledger/wasp/packages/vm/core" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -67,16 +67,16 @@ func checkErc20Allowance(ctx *wasmsolo.SoloContext, account, delegation *wasmsol func approve(ctx *wasmsolo.SoloContext, from, to *wasmsolo.SoloAgent, amount uint64) error { appr := erc20.ScFuncs.Approve(ctx.Sign(from)) appr.Params.Delegation().SetValue(to.ScAgentID()) - appr.Params.Amount().SetValue(int64(amount)) - appr.Func.TransferIotas(1).Post() + appr.Params.Amount().SetValue(amount) + appr.Func.Post() return ctx.Err } func transfer(ctx *wasmsolo.SoloContext, from, to *wasmsolo.SoloAgent, amount uint64) error { tx := erc20.ScFuncs.Transfer(ctx.Sign(from)) tx.Params.Account().SetValue(to.ScAgentID()) - tx.Params.Amount().SetValue(int64(amount)) - tx.Func.TransferIotas(1).Post() + tx.Params.Amount().SetValue(amount) + tx.Func.Post() return ctx.Err } @@ -84,8 +84,8 @@ func transferFrom(ctx *wasmsolo.SoloContext, delegate, from, to *wasmsolo.SoloAg tx := erc20.ScFuncs.TransferFrom(ctx.Sign(delegate)) tx.Params.Account().SetValue(from.ScAgentID()) tx.Params.Recipient().SetValue(to.ScAgentID()) - tx.Params.Amount().SetValue(int64(amount)) - tx.Func.TransferIotas(1).Post() + tx.Params.Amount().SetValue(amount) + tx.Func.Post() return ctx.Err } diff --git a/contracts/wasm/erc20/test/init_test.go b/contracts/wasm/erc20/test/init_test.go index 5bac03f74d..500b0aff50 100644 --- a/contracts/wasm/erc20/test/init_test.go +++ b/contracts/wasm/erc20/test/init_test.go @@ -6,7 +6,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/erc20/go/erc20" "github.com/iotaledger/wasp/packages/solo" "github.com/iotaledger/wasp/packages/vm/core" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) diff --git a/contracts/wasm/erc20/ts/erc20/consts.ts b/contracts/wasm/erc20/ts/erc20/consts.ts index 6912a924b5..d46d38ecad 100644 --- a/contracts/wasm/erc20/ts/erc20/consts.ts +++ b/contracts/wasm/erc20/ts/erc20/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "erc20"; export const ScDescription = "ERC-20 PoC for IOTA Smart Contracts"; -export const HScName = new wasmlib.ScHname(0x200e3733); +export const HScName = new wasmtypes.ScHname(0x200e3733); export const ParamAccount = "ac"; export const ParamAmount = "am"; @@ -33,10 +33,10 @@ export const ViewAllowance = "allowance"; export const ViewBalanceOf = "balanceOf"; export const ViewTotalSupply = "totalSupply"; -export const HFuncApprove = new wasmlib.ScHname(0xa0661268); -export const HFuncInit = new wasmlib.ScHname(0x1f44d644); -export const HFuncTransfer = new wasmlib.ScHname(0xa15da184); -export const HFuncTransferFrom = new wasmlib.ScHname(0xd5e0a602); -export const HViewAllowance = new wasmlib.ScHname(0x5e16006a); -export const HViewBalanceOf = new wasmlib.ScHname(0x67ef8df4); -export const HViewTotalSupply = new wasmlib.ScHname(0x9505e6ca); +export const HFuncApprove = new wasmtypes.ScHname(0xa0661268); +export const HFuncInit = new wasmtypes.ScHname(0x1f44d644); +export const HFuncTransfer = new wasmtypes.ScHname(0xa15da184); +export const HFuncTransferFrom = new wasmtypes.ScHname(0xd5e0a602); +export const HViewAllowance = new wasmtypes.ScHname(0x5e16006a); +export const HViewBalanceOf = new wasmtypes.ScHname(0x67ef8df4); +export const HViewTotalSupply = new wasmtypes.ScHname(0x9505e6ca); diff --git a/contracts/wasm/erc20/ts/erc20/contract.ts b/contracts/wasm/erc20/ts/erc20/contract.ts index d04ec0afa0..fc4c11cbb5 100644 --- a/contracts/wasm/erc20/ts/erc20/contract.ts +++ b/contracts/wasm/erc20/ts/erc20/contract.ts @@ -10,122 +10,124 @@ import * as sc from "./index"; export class ApproveCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncApprove); - params: sc.MutableApproveParams = new sc.MutableApproveParams(); + params: sc.MutableApproveParams = new sc.MutableApproveParams(wasmlib.ScView.nilProxy); } export class ApproveContext { events: sc.Erc20Events = new sc.Erc20Events(); - params: sc.ImmutableApproveParams = new sc.ImmutableApproveParams(); - state: sc.MutableErc20State = new sc.MutableErc20State(); + params: sc.ImmutableApproveParams = new sc.ImmutableApproveParams(wasmlib.paramsProxy()); + state: sc.MutableErc20State = new sc.MutableErc20State(wasmlib.ScState.proxy()); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); - params: sc.MutableInitParams = new sc.MutableInitParams(); + params: sc.MutableInitParams = new sc.MutableInitParams(wasmlib.ScView.nilProxy); } export class InitContext { events: sc.Erc20Events = new sc.Erc20Events(); - params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); - state: sc.MutableErc20State = new sc.MutableErc20State(); + params: sc.ImmutableInitParams = new sc.ImmutableInitParams(wasmlib.paramsProxy()); + state: sc.MutableErc20State = new sc.MutableErc20State(wasmlib.ScState.proxy()); } export class TransferCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTransfer); - params: sc.MutableTransferParams = new sc.MutableTransferParams(); + params: sc.MutableTransferParams = new sc.MutableTransferParams(wasmlib.ScView.nilProxy); } export class TransferContext { events: sc.Erc20Events = new sc.Erc20Events(); - params: sc.ImmutableTransferParams = new sc.ImmutableTransferParams(); - state: sc.MutableErc20State = new sc.MutableErc20State(); + params: sc.ImmutableTransferParams = new sc.ImmutableTransferParams(wasmlib.paramsProxy()); + state: sc.MutableErc20State = new sc.MutableErc20State(wasmlib.ScState.proxy()); } export class TransferFromCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTransferFrom); - params: sc.MutableTransferFromParams = new sc.MutableTransferFromParams(); + params: sc.MutableTransferFromParams = new sc.MutableTransferFromParams(wasmlib.ScView.nilProxy); } export class TransferFromContext { events: sc.Erc20Events = new sc.Erc20Events(); - params: sc.ImmutableTransferFromParams = new sc.ImmutableTransferFromParams(); - state: sc.MutableErc20State = new sc.MutableErc20State(); + params: sc.ImmutableTransferFromParams = new sc.ImmutableTransferFromParams(wasmlib.paramsProxy()); + state: sc.MutableErc20State = new sc.MutableErc20State(wasmlib.ScState.proxy()); } export class AllowanceCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewAllowance); - params: sc.MutableAllowanceParams = new sc.MutableAllowanceParams(); - results: sc.ImmutableAllowanceResults = new sc.ImmutableAllowanceResults(); + params: sc.MutableAllowanceParams = new sc.MutableAllowanceParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableAllowanceResults = new sc.ImmutableAllowanceResults(wasmlib.ScView.nilProxy); } export class AllowanceContext { - params: sc.ImmutableAllowanceParams = new sc.ImmutableAllowanceParams(); - results: sc.MutableAllowanceResults = new sc.MutableAllowanceResults(); - state: sc.ImmutableErc20State = new sc.ImmutableErc20State(); + params: sc.ImmutableAllowanceParams = new sc.ImmutableAllowanceParams(wasmlib.paramsProxy()); + results: sc.MutableAllowanceResults = new sc.MutableAllowanceResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc20State = new sc.ImmutableErc20State(wasmlib.ScState.proxy()); } export class BalanceOfCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBalanceOf); - params: sc.MutableBalanceOfParams = new sc.MutableBalanceOfParams(); - results: sc.ImmutableBalanceOfResults = new sc.ImmutableBalanceOfResults(); + params: sc.MutableBalanceOfParams = new sc.MutableBalanceOfParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableBalanceOfResults = new sc.ImmutableBalanceOfResults(wasmlib.ScView.nilProxy); } export class BalanceOfContext { - params: sc.ImmutableBalanceOfParams = new sc.ImmutableBalanceOfParams(); - results: sc.MutableBalanceOfResults = new sc.MutableBalanceOfResults(); - state: sc.ImmutableErc20State = new sc.ImmutableErc20State(); + params: sc.ImmutableBalanceOfParams = new sc.ImmutableBalanceOfParams(wasmlib.paramsProxy()); + results: sc.MutableBalanceOfResults = new sc.MutableBalanceOfResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc20State = new sc.ImmutableErc20State(wasmlib.ScState.proxy()); } export class TotalSupplyCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTotalSupply); - results: sc.ImmutableTotalSupplyResults = new sc.ImmutableTotalSupplyResults(); + results: sc.ImmutableTotalSupplyResults = new sc.ImmutableTotalSupplyResults(wasmlib.ScView.nilProxy); } export class TotalSupplyContext { - results: sc.MutableTotalSupplyResults = new sc.MutableTotalSupplyResults(); - state: sc.ImmutableErc20State = new sc.ImmutableErc20State(); + results: sc.MutableTotalSupplyResults = new sc.MutableTotalSupplyResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc20State = new sc.ImmutableErc20State(wasmlib.ScState.proxy()); } export class ScFuncs { - static approve(ctx: wasmlib.ScFuncCallContext): ApproveCall { - let f = new ApproveCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static init(ctx: wasmlib.ScFuncCallContext): InitCall { - let f = new InitCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static transfer(ctx: wasmlib.ScFuncCallContext): TransferCall { - let f = new TransferCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static transferFrom(ctx: wasmlib.ScFuncCallContext): TransferFromCall { - let f = new TransferFromCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static allowance(ctx: wasmlib.ScViewCallContext): AllowanceCall { - let f = new AllowanceCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static balanceOf(ctx: wasmlib.ScViewCallContext): BalanceOfCall { - let f = new BalanceOfCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static totalSupply(ctx: wasmlib.ScViewCallContext): TotalSupplyCall { - let f = new TotalSupplyCall(); - f.func.setPtrs(null, f.results); - return f; - } + static approve(_ctx: wasmlib.ScFuncCallContext): ApproveCall { + const f = new ApproveCall(); + f.params = new sc.MutableApproveParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static init(_ctx: wasmlib.ScFuncCallContext): InitCall { + const f = new InitCall(); + f.params = new sc.MutableInitParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static transfer(_ctx: wasmlib.ScFuncCallContext): TransferCall { + const f = new TransferCall(); + f.params = new sc.MutableTransferParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static transferFrom(_ctx: wasmlib.ScFuncCallContext): TransferFromCall { + const f = new TransferFromCall(); + f.params = new sc.MutableTransferFromParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static allowance(_ctx: wasmlib.ScViewCallContext): AllowanceCall { + const f = new AllowanceCall(); + f.params = new sc.MutableAllowanceParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableAllowanceResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static balanceOf(_ctx: wasmlib.ScViewCallContext): BalanceOfCall { + const f = new BalanceOfCall(); + f.params = new sc.MutableBalanceOfParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableBalanceOfResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static totalSupply(_ctx: wasmlib.ScViewCallContext): TotalSupplyCall { + const f = new TotalSupplyCall(); + f.results = new sc.ImmutableTotalSupplyResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/erc20/ts/erc20/erc20.ts b/contracts/wasm/erc20/ts/erc20/erc20.ts index fbd3d19d3f..5a89cec34f 100644 --- a/contracts/wasm/erc20/ts/erc20/erc20.ts +++ b/contracts/wasm/erc20/ts/erc20/erc20.ts @@ -10,15 +10,14 @@ import * as sc from "./index"; // Sets the allowance value for delegated account // inputs: // - PARAM_DELEGATION: agentID -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 export function funcApprove(ctx: wasmlib.ScFuncContext, f: sc.ApproveContext): void { let delegation = f.params.delegation().value(); let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.approve.fail: wrong 'amount' parameter"); // all allowances are in the map under the name of he owner let allowances = f.state.allAllowances().getAllowancesForAgent(ctx.caller()); - allowances.getInt64(delegation).setValue(amount); + allowances.getUint64(delegation).setValue(amount); f.events.approval(amount, ctx.caller(), delegation) } @@ -36,7 +35,7 @@ export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { // so, owner of the initial supply must be provided as a parameter PARAM_CREATOR to constructor (onInit) // assign the whole supply to creator let creator = f.params.creator().value(); - f.state.balances().getInt64(creator).setValue(supply); + f.state.balances().getUint64(creator).setValue(supply); let t = "erc20.onInit.success. Supply: " + supply.toString() + ", creator:" + creator.toString(); @@ -47,20 +46,17 @@ export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { // This function emits the Transfer event. // Input: // - PARAM_ACCOUNT: agentID -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 export function funcTransfer(ctx: wasmlib.ScFuncContext, f: sc.TransferContext): void { let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.transfer.fail: wrong 'amount' parameter"); let balances = f.state.balances(); let sourceAgent = ctx.caller(); - let sourceBalance = balances.getInt64(sourceAgent); + let sourceBalance = balances.getUint64(sourceAgent); ctx.require(sourceBalance.value() >= amount, "erc20.transfer.fail: not enough funds"); let targetAgent = f.params.account().value(); - let targetBalance = balances.getInt64(targetAgent); - let result = targetBalance.value() + amount; - ctx.require(result >= 0, "erc20.transfer.fail: overflow"); + let targetBalance = balances.getUint64(targetAgent); sourceBalance.setValue(sourceBalance.value() - amount); targetBalance.setValue(targetBalance.value() + amount); @@ -74,26 +70,23 @@ export function funcTransfer(ctx: wasmlib.ScFuncContext, f: sc.TransferContext): // Input: // - PARAM_ACCOUNT: agentID the spender // - PARAM_RECIPIENT: agentID the target -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 export function funcTransferFrom(ctx: wasmlib.ScFuncContext, f: sc.TransferFromContext): void { // validate parameters let amount = f.params.amount().value(); - ctx.require(amount >= 0, "erc20.transferFrom.fail: wrong 'amount' parameter"); // allowances are in the map under the name of the account let sourceAgent = f.params.account().value(); let allowances = f.state.allAllowances().getAllowancesForAgent(sourceAgent); - let allowance = allowances.getInt64(ctx.caller()); + let allowance = allowances.getUint64(ctx.caller()); ctx.require(allowance.value() >= amount, "erc20.transferFrom.fail: not enough allowance"); let balances = f.state.balances(); - let sourceBalance = balances.getInt64(sourceAgent); + let sourceBalance = balances.getUint64(sourceAgent); ctx.require(sourceBalance.value() >= amount, "erc20.transferFrom.fail: not enough funds"); let targetAgent = f.params.recipient().value(); - let recipientBalance = balances.getInt64(targetAgent); - let result = recipientBalance.value() + amount; - ctx.require(result >= 0, "erc20.transferFrom.fail: overflow"); + let recipientBalance = balances.getUint64(targetAgent); sourceBalance.setValue(sourceBalance.value() - amount); recipientBalance.setValue(recipientBalance.value() + amount); @@ -108,11 +101,11 @@ export function funcTransferFrom(ctx: wasmlib.ScFuncContext, f: sc.TransferFromC // - PARAM_ACCOUNT: agentID // - PARAM_DELEGATION: agentID // Output: -// - PARAM_AMOUNT: i64 +// - PARAM_AMOUNT: u64 export function viewAllowance(ctx: wasmlib.ScViewContext, f: sc.AllowanceContext): void { // all allowances of the address 'owner' are stored in the map of the same name let allowances = f.state.allAllowances().getAllowancesForAgent(f.params.account().value()); - let allow = allowances.getInt64(f.params.delegation().value()).value(); + let allow = allowances.getUint64(f.params.delegation().value()).value(); f.results.amount().setValue(allow); } @@ -121,13 +114,13 @@ export function viewAllowance(ctx: wasmlib.ScViewContext, f: sc.AllowanceContext // - PARAM_ACCOUNT: agentID export function viewBalanceOf(ctx: wasmlib.ScViewContext, f: sc.BalanceOfContext): void { let balances = f.state.balances(); - let balance = balances.getInt64(f.params.account().value()); + let balance = balances.getUint64(f.params.account().value()); f.results.amount().setValue(balance.value()); } // the view returns total supply set when creating the contract (a constant). // Output: -// - PARAM_SUPPLY: i64 +// - PARAM_SUPPLY: u64 export function viewTotalSupply(ctx: wasmlib.ScViewContext, f: sc.TotalSupplyContext): void { f.results.supply().setValue(f.state.supply().value()); } diff --git a/contracts/wasm/erc20/ts/erc20/events.ts b/contracts/wasm/erc20/ts/erc20/events.ts index a8dd067940..6bff67427c 100644 --- a/contracts/wasm/erc20/ts/erc20/events.ts +++ b/contracts/wasm/erc20/ts/erc20/events.ts @@ -6,22 +6,23 @@ // Change the json schema instead import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Erc20Events { - approval(amount: i64, owner: wasmlib.ScAgentID, spender: wasmlib.ScAgentID): void { - new wasmlib.EventEncoder("erc20.approval"). - int64(amount). - agentID(owner). - agentID(spender). - emit(); + approval(amount: u64, owner: wasmtypes.ScAgentID, spender: wasmtypes.ScAgentID): void { + const evt = new wasmlib.EventEncoder("erc20.approval"); + evt.encode(wasmtypes.uint64ToString(amount)); + evt.encode(wasmtypes.agentIDToString(owner)); + evt.encode(wasmtypes.agentIDToString(spender)); + evt.emit(); } - transfer(amount: i64, from: wasmlib.ScAgentID, to: wasmlib.ScAgentID): void { - new wasmlib.EventEncoder("erc20.transfer"). - int64(amount). - agentID(from). - agentID(to). - emit(); + transfer(amount: u64, from: wasmtypes.ScAgentID, to: wasmtypes.ScAgentID): void { + const evt = new wasmlib.EventEncoder("erc20.transfer"); + evt.encode(wasmtypes.uint64ToString(amount)); + evt.encode(wasmtypes.agentIDToString(from)); + evt.encode(wasmtypes.agentIDToString(to)); + evt.emit(); } } diff --git a/contracts/wasm/erc20/ts/erc20/index.ts b/contracts/wasm/erc20/ts/erc20/index.ts index 9411e9de15..6e1f5116e4 100644 --- a/contracts/wasm/erc20/ts/erc20/index.ts +++ b/contracts/wasm/erc20/ts/erc20/index.ts @@ -10,7 +10,6 @@ export * from "./erc20"; export * from "./consts"; export * from "./contract"; export * from "./events"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/erc20/ts/erc20/keys.ts b/contracts/wasm/erc20/ts/erc20/keys.ts deleted file mode 100644 index 217222f5ce..0000000000 --- a/contracts/wasm/erc20/ts/erc20/keys.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamAccount = 0; -export const IdxParamAmount = 1; -export const IdxParamCreator = 2; -export const IdxParamDelegation = 3; -export const IdxParamRecipient = 4; -export const IdxParamSupply = 5; - -export const IdxResultAmount = 6; -export const IdxResultSupply = 7; - -export const IdxStateAllAllowances = 8; -export const IdxStateBalances = 9; -export const IdxStateSupply = 10; - -export let keyMap: string[] = [ - sc.ParamAccount, - sc.ParamAmount, - sc.ParamCreator, - sc.ParamDelegation, - sc.ParamRecipient, - sc.ParamSupply, - sc.ResultAmount, - sc.ResultSupply, - sc.StateAllAllowances, - sc.StateBalances, - sc.StateSupply, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/erc20/ts/erc20/lib.ts b/contracts/wasm/erc20/ts/erc20/lib.ts index 7b15f7fde9..ddc18bb409 100644 --- a/contracts/wasm/erc20/ts/erc20/lib.ts +++ b/contracts/wasm/erc20/ts/erc20/lib.ts @@ -8,30 +8,40 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncApprove, + sc.FuncInit, + sc.FuncTransfer, + sc.FuncTransferFrom, + sc.ViewAllowance, + sc.ViewBalanceOf, + sc.ViewTotalSupply, + ], + funcs: [ + funcApproveThunk, + funcInitThunk, + funcTransferThunk, + funcTransferFromThunk, + ], + views: [ + viewAllowanceThunk, + viewBalanceOfThunk, + viewTotalSupplyThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncApprove, funcApproveThunk); - exports.addFunc(sc.FuncInit, funcInitThunk); - exports.addFunc(sc.FuncTransfer, funcTransferThunk); - exports.addFunc(sc.FuncTransferFrom, funcTransferFromThunk); - exports.addView(sc.ViewAllowance, viewAllowanceThunk); - exports.addView(sc.ViewBalanceOf, viewBalanceOfThunk); - exports.addView(sc.ViewTotalSupply, viewTotalSupplyThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcApproveThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc20.funcApprove"); let f = new sc.ApproveContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.amount().exists(), "missing mandatory amount"); ctx.require(f.params.delegation().exists(), "missing mandatory delegation"); sc.funcApprove(ctx, f); @@ -41,8 +51,6 @@ function funcApproveThunk(ctx: wasmlib.ScFuncContext): void { function funcInitThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc20.funcInit"); let f = new sc.InitContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.creator().exists(), "missing mandatory creator"); ctx.require(f.params.supply().exists(), "missing mandatory supply"); sc.funcInit(ctx, f); @@ -52,8 +60,6 @@ function funcInitThunk(ctx: wasmlib.ScFuncContext): void { function funcTransferThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc20.funcTransfer"); let f = new sc.TransferContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.amount().exists(), "missing mandatory amount"); sc.funcTransfer(ctx, f); @@ -63,8 +69,6 @@ function funcTransferThunk(ctx: wasmlib.ScFuncContext): void { function funcTransferFromThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc20.funcTransferFrom"); let f = new sc.TransferFromContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.amount().exists(), "missing mandatory amount"); ctx.require(f.params.recipient().exists(), "missing mandatory recipient"); @@ -75,31 +79,32 @@ function funcTransferFromThunk(ctx: wasmlib.ScFuncContext): void { function viewAllowanceThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc20.viewAllowance"); let f = new sc.AllowanceContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableAllowanceResults(results.asProxy()); ctx.require(f.params.account().exists(), "missing mandatory account"); ctx.require(f.params.delegation().exists(), "missing mandatory delegation"); sc.viewAllowance(ctx, f); + ctx.results(results); ctx.log("erc20.viewAllowance ok"); } function viewBalanceOfThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc20.viewBalanceOf"); let f = new sc.BalanceOfContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableBalanceOfResults(results.asProxy()); ctx.require(f.params.account().exists(), "missing mandatory account"); sc.viewBalanceOf(ctx, f); + ctx.results(results); ctx.log("erc20.viewBalanceOf ok"); } function viewTotalSupplyThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc20.viewTotalSupply"); let f = new sc.TotalSupplyContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableTotalSupplyResults(results.asProxy()); sc.viewTotalSupply(ctx, f); + ctx.results(results); ctx.log("erc20.viewTotalSupply ok"); } diff --git a/contracts/wasm/erc20/ts/erc20/params.ts b/contracts/wasm/erc20/ts/erc20/params.ts index 00e4d9d20e..9db3cfe80e 100644 --- a/contracts/wasm/erc20/ts/erc20/params.ts +++ b/contracts/wasm/erc20/ts/erc20/params.ts @@ -5,125 +5,125 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableApproveParams extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); +export class ImmutableApproveParams extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamAmount)); } - delegation(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDelegation)); + delegation(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamDelegation)); } } -export class MutableApproveParams extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); +export class MutableApproveParams extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamAmount)); } - delegation(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDelegation)); + delegation(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamDelegation)); } } -export class ImmutableInitParams extends wasmlib.ScMapID { - creator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, sc.idxMap[sc.IdxParamCreator]); +export class ImmutableInitParams extends wasmtypes.ScProxy { + creator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamCreator)); } - supply(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, sc.idxMap[sc.IdxParamSupply]); + supply(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamSupply)); } } -export class MutableInitParams extends wasmlib.ScMapID { - creator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, sc.idxMap[sc.IdxParamCreator]); +export class MutableInitParams extends wasmtypes.ScProxy { + creator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamCreator)); } - supply(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, sc.idxMap[sc.IdxParamSupply]); + supply(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamSupply)); } } -export class ImmutableTransferParams extends wasmlib.ScMapID { - account(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class ImmutableTransferParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAccount)); } - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamAmount)); } } -export class MutableTransferParams extends wasmlib.ScMapID { - account(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class MutableTransferParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAccount)); } - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamAmount)); } } -export class ImmutableTransferFromParams extends wasmlib.ScMapID { - account(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class ImmutableTransferFromParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAccount)); } - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamAmount)); } - recipient(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamRecipient)); + recipient(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamRecipient)); } } -export class MutableTransferFromParams extends wasmlib.ScMapID { - account(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class MutableTransferFromParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAccount)); } - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamAmount)); + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamAmount)); } - recipient(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamRecipient)); + recipient(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamRecipient)); } } -export class ImmutableAllowanceParams extends wasmlib.ScMapID { - account(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class ImmutableAllowanceParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAccount)); } - delegation(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDelegation)); + delegation(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamDelegation)); } } -export class MutableAllowanceParams extends wasmlib.ScMapID { - account(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class MutableAllowanceParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAccount)); } - delegation(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDelegation)); + delegation(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamDelegation)); } } -export class ImmutableBalanceOfParams extends wasmlib.ScMapID { - account(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class ImmutableBalanceOfParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAccount)); } } -export class MutableBalanceOfParams extends wasmlib.ScMapID { - account(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAccount)); +export class MutableBalanceOfParams extends wasmtypes.ScProxy { + account(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAccount)); } } diff --git a/contracts/wasm/erc20/ts/erc20/results.ts b/contracts/wasm/erc20/ts/erc20/results.ts index 21b795a702..535b149b0c 100644 --- a/contracts/wasm/erc20/ts/erc20/results.ts +++ b/contracts/wasm/erc20/ts/erc20/results.ts @@ -5,41 +5,41 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableAllowanceResults extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class ImmutableAllowanceResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class MutableAllowanceResults extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class MutableAllowanceResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class ImmutableBalanceOfResults extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class ImmutableBalanceOfResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class MutableBalanceOfResults extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class MutableBalanceOfResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class ImmutableTotalSupplyResults extends wasmlib.ScMapID { - supply(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultSupply)); +export class ImmutableTotalSupplyResults extends wasmtypes.ScProxy { + supply(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultSupply)); } } -export class MutableTotalSupplyResults extends wasmlib.ScMapID { - supply(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultSupply)); +export class MutableTotalSupplyResults extends wasmtypes.ScProxy { + supply(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultSupply)); } } diff --git a/contracts/wasm/erc20/ts/erc20/state.ts b/contracts/wasm/erc20/ts/erc20/state.ts index 9b91699eb3..639a743f47 100644 --- a/contracts/wasm/erc20/ts/erc20/state.ts +++ b/contracts/wasm/erc20/ts/erc20/state.ts @@ -5,73 +5,55 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapAgentIDToImmutableAllowancesForAgent { - objID: i32; +export class MapAgentIDToImmutableAllowancesForAgent extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getAllowancesForAgent(key: wasmlib.ScAgentID): sc.ImmutableAllowancesForAgent { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.ImmutableAllowancesForAgent(subID); - } + getAllowancesForAgent(key: wasmtypes.ScAgentID): sc.ImmutableAllowancesForAgent { + return new sc.ImmutableAllowancesForAgent(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class ImmutableErc20State extends wasmlib.ScMapID { - allAllowances(): sc.MapAgentIDToImmutableAllowancesForAgent { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateAllAllowances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToImmutableAllowancesForAgent(mapID); +export class ImmutableErc20State extends wasmtypes.ScProxy { + allAllowances(): sc.MapAgentIDToImmutableAllowancesForAgent { + return new sc.MapAgentIDToImmutableAllowancesForAgent(this.proxy.root(sc.StateAllAllowances)); } - balances(): sc.MapAgentIDToImmutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBalances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToImmutableInt64(mapID); + balances(): sc.MapAgentIDToImmutableUint64 { + return new sc.MapAgentIDToImmutableUint64(this.proxy.root(sc.StateBalances)); } - supply(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateSupply)); + supply(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateSupply)); } } -export class MapAgentIDToMutableAllowancesForAgent { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableAllowancesForAgent extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getAllowancesForAgent(key: wasmlib.ScAgentID): sc.MutableAllowancesForAgent { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.MutableAllowancesForAgent(subID); - } + getAllowancesForAgent(key: wasmtypes.ScAgentID): sc.MutableAllowancesForAgent { + return new sc.MutableAllowancesForAgent(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MutableErc20State extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableErc20State { - const imm = new sc.ImmutableErc20State(); - imm.mapID = this.mapID; - return imm; +export class MutableErc20State extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableErc20State { + return new sc.ImmutableErc20State(this.proxy); } - allAllowances(): sc.MapAgentIDToMutableAllowancesForAgent { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateAllAllowances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToMutableAllowancesForAgent(mapID); + allAllowances(): sc.MapAgentIDToMutableAllowancesForAgent { + return new sc.MapAgentIDToMutableAllowancesForAgent(this.proxy.root(sc.StateAllAllowances)); } - balances(): sc.MapAgentIDToMutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBalances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToMutableInt64(mapID); + balances(): sc.MapAgentIDToMutableUint64 { + return new sc.MapAgentIDToMutableUint64(this.proxy.root(sc.StateBalances)); } - supply(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateSupply)); + supply(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateSupply)); } } diff --git a/contracts/wasm/erc20/ts/erc20/typedefs.ts b/contracts/wasm/erc20/ts/erc20/typedefs.ts index 2d09733fac..b6f0eb67cb 100644 --- a/contracts/wasm/erc20/ts/erc20/typedefs.ts +++ b/contracts/wasm/erc20/ts/erc20/typedefs.ts @@ -5,39 +5,29 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapAgentIDToImmutableInt64 { - objID: i32; +export class MapAgentIDToImmutableUint64 extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getInt64(key: wasmlib.ScAgentID): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAgentID): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class ImmutableAllowancesForAgent extends MapAgentIDToImmutableInt64 { -}; - -export class MapAgentIDToMutableInt64 { - objID: i32; +export class ImmutableAllowancesForAgent extends MapAgentIDToImmutableUint64 { +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableUint64 extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getInt64(key: wasmlib.ScAgentID): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAgentID): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MutableAllowancesForAgent extends MapAgentIDToMutableInt64 { -}; +export class MutableAllowancesForAgent extends MapAgentIDToMutableUint64 { +} diff --git a/contracts/wasm/erc721/Cargo.toml b/contracts/wasm/erc721/Cargo.toml index 8485099a71..883bb82695 100644 --- a/contracts/wasm/erc721/Cargo.toml +++ b/contracts/wasm/erc721/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } console_error_panic_hook = { version = "0.1.6", optional = true } wee_alloc = { version = "0.4.5", optional = true } diff --git a/contracts/wasm/erc721/README.md b/contracts/wasm/erc721/README.md index 01fbc435e3..a56eef0eb6 100644 --- a/contracts/wasm/erc721/README.md +++ b/contracts/wasm/erc721/README.md @@ -2,25 +2,25 @@ ### Deploy new chain (optional) -```bash +```shell $ ./wasp-cli chain deploy --committee=0 --quorum=1 --chain=wasptest --description="ArgentinaHub" # You can replace the amount of committees and quorum by your needs ``` ### Deposit IOTA tokens to the chain -```bash +```shell $ ./wasp-cli chain deposit IOTA:1000 ``` ### Deploy contract -```bash +```shell ./wasp-cli --verbose chain deploy-contract wasmtime erc721 "Argentina Hub" contracts/wasm/erc721/pkg/nft_bg.wasm string n string ArgHub string s string ARH # n: Name # s: Symbol ``` ### Mint new erc721 -```bash +```shell ./wasp-cli --verbose chain post-request erc721 mint string tokenid int string tokenuri string #Example @@ -29,7 +29,7 @@ string tokenuri string ``` ### Transfer ownership of the erc721 -```bash +```shell ./wasp-cli --verbose chain post-request erc721 transferFrom string from agentid string to agentid string tokenid int # Example # = A/1urERbzXL1iraoW2jMvkLdFuMmPS711BYtA8u4L6sS53::00000000 @@ -38,7 +38,7 @@ string tokenuri string ``` ### Approves another agentid to transfer the given token -```bash +```shell ./wasp-cli --verbose chain post-request erc721 approve string to agentid string tokenid int # Example # = A/1urERbzXL1iraoW2jMvkLdFuMmPS711BYtA8u4L6sS53::00000000 @@ -46,24 +46,24 @@ string tokenuri string ``` ### Balance Of -```bash +```shell ./wasp-cli chain call-view erc721 balanceOf string account agentid | ./wasp-cli decode string amount int # Example # = A/1urERbzXL1iraoW2jMvkLdFuMmPS711BYtA8u4L6sS53::00000000 ``` ### Name of contract -```bash +```shell ./wasp-cli chain call-view erc721 name | ./wasp-cli decode string name string ``` ### Symbol of contract -```bash +```shell ./wasp-cli chain call-view erc721 name | ./wasp-cli decode string name string ``` ### Check agent id if it's approved (1 = true ; 0 = false) -```bash +```shell ./wasp-cli chain call-view erc721 isApproved string tokenid int string operator agentid | ./wasp-cli decode string approved int # Example # = 73798465 @@ -71,15 +71,15 @@ string tokenuri string ``` ### Get token URI -```bash +```shell ./wasp-cli chain call-view erc721 tokenURI string tokenid int | ./wasp-cli decode string uri string # Example # = 73798465 ``` ### Set approval for all (1 = true ; 0 = false) -```bash +```shell ./wasp-cli --verbose chain post-request erc721 setApprovalForAll string operator agentid string approved int 1 # Example # = A/12uApMh48Nq9EZGB8idco4W5NpZtyu6vv4sXpZuP5FUKs::00000000 -``` \ No newline at end of file +``` diff --git a/contracts/wasm/erc721/go/erc721/consts.go b/contracts/wasm/erc721/go/erc721/consts.go index a40a421910..b5d8b0ad3a 100644 --- a/contracts/wasm/erc721/go/erc721/consts.go +++ b/contracts/wasm/erc721/go/erc721/consts.go @@ -7,12 +7,12 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "erc721" ScDescription = "ERC-721 NFT PoC for IOTA Smart Contracts" - HScName = wasmlib.ScHname(0xd967c216) + HScName = wasmtypes.ScHname(0xd967c216) ) const ( @@ -67,18 +67,18 @@ const ( ) const ( - HFuncApprove = wasmlib.ScHname(0xa0661268) - HFuncBurn = wasmlib.ScHname(0x7bc1efb1) - HFuncInit = wasmlib.ScHname(0x1f44d644) - HFuncMint = wasmlib.ScHname(0xa29addcf) - HFuncSafeTransferFrom = wasmlib.ScHname(0x130ce158) - HFuncSetApprovalForAll = wasmlib.ScHname(0xb8d8c776) - HFuncTransferFrom = wasmlib.ScHname(0xd5e0a602) - HViewBalanceOf = wasmlib.ScHname(0x67ef8df4) - HViewGetApproved = wasmlib.ScHname(0xbe34b6ba) - HViewIsApprovedForAll = wasmlib.ScHname(0x3251b0f0) - HViewName = wasmlib.ScHname(0x0df7da3a) - HViewOwnerOf = wasmlib.ScHname(0x1246f5ad) - HViewSymbol = wasmlib.ScHname(0x3e93d19b) - HViewTokenURI = wasmlib.ScHname(0x4e1a7397) + HFuncApprove = wasmtypes.ScHname(0xa0661268) + HFuncBurn = wasmtypes.ScHname(0x7bc1efb1) + HFuncInit = wasmtypes.ScHname(0x1f44d644) + HFuncMint = wasmtypes.ScHname(0xa29addcf) + HFuncSafeTransferFrom = wasmtypes.ScHname(0x130ce158) + HFuncSetApprovalForAll = wasmtypes.ScHname(0xb8d8c776) + HFuncTransferFrom = wasmtypes.ScHname(0xd5e0a602) + HViewBalanceOf = wasmtypes.ScHname(0x67ef8df4) + HViewGetApproved = wasmtypes.ScHname(0xbe34b6ba) + HViewIsApprovedForAll = wasmtypes.ScHname(0x3251b0f0) + HViewName = wasmtypes.ScHname(0x0df7da3a) + HViewOwnerOf = wasmtypes.ScHname(0x1246f5ad) + HViewSymbol = wasmtypes.ScHname(0x3e93d19b) + HViewTokenURI = wasmtypes.ScHname(0x4e1a7397) ) diff --git a/contracts/wasm/erc721/go/erc721/contract.go b/contracts/wasm/erc721/go/erc721/contract.go index 258858e677..903a910922 100644 --- a/contracts/wasm/erc721/go/erc721/contract.go +++ b/contracts/wasm/erc721/go/erc721/contract.go @@ -7,7 +7,7 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type ApproveCall struct { Func *wasmlib.ScFunc @@ -90,84 +90,89 @@ var ScFuncs Funcs func (sc Funcs) Approve(ctx wasmlib.ScFuncCallContext) *ApproveCall { f := &ApproveCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncApprove)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Burn(ctx wasmlib.ScFuncCallContext) *BurnCall { f := &BurnCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncBurn)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Init(ctx wasmlib.ScFuncCallContext) *InitCall { - f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit, keyMap[:], idxMap[:])} - f.Func.SetPtrs(&f.Params.id, nil) + f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Mint(ctx wasmlib.ScFuncCallContext) *MintCall { f := &MintCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMint)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SafeTransferFrom(ctx wasmlib.ScFuncCallContext) *SafeTransferFromCall { f := &SafeTransferFromCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSafeTransferFrom)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetApprovalForAll(ctx wasmlib.ScFuncCallContext) *SetApprovalForAllCall { f := &SetApprovalForAllCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetApprovalForAll)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) TransferFrom(ctx wasmlib.ScFuncCallContext) *TransferFromCall { f := &TransferFromCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferFrom)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) BalanceOf(ctx wasmlib.ScViewCallContext) *BalanceOfCall { f := &BalanceOfCall{Func: wasmlib.NewScView(ctx, HScName, HViewBalanceOf)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetApproved(ctx wasmlib.ScViewCallContext) *GetApprovedCall { f := &GetApprovedCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetApproved)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) IsApprovedForAll(ctx wasmlib.ScViewCallContext) *IsApprovedForAllCall { f := &IsApprovedForAllCall{Func: wasmlib.NewScView(ctx, HScName, HViewIsApprovedForAll)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) Name(ctx wasmlib.ScViewCallContext) *NameCall { f := &NameCall{Func: wasmlib.NewScView(ctx, HScName, HViewName)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) OwnerOf(ctx wasmlib.ScViewCallContext) *OwnerOfCall { f := &OwnerOfCall{Func: wasmlib.NewScView(ctx, HScName, HViewOwnerOf)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) Symbol(ctx wasmlib.ScViewCallContext) *SymbolCall { f := &SymbolCall{Func: wasmlib.NewScView(ctx, HScName, HViewSymbol)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) TokenURI(ctx wasmlib.ScViewCallContext) *TokenURICall { f := &TokenURICall{Func: wasmlib.NewScView(ctx, HScName, HViewTokenURI)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/erc721/go/erc721/erc721.go b/contracts/wasm/erc721/go/erc721/erc721.go index 81b8cf78f1..97f1da0653 100644 --- a/contracts/wasm/erc721/go/erc721/erc721.go +++ b/contracts/wasm/erc721/go/erc721/erc721.go @@ -3,7 +3,10 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) // Follows ERC-721 standard as closely as possible // https//eips.Ethereum.Org/EIPS/eip-721 @@ -18,12 +21,12 @@ import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" // set the required base URI, to which the base58 encoded token ID will be concatenated const baseURI = "my/special/base/uri/" -var zero = wasmlib.ScAgentID{} +var zero = wasmtypes.ScAgentID{} /////////////////////////// HELPER FUNCTIONS //////////////////////////// // checks if caller is owner, or one of its delegated operators -func canOperate(state MutableErc721State, caller, owner wasmlib.ScAgentID) bool { +func canOperate(state MutableErc721State, caller, owner wasmtypes.ScAgentID) bool { if caller == owner { return true } @@ -33,7 +36,7 @@ func canOperate(state MutableErc721State, caller, owner wasmlib.ScAgentID) bool } // checks if caller is owner, or one of its delegated operators, or approved account for tokenID -func canTransfer(state MutableErc721State, caller, owner wasmlib.ScAgentID, tokenID wasmlib.ScHash) bool { +func canTransfer(state MutableErc721State, caller, owner wasmtypes.ScAgentID, tokenID wasmtypes.ScHash) bool { if canOperate(state, caller, owner) { return true } @@ -43,7 +46,7 @@ func canTransfer(state MutableErc721State, caller, owner wasmlib.ScAgentID, toke } // common code for safeTransferFrom and transferFrom -func transfer(ctx wasmlib.ScFuncContext, state MutableErc721State, from, to wasmlib.ScAgentID, tokenID wasmlib.ScHash) { +func transfer(ctx wasmlib.ScFuncContext, state MutableErc721State, from, to wasmtypes.ScAgentID, tokenID wasmtypes.ScHash) { tokenOwner := state.Owners().GetAgentID(tokenID) ctx.Require(tokenOwner.Exists(), "tokenID does not exist") diff --git a/contracts/wasm/erc721/go/erc721/events.go b/contracts/wasm/erc721/go/erc721/events.go index ab863646b5..7b913defe2 100644 --- a/contracts/wasm/erc721/go/erc721/events.go +++ b/contracts/wasm/erc721/go/erc721/events.go @@ -8,45 +8,48 @@ //nolint:gocritic package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) type Erc721Events struct{} -func (e Erc721Events) Approval(approved wasmlib.ScAgentID, owner wasmlib.ScAgentID, tokenID wasmlib.ScHash) { - wasmlib.NewEventEncoder("erc721.approval"). - AgentID(approved). - AgentID(owner). - Hash(tokenID). - Emit() +func (e Erc721Events) Approval(approved wasmtypes.ScAgentID, owner wasmtypes.ScAgentID, tokenID wasmtypes.ScHash) { + evt := wasmlib.NewEventEncoder("erc721.approval") + evt.Encode(wasmtypes.AgentIDToString(approved)) + evt.Encode(wasmtypes.AgentIDToString(owner)) + evt.Encode(wasmtypes.HashToString(tokenID)) + evt.Emit() } -func (e Erc721Events) ApprovalForAll(approval bool, operator wasmlib.ScAgentID, owner wasmlib.ScAgentID) { - wasmlib.NewEventEncoder("erc721.approvalForAll"). - Bool(approval). - AgentID(operator). - AgentID(owner). - Emit() +func (e Erc721Events) ApprovalForAll(approval bool, operator wasmtypes.ScAgentID, owner wasmtypes.ScAgentID) { + evt := wasmlib.NewEventEncoder("erc721.approvalForAll") + evt.Encode(wasmtypes.BoolToString(approval)) + evt.Encode(wasmtypes.AgentIDToString(operator)) + evt.Encode(wasmtypes.AgentIDToString(owner)) + evt.Emit() } func (e Erc721Events) Init(name string, symbol string) { - wasmlib.NewEventEncoder("erc721.init"). - String(name). - String(symbol). - Emit() + evt := wasmlib.NewEventEncoder("erc721.init") + evt.Encode(wasmtypes.StringToString(name)) + evt.Encode(wasmtypes.StringToString(symbol)) + evt.Emit() } -func (e Erc721Events) Mint(balance uint64, owner wasmlib.ScAgentID, tokenID wasmlib.ScHash) { - wasmlib.NewEventEncoder("erc721.mint"). - Uint64(balance). - AgentID(owner). - Hash(tokenID). - Emit() +func (e Erc721Events) Mint(balance uint64, owner wasmtypes.ScAgentID, tokenID wasmtypes.ScHash) { + evt := wasmlib.NewEventEncoder("erc721.mint") + evt.Encode(wasmtypes.Uint64ToString(balance)) + evt.Encode(wasmtypes.AgentIDToString(owner)) + evt.Encode(wasmtypes.HashToString(tokenID)) + evt.Emit() } -func (e Erc721Events) Transfer(from wasmlib.ScAgentID, to wasmlib.ScAgentID, tokenID wasmlib.ScHash) { - wasmlib.NewEventEncoder("erc721.transfer"). - AgentID(from). - AgentID(to). - Hash(tokenID). - Emit() +func (e Erc721Events) Transfer(from wasmtypes.ScAgentID, to wasmtypes.ScAgentID, tokenID wasmtypes.ScHash) { + evt := wasmlib.NewEventEncoder("erc721.transfer") + evt.Encode(wasmtypes.AgentIDToString(from)) + evt.Encode(wasmtypes.AgentIDToString(to)) + evt.Encode(wasmtypes.HashToString(tokenID)) + evt.Emit() } diff --git a/contracts/wasm/erc721/go/erc721/keys.go b/contracts/wasm/erc721/go/erc721/keys.go deleted file mode 100644 index a1f47ba9f4..0000000000 --- a/contracts/wasm/erc721/go/erc721/keys.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package erc721 - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamApproval = 0 - IdxParamApproved = 1 - IdxParamData = 2 - IdxParamFrom = 3 - IdxParamName = 4 - IdxParamOperator = 5 - IdxParamOwner = 6 - IdxParamSymbol = 7 - IdxParamTo = 8 - IdxParamTokenID = 9 - IdxParamTokenURI = 10 - - IdxResultAmount = 11 - IdxResultApproval = 12 - IdxResultApproved = 13 - IdxResultName = 14 - IdxResultOwner = 15 - IdxResultSymbol = 16 - IdxResultTokenURI = 17 - - IdxStateApprovedAccounts = 18 - IdxStateApprovedOperators = 19 - IdxStateBalances = 20 - IdxStateName = 21 - IdxStateOwners = 22 - IdxStateSymbol = 23 - IdxStateTokenURIs = 24 -) - -const keyMapLen = 25 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamApproval, - ParamApproved, - ParamData, - ParamFrom, - ParamName, - ParamOperator, - ParamOwner, - ParamSymbol, - ParamTo, - ParamTokenID, - ParamTokenURI, - ResultAmount, - ResultApproval, - ResultApproved, - ResultName, - ResultOwner, - ResultSymbol, - ResultTokenURI, - StateApprovedAccounts, - StateApprovedOperators, - StateBalances, - StateName, - StateOwners, - StateSymbol, - StateTokenURIs, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/erc721/go/erc721/lib.go b/contracts/wasm/erc721/go/erc721/lib.go index 60498f3a9e..2c773e765b 100644 --- a/contracts/wasm/erc721/go/erc721/lib.go +++ b/contracts/wasm/erc721/go/erc721/lib.go @@ -7,28 +7,52 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncApprove, funcApproveThunk) - exports.AddFunc(FuncBurn, funcBurnThunk) - exports.AddFunc(FuncInit, funcInitThunk) - exports.AddFunc(FuncMint, funcMintThunk) - exports.AddFunc(FuncSafeTransferFrom, funcSafeTransferFromThunk) - exports.AddFunc(FuncSetApprovalForAll, funcSetApprovalForAllThunk) - exports.AddFunc(FuncTransferFrom, funcTransferFromThunk) - exports.AddView(ViewBalanceOf, viewBalanceOfThunk) - exports.AddView(ViewGetApproved, viewGetApprovedThunk) - exports.AddView(ViewIsApprovedForAll, viewIsApprovedForAllThunk) - exports.AddView(ViewName, viewNameThunk) - exports.AddView(ViewOwnerOf, viewOwnerOfThunk) - exports.AddView(ViewSymbol, viewSymbolThunk) - exports.AddView(ViewTokenURI, viewTokenURIThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncApprove, + FuncBurn, + FuncInit, + FuncMint, + FuncSafeTransferFrom, + FuncSetApprovalForAll, + FuncTransferFrom, + ViewBalanceOf, + ViewGetApproved, + ViewIsApprovedForAll, + ViewName, + ViewOwnerOf, + ViewSymbol, + ViewTokenURI, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcApproveThunk, + funcBurnThunk, + funcInitThunk, + funcMintThunk, + funcSafeTransferFromThunk, + funcSetApprovalForAllThunk, + funcTransferFromThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewBalanceOfThunk, + viewGetApprovedThunk, + viewIsApprovedForAllThunk, + viewNameThunk, + viewOwnerOfThunk, + viewSymbolThunk, + viewTokenURIThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type ApproveContext struct { @@ -41,10 +65,10 @@ func funcApproveThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcApprove") f := &ApproveContext{ Params: ImmutableApproveParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") @@ -62,10 +86,10 @@ func funcBurnThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcBurn") f := &BurnContext{ Params: ImmutableBurnParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") @@ -83,10 +107,10 @@ func funcInitThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcInit") f := &InitContext{ Params: ImmutableInitParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") @@ -105,10 +129,10 @@ func funcMintThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcMint") f := &MintContext{ Params: ImmutableMintParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") @@ -126,10 +150,10 @@ func funcSafeTransferFromThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcSafeTransferFrom") f := &SafeTransferFromContext{ Params: ImmutableSafeTransferFromParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.From().Exists(), "missing mandatory from") @@ -149,10 +173,10 @@ func funcSetApprovalForAllThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcSetApprovalForAll") f := &SetApprovalForAllContext{ Params: ImmutableSetApprovalForAllParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Approval().Exists(), "missing mandatory approval") @@ -171,10 +195,10 @@ func funcTransferFromThunk(ctx wasmlib.ScFuncContext) { ctx.Log("erc721.funcTransferFrom") f := &TransferFromContext{ Params: ImmutableTransferFromParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.From().Exists(), "missing mandatory from") @@ -192,19 +216,21 @@ type BalanceOfContext struct { func viewBalanceOfThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewBalanceOf") + results := wasmlib.NewScDict() f := &BalanceOfContext{ Params: ImmutableBalanceOfParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableBalanceOfResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Owner().Exists(), "missing mandatory owner") viewBalanceOf(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewBalanceOf ok") } @@ -216,19 +242,21 @@ type GetApprovedContext struct { func viewGetApprovedThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewGetApproved") + results := wasmlib.NewScDict() f := &GetApprovedContext{ Params: ImmutableGetApprovedParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableGetApprovedResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") viewGetApproved(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewGetApproved ok") } @@ -240,20 +268,22 @@ type IsApprovedForAllContext struct { func viewIsApprovedForAllThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewIsApprovedForAll") + results := wasmlib.NewScDict() f := &IsApprovedForAllContext{ Params: ImmutableIsApprovedForAllParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableIsApprovedForAllResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Operator().Exists(), "missing mandatory operator") ctx.Require(f.Params.Owner().Exists(), "missing mandatory owner") viewIsApprovedForAll(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewIsApprovedForAll ok") } @@ -264,15 +294,17 @@ type NameContext struct { func viewNameThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewName") + results := wasmlib.NewScDict() f := &NameContext{ Results: MutableNameResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewName(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewName ok") } @@ -284,19 +316,21 @@ type OwnerOfContext struct { func viewOwnerOfThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewOwnerOf") + results := wasmlib.NewScDict() f := &OwnerOfContext{ Params: ImmutableOwnerOfParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableOwnerOfResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") viewOwnerOf(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewOwnerOf ok") } @@ -307,15 +341,17 @@ type SymbolContext struct { func viewSymbolThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewSymbol") + results := wasmlib.NewScDict() f := &SymbolContext{ Results: MutableSymbolResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewSymbol(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewSymbol ok") } @@ -327,18 +363,20 @@ type TokenURIContext struct { func viewTokenURIThunk(ctx wasmlib.ScViewContext) { ctx.Log("erc721.viewTokenURI") + results := wasmlib.NewScDict() f := &TokenURIContext{ Params: ImmutableTokenURIParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableTokenURIResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableErc721State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.TokenID().Exists(), "missing mandatory tokenID") viewTokenURI(ctx, f) + ctx.Results(results) ctx.Log("erc721.viewTokenURI ok") } diff --git a/contracts/wasm/erc721/go/erc721/params.go b/contracts/wasm/erc721/go/erc721/params.go index 63a30646d2..60ef796639 100644 --- a/contracts/wasm/erc721/go/erc721/params.go +++ b/contracts/wasm/erc721/go/erc721/params.go @@ -7,276 +7,276 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableApproveParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableApproveParams) Approved() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamApproved)) +func (s ImmutableApproveParams) Approved() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamApproved)) } -func (s ImmutableApproveParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableApproveParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableApproveParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableApproveParams) Approved() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamApproved)) +func (s MutableApproveParams) Approved() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamApproved)) } -func (s MutableApproveParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableApproveParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableBurnParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBurnParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableBurnParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableBurnParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBurnParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableBurnParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableInitParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, idxMap[IdxParamName]) +func (s ImmutableInitParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -func (s ImmutableInitParams) Symbol() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, idxMap[IdxParamSymbol]) +func (s ImmutableInitParams) Symbol() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamSymbol)) } type MutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableInitParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, idxMap[IdxParamName]) +func (s MutableInitParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } -func (s MutableInitParams) Symbol() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, idxMap[IdxParamSymbol]) +func (s MutableInitParams) Symbol() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamSymbol)) } type ImmutableMintParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMintParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableMintParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } -func (s ImmutableMintParams) TokenURI() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamTokenURI)) +func (s ImmutableMintParams) TokenURI() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamTokenURI)) } type MutableMintParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMintParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableMintParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } -func (s MutableMintParams) TokenURI() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamTokenURI)) +func (s MutableMintParams) TokenURI() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamTokenURI)) } type ImmutableSafeTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSafeTransferFromParams) Data() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ParamData)) +func (s ImmutableSafeTransferFromParams) Data() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ParamData)) } -func (s ImmutableSafeTransferFromParams) From() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamFrom)) +func (s ImmutableSafeTransferFromParams) From() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamFrom)) } -func (s ImmutableSafeTransferFromParams) To() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamTo)) +func (s ImmutableSafeTransferFromParams) To() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamTo)) } -func (s ImmutableSafeTransferFromParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableSafeTransferFromParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableSafeTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSafeTransferFromParams) Data() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ParamData)) +func (s MutableSafeTransferFromParams) Data() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ParamData)) } -func (s MutableSafeTransferFromParams) From() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamFrom)) +func (s MutableSafeTransferFromParams) From() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamFrom)) } -func (s MutableSafeTransferFromParams) To() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamTo)) +func (s MutableSafeTransferFromParams) To() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamTo)) } -func (s MutableSafeTransferFromParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableSafeTransferFromParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableSetApprovalForAllParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSetApprovalForAllParams) Approval() wasmlib.ScImmutableBool { - return wasmlib.NewScImmutableBool(s.id, wasmlib.KeyID(ParamApproval)) +func (s ImmutableSetApprovalForAllParams) Approval() wasmtypes.ScImmutableBool { + return wasmtypes.NewScImmutableBool(s.proxy.Root(ParamApproval)) } -func (s ImmutableSetApprovalForAllParams) Operator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamOperator)) +func (s ImmutableSetApprovalForAllParams) Operator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOperator)) } type MutableSetApprovalForAllParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSetApprovalForAllParams) Approval() wasmlib.ScMutableBool { - return wasmlib.NewScMutableBool(s.id, wasmlib.KeyID(ParamApproval)) +func (s MutableSetApprovalForAllParams) Approval() wasmtypes.ScMutableBool { + return wasmtypes.NewScMutableBool(s.proxy.Root(ParamApproval)) } -func (s MutableSetApprovalForAllParams) Operator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamOperator)) +func (s MutableSetApprovalForAllParams) Operator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOperator)) } type ImmutableTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTransferFromParams) From() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamFrom)) +func (s ImmutableTransferFromParams) From() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamFrom)) } -func (s ImmutableTransferFromParams) To() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamTo)) +func (s ImmutableTransferFromParams) To() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamTo)) } -func (s ImmutableTransferFromParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableTransferFromParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableTransferFromParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTransferFromParams) From() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamFrom)) +func (s MutableTransferFromParams) From() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamFrom)) } -func (s MutableTransferFromParams) To() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamTo)) +func (s MutableTransferFromParams) To() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamTo)) } -func (s MutableTransferFromParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableTransferFromParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableBalanceOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBalanceOfParams) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s ImmutableBalanceOfParams) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOwner)) } type MutableBalanceOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBalanceOfParams) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s MutableBalanceOfParams) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOwner)) } type ImmutableGetApprovedParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetApprovedParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableGetApprovedParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableGetApprovedParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetApprovedParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableGetApprovedParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableIsApprovedForAllParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableIsApprovedForAllParams) Operator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamOperator)) +func (s ImmutableIsApprovedForAllParams) Operator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOperator)) } -func (s ImmutableIsApprovedForAllParams) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s ImmutableIsApprovedForAllParams) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamOwner)) } type MutableIsApprovedForAllParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableIsApprovedForAllParams) Operator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamOperator)) +func (s MutableIsApprovedForAllParams) Operator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOperator)) } -func (s MutableIsApprovedForAllParams) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamOwner)) +func (s MutableIsApprovedForAllParams) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamOwner)) } type ImmutableOwnerOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableOwnerOfParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableOwnerOfParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableOwnerOfParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableOwnerOfParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableOwnerOfParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } type ImmutableTokenURIParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTokenURIParams) TokenID() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s ImmutableTokenURIParams) TokenID() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamTokenID)) } type MutableTokenURIParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTokenURIParams) TokenID() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamTokenID)) +func (s MutableTokenURIParams) TokenID() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamTokenID)) } diff --git a/contracts/wasm/erc721/go/erc721/results.go b/contracts/wasm/erc721/go/erc721/results.go index ff831db9c0..f8864d5e54 100644 --- a/contracts/wasm/erc721/go/erc721/results.go +++ b/contracts/wasm/erc721/go/erc721/results.go @@ -7,116 +7,116 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableBalanceOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBalanceOfResults) Amount() wasmlib.ScImmutableUint64 { - return wasmlib.NewScImmutableUint64(s.id, wasmlib.KeyID(ResultAmount)) +func (s ImmutableBalanceOfResults) Amount() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultAmount)) } type MutableBalanceOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBalanceOfResults) Amount() wasmlib.ScMutableUint64 { - return wasmlib.NewScMutableUint64(s.id, wasmlib.KeyID(ResultAmount)) +func (s MutableBalanceOfResults) Amount() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultAmount)) } type ImmutableGetApprovedResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetApprovedResults) Approved() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultApproved)) +func (s ImmutableGetApprovedResults) Approved() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultApproved)) } type MutableGetApprovedResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetApprovedResults) Approved() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultApproved)) +func (s MutableGetApprovedResults) Approved() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultApproved)) } type ImmutableIsApprovedForAllResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableIsApprovedForAllResults) Approval() wasmlib.ScImmutableBool { - return wasmlib.NewScImmutableBool(s.id, wasmlib.KeyID(ResultApproval)) +func (s ImmutableIsApprovedForAllResults) Approval() wasmtypes.ScImmutableBool { + return wasmtypes.NewScImmutableBool(s.proxy.Root(ResultApproval)) } type MutableIsApprovedForAllResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableIsApprovedForAllResults) Approval() wasmlib.ScMutableBool { - return wasmlib.NewScMutableBool(s.id, wasmlib.KeyID(ResultApproval)) +func (s MutableIsApprovedForAllResults) Approval() wasmtypes.ScMutableBool { + return wasmtypes.NewScMutableBool(s.proxy.Root(ResultApproval)) } type ImmutableNameResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableNameResults) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultName)) +func (s ImmutableNameResults) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultName)) } type MutableNameResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableNameResults) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultName)) +func (s MutableNameResults) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultName)) } type ImmutableOwnerOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableOwnerOfResults) Owner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultOwner)) +func (s ImmutableOwnerOfResults) Owner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultOwner)) } type MutableOwnerOfResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableOwnerOfResults) Owner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultOwner)) +func (s MutableOwnerOfResults) Owner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultOwner)) } type ImmutableSymbolResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSymbolResults) Symbol() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultSymbol)) +func (s ImmutableSymbolResults) Symbol() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultSymbol)) } type MutableSymbolResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSymbolResults) Symbol() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultSymbol)) +func (s MutableSymbolResults) Symbol() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultSymbol)) } type ImmutableTokenURIResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTokenURIResults) TokenURI() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultTokenURI)) +func (s ImmutableTokenURIResults) TokenURI() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultTokenURI)) } type MutableTokenURIResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTokenURIResults) TokenURI() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultTokenURI)) +func (s MutableTokenURIResults) TokenURI() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultTokenURI)) } diff --git a/contracts/wasm/erc721/go/erc721/state.go b/contracts/wasm/erc721/go/erc721/state.go index e2204b0108..12f7c29189 100644 --- a/contracts/wasm/erc721/go/erc721/state.go +++ b/contracts/wasm/erc721/go/erc721/state.go @@ -7,129 +7,122 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type MapHashToImmutableAgentID struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapHashToImmutableAgentID) GetAgentID(key wasmlib.ScHash) wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(m.objID, key.KeyID()) +func (m MapHashToImmutableAgentID) GetAgentID(key wasmtypes.ScHash) wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(m.proxy.Key(wasmtypes.HashToBytes(key))) } type MapAgentIDToImmutableOperators struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableOperators) GetOperators(key wasmlib.ScAgentID) ImmutableOperators { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return ImmutableOperators{objID: subID} +func (m MapAgentIDToImmutableOperators) GetOperators(key wasmtypes.ScAgentID) ImmutableOperators { + return ImmutableOperators{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type MapAgentIDToImmutableUint64 struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableUint64) GetUint64(key wasmlib.ScAgentID) wasmlib.ScImmutableUint64 { - return wasmlib.NewScImmutableUint64(m.objID, key.KeyID()) +func (m MapAgentIDToImmutableUint64) GetUint64(key wasmtypes.ScAgentID) wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } type MapHashToImmutableString struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapHashToImmutableString) GetString(key wasmlib.ScHash) wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(m.objID, key.KeyID()) +func (m MapHashToImmutableString) GetString(key wasmtypes.ScHash) wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(m.proxy.Key(wasmtypes.HashToBytes(key))) } type ImmutableErc721State struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableErc721State) ApprovedAccounts() MapHashToImmutableAgentID { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateApprovedAccounts), wasmlib.TYPE_MAP) - return MapHashToImmutableAgentID{objID: mapID} + return MapHashToImmutableAgentID{proxy: s.proxy.Root(StateApprovedAccounts)} } func (s ImmutableErc721State) ApprovedOperators() MapAgentIDToImmutableOperators { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateApprovedOperators), wasmlib.TYPE_MAP) - return MapAgentIDToImmutableOperators{objID: mapID} + return MapAgentIDToImmutableOperators{proxy: s.proxy.Root(StateApprovedOperators)} } func (s ImmutableErc721State) Balances() MapAgentIDToImmutableUint64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBalances), wasmlib.TYPE_MAP) - return MapAgentIDToImmutableUint64{objID: mapID} + return MapAgentIDToImmutableUint64{proxy: s.proxy.Root(StateBalances)} } -func (s ImmutableErc721State) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(StateName)) +func (s ImmutableErc721State) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(StateName)) } func (s ImmutableErc721State) Owners() MapHashToImmutableAgentID { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateOwners), wasmlib.TYPE_MAP) - return MapHashToImmutableAgentID{objID: mapID} + return MapHashToImmutableAgentID{proxy: s.proxy.Root(StateOwners)} } -func (s ImmutableErc721State) Symbol() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(StateSymbol)) +func (s ImmutableErc721State) Symbol() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(StateSymbol)) } func (s ImmutableErc721State) TokenURIs() MapHashToImmutableString { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateTokenURIs), wasmlib.TYPE_MAP) - return MapHashToImmutableString{objID: mapID} + return MapHashToImmutableString{proxy: s.proxy.Root(StateTokenURIs)} } type MapHashToMutableAgentID struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapHashToMutableAgentID) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapHashToMutableAgentID) GetAgentID(key wasmlib.ScHash) wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(m.objID, key.KeyID()) +func (m MapHashToMutableAgentID) GetAgentID(key wasmtypes.ScHash) wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(m.proxy.Key(wasmtypes.HashToBytes(key))) } type MapAgentIDToMutableOperators struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapAgentIDToMutableOperators) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapAgentIDToMutableOperators) GetOperators(key wasmlib.ScAgentID) MutableOperators { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return MutableOperators{objID: subID} +func (m MapAgentIDToMutableOperators) GetOperators(key wasmtypes.ScAgentID) MutableOperators { + return MutableOperators{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type MapAgentIDToMutableUint64 struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapAgentIDToMutableUint64) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapAgentIDToMutableUint64) GetUint64(key wasmlib.ScAgentID) wasmlib.ScMutableUint64 { - return wasmlib.NewScMutableUint64(m.objID, key.KeyID()) +func (m MapAgentIDToMutableUint64) GetUint64(key wasmtypes.ScAgentID) wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } type MapHashToMutableString struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapHashToMutableString) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapHashToMutableString) GetString(key wasmlib.ScHash) wasmlib.ScMutableString { - return wasmlib.NewScMutableString(m.objID, key.KeyID()) +func (m MapHashToMutableString) GetString(key wasmtypes.ScHash) wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(m.proxy.Key(wasmtypes.HashToBytes(key))) } type MutableErc721State struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableErc721State) AsImmutable() ImmutableErc721State { @@ -137,34 +130,29 @@ func (s MutableErc721State) AsImmutable() ImmutableErc721State { } func (s MutableErc721State) ApprovedAccounts() MapHashToMutableAgentID { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateApprovedAccounts), wasmlib.TYPE_MAP) - return MapHashToMutableAgentID{objID: mapID} + return MapHashToMutableAgentID{proxy: s.proxy.Root(StateApprovedAccounts)} } func (s MutableErc721State) ApprovedOperators() MapAgentIDToMutableOperators { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateApprovedOperators), wasmlib.TYPE_MAP) - return MapAgentIDToMutableOperators{objID: mapID} + return MapAgentIDToMutableOperators{proxy: s.proxy.Root(StateApprovedOperators)} } func (s MutableErc721State) Balances() MapAgentIDToMutableUint64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBalances), wasmlib.TYPE_MAP) - return MapAgentIDToMutableUint64{objID: mapID} + return MapAgentIDToMutableUint64{proxy: s.proxy.Root(StateBalances)} } -func (s MutableErc721State) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(StateName)) +func (s MutableErc721State) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(StateName)) } func (s MutableErc721State) Owners() MapHashToMutableAgentID { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateOwners), wasmlib.TYPE_MAP) - return MapHashToMutableAgentID{objID: mapID} + return MapHashToMutableAgentID{proxy: s.proxy.Root(StateOwners)} } -func (s MutableErc721State) Symbol() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(StateSymbol)) +func (s MutableErc721State) Symbol() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(StateSymbol)) } func (s MutableErc721State) TokenURIs() MapHashToMutableString { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateTokenURIs), wasmlib.TYPE_MAP) - return MapHashToMutableString{objID: mapID} + return MapHashToMutableString{proxy: s.proxy.Root(StateTokenURIs)} } diff --git a/contracts/wasm/erc721/go/erc721/typedefs.go b/contracts/wasm/erc721/go/erc721/typedefs.go index b9f771d048..d27d05ac01 100644 --- a/contracts/wasm/erc721/go/erc721/typedefs.go +++ b/contracts/wasm/erc721/go/erc721/typedefs.go @@ -7,28 +7,28 @@ package erc721 -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type MapAgentIDToImmutableBool struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableBool) GetBool(key wasmlib.ScAgentID) wasmlib.ScImmutableBool { - return wasmlib.NewScImmutableBool(m.objID, key.KeyID()) +func (m MapAgentIDToImmutableBool) GetBool(key wasmtypes.ScAgentID) wasmtypes.ScImmutableBool { + return wasmtypes.NewScImmutableBool(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } type ImmutableOperators = MapAgentIDToImmutableBool type MapAgentIDToMutableBool struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapAgentIDToMutableBool) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapAgentIDToMutableBool) GetBool(key wasmlib.ScAgentID) wasmlib.ScMutableBool { - return wasmlib.NewScMutableBool(m.objID, key.KeyID()) +func (m MapAgentIDToMutableBool) GetBool(key wasmtypes.ScAgentID) wasmtypes.ScMutableBool { + return wasmtypes.NewScMutableBool(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) } type MutableOperators = MapAgentIDToMutableBool diff --git a/contracts/wasm/erc721/go/erc721client/events.go b/contracts/wasm/erc721/go/erc721client/events.go new file mode 100644 index 0000000000..8c27c39289 --- /dev/null +++ b/contracts/wasm/erc721/go/erc721client/events.go @@ -0,0 +1,146 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package erc721client + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" + +var erc721Handlers = map[string]func(*Erc721Events, []string){ + "erc721.approval": func(evt *Erc721Events, msg []string) { evt.onErc721ApprovalThunk(msg) }, + "erc721.approvalForAll": func(evt *Erc721Events, msg []string) { evt.onErc721ApprovalForAllThunk(msg) }, + "erc721.init": func(evt *Erc721Events, msg []string) { evt.onErc721InitThunk(msg) }, + "erc721.mint": func(evt *Erc721Events, msg []string) { evt.onErc721MintThunk(msg) }, + "erc721.transfer": func(evt *Erc721Events, msg []string) { evt.onErc721TransferThunk(msg) }, +} + +type Erc721Events struct { + approval func(e *EventApproval) + approvalForAll func(e *EventApprovalForAll) + init func(e *EventInit) + mint func(e *EventMint) + transfer func(e *EventTransfer) +} + +func (h *Erc721Events) CallHandler(topic string, params []string) { + handler := erc721Handlers[topic] + if handler != nil { + handler(h, params) + } +} + +func (h *Erc721Events) OnErc721Approval(handler func(e *EventApproval)) { + h.approval = handler +} + +func (h *Erc721Events) OnErc721ApprovalForAll(handler func(e *EventApprovalForAll)) { + h.approvalForAll = handler +} + +func (h *Erc721Events) OnErc721Init(handler func(e *EventInit)) { + h.init = handler +} + +func (h *Erc721Events) OnErc721Mint(handler func(e *EventMint)) { + h.mint = handler +} + +func (h *Erc721Events) OnErc721Transfer(handler func(e *EventTransfer)) { + h.transfer = handler +} + +type EventApproval struct { + wasmclient.Event + Approved wasmclient.AgentID + Owner wasmclient.AgentID + TokenID wasmclient.Hash +} + +func (h *Erc721Events) onErc721ApprovalThunk(message []string) { + if h.approval == nil { + return + } + e := &EventApproval{} + e.Init(message) + e.Approved = e.NextAgentID() + e.Owner = e.NextAgentID() + e.TokenID = e.NextHash() + h.approval(e) +} + +type EventApprovalForAll struct { + wasmclient.Event + Approval bool + Operator wasmclient.AgentID + Owner wasmclient.AgentID +} + +func (h *Erc721Events) onErc721ApprovalForAllThunk(message []string) { + if h.approvalForAll == nil { + return + } + e := &EventApprovalForAll{} + e.Init(message) + e.Approval = e.NextBool() + e.Operator = e.NextAgentID() + e.Owner = e.NextAgentID() + h.approvalForAll(e) +} + +type EventInit struct { + wasmclient.Event + Name string + Symbol string +} + +func (h *Erc721Events) onErc721InitThunk(message []string) { + if h.init == nil { + return + } + e := &EventInit{} + e.Init(message) + e.Name = e.NextString() + e.Symbol = e.NextString() + h.init(e) +} + +type EventMint struct { + wasmclient.Event + Balance uint64 + Owner wasmclient.AgentID + TokenID wasmclient.Hash +} + +func (h *Erc721Events) onErc721MintThunk(message []string) { + if h.mint == nil { + return + } + e := &EventMint{} + e.Init(message) + e.Balance = e.NextUint64() + e.Owner = e.NextAgentID() + e.TokenID = e.NextHash() + h.mint(e) +} + +type EventTransfer struct { + wasmclient.Event + From wasmclient.AgentID + To wasmclient.AgentID + TokenID wasmclient.Hash +} + +func (h *Erc721Events) onErc721TransferThunk(message []string) { + if h.transfer == nil { + return + } + e := &EventTransfer{} + e.Init(message) + e.From = e.NextAgentID() + e.To = e.NextAgentID() + e.TokenID = e.NextHash() + h.transfer(e) +} diff --git a/contracts/wasm/erc721/go/erc721client/service.go b/contracts/wasm/erc721/go/erc721client/service.go new file mode 100644 index 0000000000..57659c39ed --- /dev/null +++ b/contracts/wasm/erc721/go/erc721client/service.go @@ -0,0 +1,446 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package erc721client + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" + +const ( + ArgApproval = "approval" + ArgApproved = "approved" + ArgData = "data" + ArgFrom = "from" + ArgName = "n" + ArgOperator = "operator" + ArgOwner = "owner" + ArgSymbol = "s" + ArgTo = "to" + ArgTokenID = "tokenID" + ArgTokenURI = "tokenURI" + + ResAmount = "amount" + ResApproval = "approval" + ResApproved = "approved" + ResName = "name" + ResOwner = "owner" + ResSymbol = "symbol" + ResTokenURI = "tokenURI" +) + +///////////////////////////// approve ///////////////////////////// + +type ApproveFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *ApproveFunc) Approved(v wasmclient.AgentID) { + f.args.Set(ArgApproved, f.args.FromAgentID(v)) +} + +func (f *ApproveFunc) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *ApproveFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgTokenID) + return f.ClientFunc.Post(0xa0661268, &f.args) +} + +///////////////////////////// burn ///////////////////////////// + +type BurnFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *BurnFunc) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *BurnFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgTokenID) + return f.ClientFunc.Post(0x7bc1efb1, &f.args) +} + +///////////////////////////// init ///////////////////////////// + +type InitFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *InitFunc) Name(v string) { + f.args.Set(ArgName, f.args.FromString(v)) +} + +func (f *InitFunc) Symbol(v string) { + f.args.Set(ArgSymbol, f.args.FromString(v)) +} + +func (f *InitFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgName) + f.args.Mandatory(ArgSymbol) + return f.ClientFunc.Post(0x1f44d644, &f.args) +} + +///////////////////////////// mint ///////////////////////////// + +type MintFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *MintFunc) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *MintFunc) TokenURI(v string) { + f.args.Set(ArgTokenURI, f.args.FromString(v)) +} + +func (f *MintFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgTokenID) + return f.ClientFunc.Post(0xa29addcf, &f.args) +} + +///////////////////////////// safeTransferFrom ///////////////////////////// + +type SafeTransferFromFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *SafeTransferFromFunc) Data(v []byte) { + f.args.Set(ArgData, f.args.FromBytes(v)) +} + +func (f *SafeTransferFromFunc) From(v wasmclient.AgentID) { + f.args.Set(ArgFrom, f.args.FromAgentID(v)) +} + +func (f *SafeTransferFromFunc) To(v wasmclient.AgentID) { + f.args.Set(ArgTo, f.args.FromAgentID(v)) +} + +func (f *SafeTransferFromFunc) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *SafeTransferFromFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgFrom) + f.args.Mandatory(ArgTo) + f.args.Mandatory(ArgTokenID) + return f.ClientFunc.Post(0x130ce158, &f.args) +} + +///////////////////////////// setApprovalForAll ///////////////////////////// + +type SetApprovalForAllFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *SetApprovalForAllFunc) Approval(v bool) { + f.args.Set(ArgApproval, f.args.FromBool(v)) +} + +func (f *SetApprovalForAllFunc) Operator(v wasmclient.AgentID) { + f.args.Set(ArgOperator, f.args.FromAgentID(v)) +} + +func (f *SetApprovalForAllFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgApproval) + f.args.Mandatory(ArgOperator) + return f.ClientFunc.Post(0xb8d8c776, &f.args) +} + +///////////////////////////// transferFrom ///////////////////////////// + +type TransferFromFunc struct { + wasmclient.ClientFunc + args wasmclient.Arguments +} + +func (f *TransferFromFunc) From(v wasmclient.AgentID) { + f.args.Set(ArgFrom, f.args.FromAgentID(v)) +} + +func (f *TransferFromFunc) To(v wasmclient.AgentID) { + f.args.Set(ArgTo, f.args.FromAgentID(v)) +} + +func (f *TransferFromFunc) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *TransferFromFunc) Post() wasmclient.Request { + f.args.Mandatory(ArgFrom) + f.args.Mandatory(ArgTo) + f.args.Mandatory(ArgTokenID) + return f.ClientFunc.Post(0xd5e0a602, &f.args) +} + +///////////////////////////// balanceOf ///////////////////////////// + +type BalanceOfView struct { + wasmclient.ClientView + args wasmclient.Arguments +} + +func (f *BalanceOfView) Owner(v wasmclient.AgentID) { + f.args.Set(ArgOwner, f.args.FromAgentID(v)) +} + +func (f *BalanceOfView) Call() BalanceOfResults { + f.args.Mandatory(ArgOwner) + f.ClientView.Call("balanceOf", &f.args) + return BalanceOfResults{res: f.Results()} +} + +type BalanceOfResults struct { + res wasmclient.Results +} + +func (r *BalanceOfResults) AmountExists() bool { + return r.res.Exists(ResAmount) +} + +func (r *BalanceOfResults) Amount() uint64 { + return r.res.ToUint64(r.res.Get(ResAmount)) +} + +///////////////////////////// getApproved ///////////////////////////// + +type GetApprovedView struct { + wasmclient.ClientView + args wasmclient.Arguments +} + +func (f *GetApprovedView) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *GetApprovedView) Call() GetApprovedResults { + f.args.Mandatory(ArgTokenID) + f.ClientView.Call("getApproved", &f.args) + return GetApprovedResults{res: f.Results()} +} + +type GetApprovedResults struct { + res wasmclient.Results +} + +func (r *GetApprovedResults) ApprovedExists() bool { + return r.res.Exists(ResApproved) +} + +func (r *GetApprovedResults) Approved() wasmclient.AgentID { + return r.res.ToAgentID(r.res.Get(ResApproved)) +} + +///////////////////////////// isApprovedForAll ///////////////////////////// + +type IsApprovedForAllView struct { + wasmclient.ClientView + args wasmclient.Arguments +} + +func (f *IsApprovedForAllView) Operator(v wasmclient.AgentID) { + f.args.Set(ArgOperator, f.args.FromAgentID(v)) +} + +func (f *IsApprovedForAllView) Owner(v wasmclient.AgentID) { + f.args.Set(ArgOwner, f.args.FromAgentID(v)) +} + +func (f *IsApprovedForAllView) Call() IsApprovedForAllResults { + f.args.Mandatory(ArgOperator) + f.args.Mandatory(ArgOwner) + f.ClientView.Call("isApprovedForAll", &f.args) + return IsApprovedForAllResults{res: f.Results()} +} + +type IsApprovedForAllResults struct { + res wasmclient.Results +} + +func (r *IsApprovedForAllResults) ApprovalExists() bool { + return r.res.Exists(ResApproval) +} + +func (r *IsApprovedForAllResults) Approval() bool { + return r.res.ToBool(r.res.Get(ResApproval)) +} + +///////////////////////////// name ///////////////////////////// + +type NameView struct { + wasmclient.ClientView +} + +func (f *NameView) Call() NameResults { + f.ClientView.Call("name", nil) + return NameResults{res: f.Results()} +} + +type NameResults struct { + res wasmclient.Results +} + +func (r *NameResults) Name() string { + return r.res.ToString(r.res.Get(ResName)) +} + +///////////////////////////// ownerOf ///////////////////////////// + +type OwnerOfView struct { + wasmclient.ClientView + args wasmclient.Arguments +} + +func (f *OwnerOfView) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *OwnerOfView) Call() OwnerOfResults { + f.args.Mandatory(ArgTokenID) + f.ClientView.Call("ownerOf", &f.args) + return OwnerOfResults{res: f.Results()} +} + +type OwnerOfResults struct { + res wasmclient.Results +} + +func (r *OwnerOfResults) OwnerExists() bool { + return r.res.Exists(ResOwner) +} + +func (r *OwnerOfResults) Owner() wasmclient.AgentID { + return r.res.ToAgentID(r.res.Get(ResOwner)) +} + +///////////////////////////// symbol ///////////////////////////// + +type SymbolView struct { + wasmclient.ClientView +} + +func (f *SymbolView) Call() SymbolResults { + f.ClientView.Call("symbol", nil) + return SymbolResults{res: f.Results()} +} + +type SymbolResults struct { + res wasmclient.Results +} + +func (r *SymbolResults) Symbol() string { + return r.res.ToString(r.res.Get(ResSymbol)) +} + +///////////////////////////// tokenURI ///////////////////////////// + +type TokenURIView struct { + wasmclient.ClientView + args wasmclient.Arguments +} + +func (f *TokenURIView) TokenID(v wasmclient.Hash) { + f.args.Set(ArgTokenID, f.args.FromHash(v)) +} + +func (f *TokenURIView) Call() TokenURIResults { + f.args.Mandatory(ArgTokenID) + f.ClientView.Call("tokenURI", &f.args) + return TokenURIResults{res: f.Results()} +} + +type TokenURIResults struct { + res wasmclient.Results +} + +func (r *TokenURIResults) TokenURIExists() bool { + return r.res.Exists(ResTokenURI) +} + +func (r *TokenURIResults) TokenURI() string { + return r.res.ToString(r.res.Get(ResTokenURI)) +} + +///////////////////////////// Erc721Service ///////////////////////////// + +type Erc721Service struct { + wasmclient.Service +} + +func NewErc721Service(cl *wasmclient.ServiceClient, chainID string) (*Erc721Service, error) { + s := &Erc721Service{} + err := s.Service.Init(cl, chainID, 0xd967c216) + return s, err +} + +func (s *Erc721Service) NewEventHandler() *Erc721Events { + return &Erc721Events{} +} + +func (s *Erc721Service) Approve() ApproveFunc { + return ApproveFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) Burn() BurnFunc { + return BurnFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) Init() InitFunc { + return InitFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) Mint() MintFunc { + return MintFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) SafeTransferFrom() SafeTransferFromFunc { + return SafeTransferFromFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) SetApprovalForAll() SetApprovalForAllFunc { + return SetApprovalForAllFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) TransferFrom() TransferFromFunc { + return TransferFromFunc{ClientFunc: s.AsClientFunc()} +} + +func (s *Erc721Service) BalanceOf() BalanceOfView { + return BalanceOfView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) GetApproved() GetApprovedView { + return GetApprovedView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) IsApprovedForAll() IsApprovedForAllView { + return IsApprovedForAllView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) Name() NameView { + return NameView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) OwnerOf() OwnerOfView { + return OwnerOfView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) Symbol() SymbolView { + return SymbolView{ClientView: s.AsClientView()} +} + +func (s *Erc721Service) TokenURI() TokenURIView { + return TokenURIView{ClientView: s.AsClientView()} +} diff --git a/contracts/wasm/erc721/go/main.go b/contracts/wasm/erc721/go/main.go index f06a3059cc..d75a0448a1 100644 --- a/contracts/wasm/erc721/go/main.go +++ b/contracts/wasm/erc721/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/erc721/go/erc721" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + erc721.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - erc721.OnLoad() + erc721.OnLoad(-1) } diff --git a/contracts/wasm/erc721/src/contract.rs b/contracts/wasm/erc721/src/contract.rs index 4f23b4c652..7dd5a240ea 100644 --- a/contracts/wasm/erc721/src/contract.rs +++ b/contracts/wasm/erc721/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct ApproveCall { pub func: ScFunc, @@ -94,134 +89,139 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn approve(_ctx: & dyn ScFuncCallContext) -> ApproveCall { + pub fn approve(_ctx: &dyn ScFuncCallContext) -> ApproveCall { let mut f = ApproveCall { func: ScFunc::new(HSC_NAME, HFUNC_APPROVE), - params: MutableApproveParams { id: 0 }, + params: MutableApproveParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn burn(_ctx: & dyn ScFuncCallContext) -> BurnCall { + pub fn burn(_ctx: &dyn ScFuncCallContext) -> BurnCall { let mut f = BurnCall { func: ScFunc::new(HSC_NAME, HFUNC_BURN), - params: MutableBurnParams { id: 0 }, + params: MutableBurnParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn init(_ctx: & dyn ScFuncCallContext) -> InitCall { + pub fn init(_ctx: &dyn ScFuncCallContext) -> InitCall { let mut f = InitCall { func: ScInitFunc::new(HSC_NAME, HFUNC_INIT), - params: MutableInitParams { id: 0 }, + params: MutableInitParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScInitFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn mint(_ctx: & dyn ScFuncCallContext) -> MintCall { + pub fn mint(_ctx: &dyn ScFuncCallContext) -> MintCall { let mut f = MintCall { func: ScFunc::new(HSC_NAME, HFUNC_MINT), - params: MutableMintParams { id: 0 }, + params: MutableMintParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn safe_transfer_from(_ctx: & dyn ScFuncCallContext) -> SafeTransferFromCall { + pub fn safe_transfer_from(_ctx: &dyn ScFuncCallContext) -> SafeTransferFromCall { let mut f = SafeTransferFromCall { func: ScFunc::new(HSC_NAME, HFUNC_SAFE_TRANSFER_FROM), - params: MutableSafeTransferFromParams { id: 0 }, + params: MutableSafeTransferFromParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_approval_for_all(_ctx: & dyn ScFuncCallContext) -> SetApprovalForAllCall { + pub fn set_approval_for_all(_ctx: &dyn ScFuncCallContext) -> SetApprovalForAllCall { let mut f = SetApprovalForAllCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_APPROVAL_FOR_ALL), - params: MutableSetApprovalForAllParams { id: 0 }, + params: MutableSetApprovalForAllParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn transfer_from(_ctx: & dyn ScFuncCallContext) -> TransferFromCall { + pub fn transfer_from(_ctx: &dyn ScFuncCallContext) -> TransferFromCall { let mut f = TransferFromCall { func: ScFunc::new(HSC_NAME, HFUNC_TRANSFER_FROM), - params: MutableTransferFromParams { id: 0 }, + params: MutableTransferFromParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn balance_of(_ctx: & dyn ScViewCallContext) -> BalanceOfCall { + pub fn balance_of(_ctx: &dyn ScViewCallContext) -> BalanceOfCall { let mut f = BalanceOfCall { func: ScView::new(HSC_NAME, HVIEW_BALANCE_OF), - params: MutableBalanceOfParams { id: 0 }, - results: ImmutableBalanceOfResults { id: 0 }, + params: MutableBalanceOfParams { proxy: Proxy::nil() }, + results: ImmutableBalanceOfResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_approved(_ctx: & dyn ScViewCallContext) -> GetApprovedCall { + pub fn get_approved(_ctx: &dyn ScViewCallContext) -> GetApprovedCall { let mut f = GetApprovedCall { func: ScView::new(HSC_NAME, HVIEW_GET_APPROVED), - params: MutableGetApprovedParams { id: 0 }, - results: ImmutableGetApprovedResults { id: 0 }, + params: MutableGetApprovedParams { proxy: Proxy::nil() }, + results: ImmutableGetApprovedResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn is_approved_for_all(_ctx: & dyn ScViewCallContext) -> IsApprovedForAllCall { + pub fn is_approved_for_all(_ctx: &dyn ScViewCallContext) -> IsApprovedForAllCall { let mut f = IsApprovedForAllCall { func: ScView::new(HSC_NAME, HVIEW_IS_APPROVED_FOR_ALL), - params: MutableIsApprovedForAllParams { id: 0 }, - results: ImmutableIsApprovedForAllResults { id: 0 }, + params: MutableIsApprovedForAllParams { proxy: Proxy::nil() }, + results: ImmutableIsApprovedForAllResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn name(_ctx: & dyn ScViewCallContext) -> NameCall { + pub fn name(_ctx: &dyn ScViewCallContext) -> NameCall { let mut f = NameCall { func: ScView::new(HSC_NAME, HVIEW_NAME), - results: ImmutableNameResults { id: 0 }, + results: ImmutableNameResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn owner_of(_ctx: & dyn ScViewCallContext) -> OwnerOfCall { + pub fn owner_of(_ctx: &dyn ScViewCallContext) -> OwnerOfCall { let mut f = OwnerOfCall { func: ScView::new(HSC_NAME, HVIEW_OWNER_OF), - params: MutableOwnerOfParams { id: 0 }, - results: ImmutableOwnerOfResults { id: 0 }, + params: MutableOwnerOfParams { proxy: Proxy::nil() }, + results: ImmutableOwnerOfResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn symbol(_ctx: & dyn ScViewCallContext) -> SymbolCall { + pub fn symbol(_ctx: &dyn ScViewCallContext) -> SymbolCall { let mut f = SymbolCall { func: ScView::new(HSC_NAME, HVIEW_SYMBOL), - results: ImmutableSymbolResults { id: 0 }, + results: ImmutableSymbolResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn token_uri(_ctx: & dyn ScViewCallContext) -> TokenURICall { + pub fn token_uri(_ctx: &dyn ScViewCallContext) -> TokenURICall { let mut f = TokenURICall { func: ScView::new(HSC_NAME, HVIEW_TOKEN_URI), - params: MutableTokenURIParams { id: 0 }, - results: ImmutableTokenURIResults { id: 0 }, + params: MutableTokenURIParams { proxy: Proxy::nil() }, + results: ImmutableTokenURIResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/erc721/src/erc721.rs b/contracts/wasm/erc721/src/erc721.rs index 26b0263492..656740c01e 100644 --- a/contracts/wasm/erc721/src/erc721.rs +++ b/contracts/wasm/erc721/src/erc721.rs @@ -22,7 +22,7 @@ const BASE_URI: &str = "my/special/base/uri/"; /////////////////////////// HELPER FUNCTIONS //////////////////////////// // checks if caller is owner, or one of its delegated operators -fn can_operate(state: MutableErc721State, caller: &ScAgentID, owner: &ScAgentID) -> bool { +fn can_operate(state: &MutableErc721State, caller: &ScAgentID, owner: &ScAgentID) -> bool { if *caller == *owner { return true; } @@ -32,7 +32,7 @@ fn can_operate(state: MutableErc721State, caller: &ScAgentID, owner: &ScAgentID) } // checks if caller is owner, or one of its delegated operators, or approved account for tokenID -fn can_transfer(state: MutableErc721State, caller: &ScAgentID, owner: &ScAgentID, token_id: &ScHash) -> bool { +fn can_transfer(state: &MutableErc721State, caller: &ScAgentID, owner: &ScAgentID, token_id: &ScHash) -> bool { if can_operate(state, caller, owner) { return true; } @@ -42,7 +42,7 @@ fn can_transfer(state: MutableErc721State, caller: &ScAgentID, owner: &ScAgentID } // common code for safeTransferFrom and transferFrom -fn transfer(ctx: &ScFuncContext, state: MutableErc721State, from: &ScAgentID, to: &ScAgentID, token_id: &ScHash) { +fn transfer(ctx: &ScFuncContext, state: &MutableErc721State, from: &ScAgentID, to: &ScAgentID, token_id: &ScHash) { let token_owner = state.owners().get_agent_id(token_id); ctx.require(token_owner.exists(), "tokenID does not exist"); @@ -66,12 +66,16 @@ fn transfer(ctx: &ScFuncContext, state: MutableErc721State, from: &ScAgentID, to let current_approved = state.approved_accounts().get_agent_id(&token_id); if current_approved.exists() { current_approved.delete(); - events.approval(&ScAgentID::ZERO, &owner, &token_id); + events.approval(&zero(), &owner, &token_id); } events.transfer(from, to, token_id); } +fn zero() -> ScAgentID { + agent_id_from_bytes(&[]) +} + /////////////////////////// SC FUNCS //////////////////////////// // Gives permission to to to transfer tokenID token to another account. @@ -82,7 +86,7 @@ pub fn func_approve(ctx: &ScFuncContext, f: &ApproveContext) { let token_owner = f.state.owners().get_agent_id(&token_id); ctx.require(token_owner.exists(), "tokenID does not exist"); let owner = token_owner.value(); - ctx.require(can_operate(f.state, &ctx.caller(), &owner), "not owner or operator"); + ctx.require(can_operate(&f.state, &ctx.caller(), &owner), "not owner or operator"); let approved = f.params.approved(); if !approved.exists() { @@ -90,7 +94,7 @@ pub fn func_approve(ctx: &ScFuncContext, f: &ApproveContext) { let current_approved = f.state.approved_accounts().get_agent_id(&token_id); if current_approved.exists() { current_approved.delete(); - f.events.approval(&ScAgentID::ZERO, &owner, &token_id); + f.events.approval(&zero(), &owner, &token_id); } return; } @@ -106,21 +110,21 @@ pub fn func_approve(ctx: &ScFuncContext, f: &ApproveContext) { pub fn func_burn(ctx: &ScFuncContext, f: &BurnContext) { let token_id = f.params.token_id().value(); let owner = f.state.owners().get_agent_id(&token_id).value(); - ctx.require(owner != ScAgentID::ZERO, "tokenID does not exist"); + ctx.require(owner != zero(), "tokenID does not exist"); ctx.require(ctx.caller() == owner, "caller is not owner"); // remove approval if it exists let current_approved = f.state.approved_accounts().get_agent_id(&token_id); if current_approved.exists() { current_approved.delete(); - f.events.approval(&ScAgentID::ZERO, &owner, &token_id); + f.events.approval(&zero(), &owner, &token_id); } let balance = f.state.balances().get_uint64(&owner); balance.set_value(balance.value() - 1); f.state.owners().get_agent_id(&token_id).delete(); - f.events.transfer(&owner, &ScAgentID::ZERO, &token_id); + f.events.transfer(&owner, &zero(), &token_id); } // Initializes the contract by setting a name and a symbol to the token collection. @@ -151,7 +155,7 @@ pub fn func_mint(ctx: &ScFuncContext, f: &MintContext) { let balance = f.state.balances().get_uint64(&owner); balance.set_value(balance.value() + 1); - f.events.transfer(&ScAgentID::ZERO, &owner, &token_id); + f.events.transfer(&zero(), &owner, &token_id); // if !owner.is_address() { // //TODO interpret to as SC address and call its onERC721Received() function // } @@ -163,7 +167,7 @@ pub fn func_safe_transfer_from(ctx: &ScFuncContext, f: &SafeTransferFromContext) let from = f.params.from().value(); let to = f.params.to().value(); let token_id = f.params.token_id().value(); - transfer(&ctx, f.state, &from, &to, &token_id); + transfer(&ctx, &f.state, &from, &to, &token_id); // if !to.is_address() { // //TODO interpret to as SC address and call its onERC721Received() function // } @@ -187,7 +191,7 @@ pub fn func_transfer_from(ctx: &ScFuncContext, f: &TransferFromContext) { let from = f.params.from().value(); let to = f.params.to().value(); let token_id = f.params.token_id().value(); - transfer(ctx, f.state, &from, &to, &token_id); + transfer(ctx, &f.state, &from, &to, &token_id); } /////////////////////////// SC VIEWS //////////////////////////// diff --git a/contracts/wasm/erc721/src/events.rs b/contracts/wasm/erc721/src/events.rs index 5d13ded8be..f4f652f53e 100644 --- a/contracts/wasm/erc721/src/events.rs +++ b/contracts/wasm/erc721/src/events.rs @@ -6,6 +6,7 @@ // Change the json schema instead #![allow(dead_code)] +#![allow(unused_mut)] use wasmlib::*; @@ -15,41 +16,41 @@ pub struct Erc721Events { impl Erc721Events { pub fn approval(&self, approved: &ScAgentID, owner: &ScAgentID, token_id: &ScHash) { - let mut encoder = EventEncoder::new("erc721.approval"); - encoder.agent_id(&approved); - encoder.agent_id(&owner); - encoder.hash(&token_id); - encoder.emit(); + let mut evt = EventEncoder::new("erc721.approval"); + evt.encode(&agent_id_to_string(&approved)); + evt.encode(&agent_id_to_string(&owner)); + evt.encode(&hash_to_string(&token_id)); + evt.emit(); } pub fn approval_for_all(&self, approval: bool, operator: &ScAgentID, owner: &ScAgentID) { - let mut encoder = EventEncoder::new("erc721.approvalForAll"); - encoder.bool(approval); - encoder.agent_id(&operator); - encoder.agent_id(&owner); - encoder.emit(); + let mut evt = EventEncoder::new("erc721.approvalForAll"); + evt.encode(&bool_to_string(approval)); + evt.encode(&agent_id_to_string(&operator)); + evt.encode(&agent_id_to_string(&owner)); + evt.emit(); } pub fn init(&self, name: &str, symbol: &str) { - let mut encoder = EventEncoder::new("erc721.init"); - encoder.string(&name); - encoder.string(&symbol); - encoder.emit(); + let mut evt = EventEncoder::new("erc721.init"); + evt.encode(&string_to_string(&name)); + evt.encode(&string_to_string(&symbol)); + evt.emit(); } pub fn mint(&self, balance: u64, owner: &ScAgentID, token_id: &ScHash) { - let mut encoder = EventEncoder::new("erc721.mint"); - encoder.uint64(balance); - encoder.agent_id(&owner); - encoder.hash(&token_id); - encoder.emit(); + let mut evt = EventEncoder::new("erc721.mint"); + evt.encode(&uint64_to_string(balance)); + evt.encode(&agent_id_to_string(&owner)); + evt.encode(&hash_to_string(&token_id)); + evt.emit(); } pub fn transfer(&self, from: &ScAgentID, to: &ScAgentID, token_id: &ScHash) { - let mut encoder = EventEncoder::new("erc721.transfer"); - encoder.agent_id(&from); - encoder.agent_id(&to); - encoder.hash(&token_id); - encoder.emit(); + let mut evt = EventEncoder::new("erc721.transfer"); + evt.encode(&agent_id_to_string(&from)); + evt.encode(&agent_id_to_string(&to)); + evt.encode(&hash_to_string(&token_id)); + evt.emit(); } } diff --git a/contracts/wasm/erc721/src/keys.rs b/contracts/wasm/erc721/src/keys.rs deleted file mode 100644 index dacf7d5ea9..0000000000 --- a/contracts/wasm/erc721/src/keys.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_APPROVAL : usize = 0; -pub(crate) const IDX_PARAM_APPROVED : usize = 1; -pub(crate) const IDX_PARAM_DATA : usize = 2; -pub(crate) const IDX_PARAM_FROM : usize = 3; -pub(crate) const IDX_PARAM_NAME : usize = 4; -pub(crate) const IDX_PARAM_OPERATOR : usize = 5; -pub(crate) const IDX_PARAM_OWNER : usize = 6; -pub(crate) const IDX_PARAM_SYMBOL : usize = 7; -pub(crate) const IDX_PARAM_TO : usize = 8; -pub(crate) const IDX_PARAM_TOKEN_ID : usize = 9; -pub(crate) const IDX_PARAM_TOKEN_URI : usize = 10; - -pub(crate) const IDX_RESULT_AMOUNT : usize = 11; -pub(crate) const IDX_RESULT_APPROVAL : usize = 12; -pub(crate) const IDX_RESULT_APPROVED : usize = 13; -pub(crate) const IDX_RESULT_NAME : usize = 14; -pub(crate) const IDX_RESULT_OWNER : usize = 15; -pub(crate) const IDX_RESULT_SYMBOL : usize = 16; -pub(crate) const IDX_RESULT_TOKEN_URI : usize = 17; - -pub(crate) const IDX_STATE_APPROVED_ACCOUNTS : usize = 18; -pub(crate) const IDX_STATE_APPROVED_OPERATORS : usize = 19; -pub(crate) const IDX_STATE_BALANCES : usize = 20; -pub(crate) const IDX_STATE_NAME : usize = 21; -pub(crate) const IDX_STATE_OWNERS : usize = 22; -pub(crate) const IDX_STATE_SYMBOL : usize = 23; -pub(crate) const IDX_STATE_TOKEN_UR_IS : usize = 24; - -pub const KEY_MAP_LEN: usize = 25; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_APPROVAL, - PARAM_APPROVED, - PARAM_DATA, - PARAM_FROM, - PARAM_NAME, - PARAM_OPERATOR, - PARAM_OWNER, - PARAM_SYMBOL, - PARAM_TO, - PARAM_TOKEN_ID, - PARAM_TOKEN_URI, - RESULT_AMOUNT, - RESULT_APPROVAL, - RESULT_APPROVED, - RESULT_NAME, - RESULT_OWNER, - RESULT_SYMBOL, - RESULT_TOKEN_URI, - STATE_APPROVED_ACCOUNTS, - STATE_APPROVED_OPERATORS, - STATE_BALANCES, - STATE_NAME, - STATE_OWNERS, - STATE_SYMBOL, - STATE_TOKEN_UR_IS, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/erc721/src/lib.rs b/contracts/wasm/erc721/src/lib.rs index c1ab699f72..dee5099251 100644 --- a/contracts/wasm/erc721/src/lib.rs +++ b/contracts/wasm/erc721/src/lib.rs @@ -10,48 +10,69 @@ use erc721::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; use crate::events::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::typedefs::*; mod consts; mod contract; mod events; -mod keys; mod params; mod results; mod state; mod typedefs; + mod erc721; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_APPROVE, + FUNC_BURN, + FUNC_INIT, + FUNC_MINT, + FUNC_SAFE_TRANSFER_FROM, + FUNC_SET_APPROVAL_FOR_ALL, + FUNC_TRANSFER_FROM, + VIEW_BALANCE_OF, + VIEW_GET_APPROVED, + VIEW_IS_APPROVED_FOR_ALL, + VIEW_NAME, + VIEW_OWNER_OF, + VIEW_SYMBOL, + VIEW_TOKEN_URI, + ], + funcs: &[ + func_approve_thunk, + func_burn_thunk, + func_init_thunk, + func_mint_thunk, + func_safe_transfer_from_thunk, + func_set_approval_for_all_thunk, + func_transfer_from_thunk, + ], + views: &[ + view_balance_of_thunk, + view_get_approved_thunk, + view_is_approved_for_all_thunk, + view_name_thunk, + view_owner_of_thunk, + view_symbol_thunk, + view_token_uri_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_APPROVE, func_approve_thunk); - exports.add_func(FUNC_BURN, func_burn_thunk); - exports.add_func(FUNC_INIT, func_init_thunk); - exports.add_func(FUNC_MINT, func_mint_thunk); - exports.add_func(FUNC_SAFE_TRANSFER_FROM, func_safe_transfer_from_thunk); - exports.add_func(FUNC_SET_APPROVAL_FOR_ALL, func_set_approval_for_all_thunk); - exports.add_func(FUNC_TRANSFER_FROM, func_transfer_from_thunk); - exports.add_view(VIEW_BALANCE_OF, view_balance_of_thunk); - exports.add_view(VIEW_GET_APPROVED, view_get_approved_thunk); - exports.add_view(VIEW_IS_APPROVED_FOR_ALL, view_is_approved_for_all_thunk); - exports.add_view(VIEW_NAME, view_name_thunk); - exports.add_view(VIEW_OWNER_OF, view_owner_of_thunk); - exports.add_view(VIEW_SYMBOL, view_symbol_thunk); - exports.add_view(VIEW_TOKEN_URI, view_token_uri_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct ApproveContext { @@ -64,12 +85,8 @@ fn func_approve_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcApprove"); let f = ApproveContext { events: Erc721Events {}, - params: ImmutableApproveParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableApproveParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); func_approve(ctx, &f); @@ -86,12 +103,8 @@ fn func_burn_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcBurn"); let f = BurnContext { events: Erc721Events {}, - params: ImmutableBurnParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableBurnParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); func_burn(ctx, &f); @@ -108,12 +121,8 @@ fn func_init_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcInit"); let f = InitContext { events: Erc721Events {}, - params: ImmutableInitParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableInitParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); ctx.require(f.params.symbol().exists(), "missing mandatory symbol"); @@ -131,12 +140,8 @@ fn func_mint_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcMint"); let f = MintContext { events: Erc721Events {}, - params: ImmutableMintParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableMintParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); func_mint(ctx, &f); @@ -153,12 +158,8 @@ fn func_safe_transfer_from_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcSafeTransferFrom"); let f = SafeTransferFromContext { events: Erc721Events {}, - params: ImmutableSafeTransferFromParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableSafeTransferFromParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.from().exists(), "missing mandatory from"); ctx.require(f.params.to().exists(), "missing mandatory to"); @@ -177,12 +178,8 @@ fn func_set_approval_for_all_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcSetApprovalForAll"); let f = SetApprovalForAllContext { events: Erc721Events {}, - params: ImmutableSetApprovalForAllParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableSetApprovalForAllParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.approval().exists(), "missing mandatory approval"); ctx.require(f.params.operator().exists(), "missing mandatory operator"); @@ -200,12 +197,8 @@ fn func_transfer_from_thunk(ctx: &ScFuncContext) { ctx.log("erc721.funcTransferFrom"); let f = TransferFromContext { events: Erc721Events {}, - params: ImmutableTransferFromParams { - id: OBJ_ID_PARAMS, - }, - state: MutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableTransferFromParams { proxy: params_proxy() }, + state: MutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.from().exists(), "missing mandatory from"); ctx.require(f.params.to().exists(), "missing mandatory to"); @@ -223,18 +216,13 @@ pub struct BalanceOfContext { fn view_balance_of_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewBalanceOf"); let f = BalanceOfContext { - params: ImmutableBalanceOfParams { - id: OBJ_ID_PARAMS, - }, - results: MutableBalanceOfResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableBalanceOfParams { proxy: params_proxy() }, + results: MutableBalanceOfResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.owner().exists(), "missing mandatory owner"); view_balance_of(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewBalanceOf ok"); } @@ -247,18 +235,13 @@ pub struct GetApprovedContext { fn view_get_approved_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewGetApproved"); let f = GetApprovedContext { - params: ImmutableGetApprovedParams { - id: OBJ_ID_PARAMS, - }, - results: MutableGetApprovedResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableGetApprovedParams { proxy: params_proxy() }, + results: MutableGetApprovedResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); view_get_approved(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewGetApproved ok"); } @@ -271,19 +254,14 @@ pub struct IsApprovedForAllContext { fn view_is_approved_for_all_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewIsApprovedForAll"); let f = IsApprovedForAllContext { - params: ImmutableIsApprovedForAllParams { - id: OBJ_ID_PARAMS, - }, - results: MutableIsApprovedForAllResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableIsApprovedForAllParams { proxy: params_proxy() }, + results: MutableIsApprovedForAllResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.operator().exists(), "missing mandatory operator"); ctx.require(f.params.owner().exists(), "missing mandatory owner"); view_is_approved_for_all(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewIsApprovedForAll ok"); } @@ -295,14 +273,11 @@ pub struct NameContext { fn view_name_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewName"); let f = NameContext { - results: MutableNameResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + results: MutableNameResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; view_name(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewName ok"); } @@ -315,18 +290,13 @@ pub struct OwnerOfContext { fn view_owner_of_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewOwnerOf"); let f = OwnerOfContext { - params: ImmutableOwnerOfParams { - id: OBJ_ID_PARAMS, - }, - results: MutableOwnerOfResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableOwnerOfParams { proxy: params_proxy() }, + results: MutableOwnerOfResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); view_owner_of(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewOwnerOf ok"); } @@ -338,14 +308,11 @@ pub struct SymbolContext { fn view_symbol_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewSymbol"); let f = SymbolContext { - results: MutableSymbolResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + results: MutableSymbolResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; view_symbol(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewSymbol ok"); } @@ -358,17 +325,12 @@ pub struct TokenURIContext { fn view_token_uri_thunk(ctx: &ScViewContext) { ctx.log("erc721.viewTokenURI"); let f = TokenURIContext { - params: ImmutableTokenURIParams { - id: OBJ_ID_PARAMS, - }, - results: MutableTokenURIResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableErc721State { - id: OBJ_ID_STATE, - }, + params: ImmutableTokenURIParams { proxy: params_proxy() }, + results: MutableTokenURIResults { proxy: results_proxy() }, + state: ImmutableErc721State { proxy: state_proxy() }, }; ctx.require(f.params.token_id().exists(), "missing mandatory tokenID"); view_token_uri(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("erc721.viewTokenURI ok"); } diff --git a/contracts/wasm/erc721/src/params.rs b/contracts/wasm/erc721/src/params.rs index 14db52728e..b4dd0d00e6 100644 --- a/contracts/wasm/erc721/src/params.rs +++ b/contracts/wasm/erc721/src/params.rs @@ -9,352 +9,348 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableApproveParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableApproveParams { pub fn approved(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_APPROVED.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_APPROVED)) } pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableApproveParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableApproveParams { pub fn approved(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_APPROVED.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_APPROVED)) } pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBurnParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBurnParams { pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBurnParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBurnParams { pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableInitParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, idx_map(IDX_PARAM_NAME)) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } pub fn symbol(&self) -> ScImmutableString { - ScImmutableString::new(self.id, idx_map(IDX_PARAM_SYMBOL)) + ScImmutableString::new(self.proxy.root(PARAM_SYMBOL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableInitParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, idx_map(IDX_PARAM_NAME)) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } pub fn symbol(&self) -> ScMutableString { - ScMutableString::new(self.id, idx_map(IDX_PARAM_SYMBOL)) + ScMutableString::new(self.proxy.root(PARAM_SYMBOL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMintParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMintParams { pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } pub fn token_uri(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_TOKEN_URI.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_TOKEN_URI)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMintParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMintParams { pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } pub fn token_uri(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_TOKEN_URI.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_TOKEN_URI)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSafeTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSafeTransferFromParams { pub fn data(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, PARAM_DATA.get_key_id()) + ScImmutableBytes::new(self.proxy.root(PARAM_DATA)) } pub fn from(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_FROM.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_FROM)) } pub fn to(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_TO.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_TO)) } pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSafeTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSafeTransferFromParams { pub fn data(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, PARAM_DATA.get_key_id()) + ScMutableBytes::new(self.proxy.root(PARAM_DATA)) } pub fn from(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_FROM.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_FROM)) } pub fn to(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_TO.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_TO)) } pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetApprovalForAllParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetApprovalForAllParams { pub fn approval(&self) -> ScImmutableBool { - ScImmutableBool::new(self.id, PARAM_APPROVAL.get_key_id()) + ScImmutableBool::new(self.proxy.root(PARAM_APPROVAL)) } pub fn operator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_OPERATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_OPERATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetApprovalForAllParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetApprovalForAllParams { pub fn approval(&self) -> ScMutableBool { - ScMutableBool::new(self.id, PARAM_APPROVAL.get_key_id()) + ScMutableBool::new(self.proxy.root(PARAM_APPROVAL)) } pub fn operator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_OPERATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_OPERATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTransferFromParams { pub fn from(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_FROM.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_FROM)) } pub fn to(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_TO.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_TO)) } pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTransferFromParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTransferFromParams { pub fn from(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_FROM.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_FROM)) } pub fn to(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_TO.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_TO)) } pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceOfParams { pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceOfParams { pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetApprovedParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetApprovedParams { pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetApprovedParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetApprovedParams { pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableIsApprovedForAllParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableIsApprovedForAllParams { pub fn operator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_OPERATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_OPERATOR)) } pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableIsApprovedForAllParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableIsApprovedForAllParams { pub fn operator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_OPERATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_OPERATOR)) } pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableOwnerOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableOwnerOfParams { pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableOwnerOfParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableOwnerOfParams { pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTokenURIParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTokenURIParams { pub fn token_id(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTokenURIParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTokenURIParams { pub fn token_id(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_TOKEN_ID.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_TOKEN_ID)) } } diff --git a/contracts/wasm/erc721/src/results.rs b/contracts/wasm/erc721/src/results.rs index 12dc895e67..b1fcde1170 100644 --- a/contracts/wasm/erc721/src/results.rs +++ b/contracts/wasm/erc721/src/results.rs @@ -9,162 +9,158 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceOfResults { pub fn amount(&self) -> ScImmutableUint64 { - ScImmutableUint64::new(self.id, RESULT_AMOUNT.get_key_id()) + ScImmutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceOfResults { pub fn amount(&self) -> ScMutableUint64 { - ScMutableUint64::new(self.id, RESULT_AMOUNT.get_key_id()) + ScMutableUint64::new(self.proxy.root(RESULT_AMOUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetApprovedResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetApprovedResults { pub fn approved(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_APPROVED.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_APPROVED)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetApprovedResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetApprovedResults { pub fn approved(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_APPROVED.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_APPROVED)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableIsApprovedForAllResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableIsApprovedForAllResults { pub fn approval(&self) -> ScImmutableBool { - ScImmutableBool::new(self.id, RESULT_APPROVAL.get_key_id()) + ScImmutableBool::new(self.proxy.root(RESULT_APPROVAL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableIsApprovedForAllResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableIsApprovedForAllResults { pub fn approval(&self) -> ScMutableBool { - ScMutableBool::new(self.id, RESULT_APPROVAL.get_key_id()) + ScMutableBool::new(self.proxy.root(RESULT_APPROVAL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableNameResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableNameResults { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableNameResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableNameResults { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableOwnerOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableOwnerOfResults { pub fn owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableOwnerOfResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableOwnerOfResults { pub fn owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSymbolResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSymbolResults { pub fn symbol(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_SYMBOL.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_SYMBOL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSymbolResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSymbolResults { pub fn symbol(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_SYMBOL.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_SYMBOL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTokenURIResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTokenURIResults { pub fn token_uri(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_TOKEN_URI.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_TOKEN_URI)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTokenURIResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTokenURIResults { pub fn token_uri(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_TOKEN_URI.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_TOKEN_URI)) } } diff --git a/contracts/wasm/erc721/src/state.rs b/contracts/wasm/erc721/src/state.rs index 48a77bd618..e99e1ca9f5 100644 --- a/contracts/wasm/erc721/src/state.rs +++ b/contracts/wasm/erc721/src/state.rs @@ -9,198 +9,183 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToImmutableAgentID { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToImmutableAgentID { pub fn get_agent_id(&self, key: &ScHash) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.obj_id, key.get_key_id()) + ScImmutableAgentID::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableOperators { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableOperators { pub fn get_operators(&self, key: &ScAgentID) -> ImmutableOperators { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ImmutableOperators { obj_id: sub_id } + ImmutableOperators { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableUint64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableUint64 { pub fn get_uint64(&self, key: &ScAgentID) -> ScImmutableUint64 { - ScImmutableUint64::new(self.obj_id, key.get_key_id()) + ScImmutableUint64::new(self.proxy.key(&agent_id_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToImmutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToImmutableString { pub fn get_string(&self, key: &ScHash) -> ScImmutableString { - ScImmutableString::new(self.obj_id, key.get_key_id()) + ScImmutableString::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableErc721State { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableErc721State { pub fn approved_accounts(&self) -> MapHashToImmutableAgentID { - let map_id = get_object_id(self.id, STATE_APPROVED_ACCOUNTS.get_key_id(), TYPE_MAP); - MapHashToImmutableAgentID { obj_id: map_id } + MapHashToImmutableAgentID { proxy: self.proxy.root(STATE_APPROVED_ACCOUNTS) } } pub fn approved_operators(&self) -> MapAgentIDToImmutableOperators { - let map_id = get_object_id(self.id, STATE_APPROVED_OPERATORS.get_key_id(), TYPE_MAP); - MapAgentIDToImmutableOperators { obj_id: map_id } + MapAgentIDToImmutableOperators { proxy: self.proxy.root(STATE_APPROVED_OPERATORS) } } pub fn balances(&self) -> MapAgentIDToImmutableUint64 { - let map_id = get_object_id(self.id, STATE_BALANCES.get_key_id(), TYPE_MAP); - MapAgentIDToImmutableUint64 { obj_id: map_id } + MapAgentIDToImmutableUint64 { proxy: self.proxy.root(STATE_BALANCES) } } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, STATE_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(STATE_NAME)) } pub fn owners(&self) -> MapHashToImmutableAgentID { - let map_id = get_object_id(self.id, STATE_OWNERS.get_key_id(), TYPE_MAP); - MapHashToImmutableAgentID { obj_id: map_id } + MapHashToImmutableAgentID { proxy: self.proxy.root(STATE_OWNERS) } } pub fn symbol(&self) -> ScImmutableString { - ScImmutableString::new(self.id, STATE_SYMBOL.get_key_id()) + ScImmutableString::new(self.proxy.root(STATE_SYMBOL)) } pub fn token_ur_is(&self) -> MapHashToImmutableString { - let map_id = get_object_id(self.id, STATE_TOKEN_UR_IS.get_key_id(), TYPE_MAP); - MapHashToImmutableString { obj_id: map_id } + MapHashToImmutableString { proxy: self.proxy.root(STATE_TOKEN_UR_IS) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToMutableAgentID { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToMutableAgentID { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_agent_id(&self, key: &ScHash) -> ScMutableAgentID { - ScMutableAgentID::new(self.obj_id, key.get_key_id()) + ScMutableAgentID::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableOperators { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableOperators { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_operators(&self, key: &ScAgentID) -> MutableOperators { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - MutableOperators { obj_id: sub_id } + MutableOperators { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableUint64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableUint64 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_uint64(&self, key: &ScAgentID) -> ScMutableUint64 { - ScMutableUint64::new(self.obj_id, key.get_key_id()) + ScMutableUint64::new(self.proxy.key(&agent_id_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToMutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToMutableString { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_string(&self, key: &ScHash) -> ScMutableString { - ScMutableString::new(self.obj_id, key.get_key_id()) + ScMutableString::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableErc721State { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableErc721State { pub fn as_immutable(&self) -> ImmutableErc721State { - ImmutableErc721State { id: self.id } + ImmutableErc721State { proxy: self.proxy.root("") } } pub fn approved_accounts(&self) -> MapHashToMutableAgentID { - let map_id = get_object_id(self.id, STATE_APPROVED_ACCOUNTS.get_key_id(), TYPE_MAP); - MapHashToMutableAgentID { obj_id: map_id } + MapHashToMutableAgentID { proxy: self.proxy.root(STATE_APPROVED_ACCOUNTS) } } pub fn approved_operators(&self) -> MapAgentIDToMutableOperators { - let map_id = get_object_id(self.id, STATE_APPROVED_OPERATORS.get_key_id(), TYPE_MAP); - MapAgentIDToMutableOperators { obj_id: map_id } + MapAgentIDToMutableOperators { proxy: self.proxy.root(STATE_APPROVED_OPERATORS) } } pub fn balances(&self) -> MapAgentIDToMutableUint64 { - let map_id = get_object_id(self.id, STATE_BALANCES.get_key_id(), TYPE_MAP); - MapAgentIDToMutableUint64 { obj_id: map_id } + MapAgentIDToMutableUint64 { proxy: self.proxy.root(STATE_BALANCES) } } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, STATE_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(STATE_NAME)) } pub fn owners(&self) -> MapHashToMutableAgentID { - let map_id = get_object_id(self.id, STATE_OWNERS.get_key_id(), TYPE_MAP); - MapHashToMutableAgentID { obj_id: map_id } + MapHashToMutableAgentID { proxy: self.proxy.root(STATE_OWNERS) } } pub fn symbol(&self) -> ScMutableString { - ScMutableString::new(self.id, STATE_SYMBOL.get_key_id()) + ScMutableString::new(self.proxy.root(STATE_SYMBOL)) } pub fn token_ur_is(&self) -> MapHashToMutableString { - let map_id = get_object_id(self.id, STATE_TOKEN_UR_IS.get_key_id(), TYPE_MAP); - MapHashToMutableString { obj_id: map_id } + MapHashToMutableString { proxy: self.proxy.root(STATE_TOKEN_UR_IS) } } } diff --git a/contracts/wasm/erc721/src/typedefs.rs b/contracts/wasm/erc721/src/typedefs.rs index 63cd1a30d9..67f2f69ea0 100644 --- a/contracts/wasm/erc721/src/typedefs.rs +++ b/contracts/wasm/erc721/src/typedefs.rs @@ -8,33 +8,33 @@ #![allow(dead_code)] use wasmlib::*; -use wasmlib::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableBool { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableBool { pub fn get_bool(&self, key: &ScAgentID) -> ScImmutableBool { - ScImmutableBool::new(self.obj_id, key.get_key_id()) + ScImmutableBool::new(self.proxy.key(&agent_id_to_bytes(key))) } } pub type ImmutableOperators = MapAgentIDToImmutableBool; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableBool { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableBool { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bool(&self, key: &ScAgentID) -> ScMutableBool { - ScMutableBool::new(self.obj_id, key.get_key_id()) + ScMutableBool::new(self.proxy.key(&agent_id_to_bytes(key))) } } diff --git a/contracts/wasm/erc721/test/erc721_bg.wasm b/contracts/wasm/erc721/test/erc721_bg.wasm index 5031bf39d0..6e8e6b469e 100644 Binary files a/contracts/wasm/erc721/test/erc721_bg.wasm and b/contracts/wasm/erc721/test/erc721_bg.wasm differ diff --git a/contracts/wasm/erc721/test/erc721_test.go b/contracts/wasm/erc721/test/erc721_test.go index b1f33b11ce..9bdbe14232 100644 --- a/contracts/wasm/erc721/test/erc721_test.go +++ b/contracts/wasm/erc721/test/erc721_test.go @@ -7,8 +7,8 @@ import ( "testing" "github.com/iotaledger/wasp/contracts/wasm/erc721/go/erc721" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -20,7 +20,7 @@ func TestDeploy(t *testing.T) { func TestMint(t *testing.T) { ctx := setup(t) owner := ctx.NewSoloAgent() - tokenID := wasmlib.NewScHashFromBytes(owner.ScAgentID().Bytes()[:32]) + tokenID := wasmtypes.HashFromBytes(owner.ScAgentID().Bytes()[:32]) mint(ctx, owner, tokenID) require.NoError(t, ctx.Err) } @@ -28,7 +28,7 @@ func TestMint(t *testing.T) { func TestApprove(t *testing.T) { ctx := setup(t) owner := ctx.NewSoloAgent() - tokenID := wasmlib.NewScHashFromBytes(owner.ScAgentID().Bytes()[:32]) + tokenID := wasmtypes.HashFromBytes(owner.ScAgentID().Bytes()[:32]) mint(ctx, owner, tokenID) require.NoError(t, ctx.Err) @@ -58,7 +58,7 @@ func TestApprove(t *testing.T) { func TestApproveAll(t *testing.T) { ctx := setup(t) owner := ctx.NewSoloAgent() - tokenID := wasmlib.NewScHashFromBytes(owner.ScAgentID().Bytes()[:32]) + tokenID := wasmtypes.HashFromBytes(owner.ScAgentID().Bytes()[:32]) mint(ctx, owner, tokenID) require.NoError(t, ctx.Err) @@ -100,7 +100,7 @@ func TestApproveAll(t *testing.T) { func TestTransferFrom(t *testing.T) { ctx := setup(t) owner := ctx.NewSoloAgent() - tokenID := wasmlib.NewScHashFromBytes(owner.ScAgentID().Bytes()[:32]) + tokenID := wasmtypes.HashFromBytes(owner.ScAgentID().Bytes()[:32]) mint(ctx, owner, tokenID) require.NoError(t, ctx.Err) @@ -155,16 +155,16 @@ func setup(t *testing.T) *wasmsolo.SoloContext { return ctx } -func approve(ctx *wasmsolo.SoloContext, owner, approved *wasmsolo.SoloAgent, tokenID wasmlib.ScHash) { +func approve(ctx *wasmsolo.SoloContext, owner, approved *wasmsolo.SoloAgent, tokenID wasmtypes.ScHash) { f := erc721.ScFuncs.Approve(ctx.Sign(owner)) if approved != nil { f.Params.Approved().SetValue(approved.ScAgentID()) } f.Params.TokenID().SetValue(tokenID) - f.Func.TransferIotas(1).Post() + f.Func.Post() } -func getApproved(t *testing.T, ctx *wasmsolo.SoloContext, tokenID wasmlib.ScHash) *wasmlib.ScAgentID { +func getApproved(t *testing.T, ctx *wasmsolo.SoloContext, tokenID wasmtypes.ScHash) *wasmtypes.ScAgentID { v := erc721.ScFuncs.GetApproved(ctx) v.Params.TokenID().SetValue(tokenID) v.Func.Call() @@ -186,13 +186,13 @@ func isApprovedForAll(t *testing.T, ctx *wasmsolo.SoloContext, owner, friend *wa return v.Results.Approval().Value() } -func mint(ctx *wasmsolo.SoloContext, owner *wasmsolo.SoloAgent, tokenID wasmlib.ScHash) { +func mint(ctx *wasmsolo.SoloContext, owner *wasmsolo.SoloAgent, tokenID wasmtypes.ScHash) { f := erc721.ScFuncs.Mint(ctx.Sign(owner)) f.Params.TokenID().SetValue(tokenID) - f.Func.TransferIotas(1).Post() + f.Func.Post() } -func ownerOf(t *testing.T, ctx *wasmsolo.SoloContext, tokenID wasmlib.ScHash) wasmlib.ScAgentID { +func ownerOf(t *testing.T, ctx *wasmsolo.SoloContext, tokenID wasmtypes.ScHash) wasmtypes.ScAgentID { v := erc721.ScFuncs.OwnerOf(ctx) v.Params.TokenID().SetValue(tokenID) v.Func.Call() @@ -204,13 +204,13 @@ func setApprovalForAll(ctx *wasmsolo.SoloContext, owner, operator *wasmsolo.Solo f := erc721.ScFuncs.SetApprovalForAll(ctx.Sign(owner)) f.Params.Operator().SetValue(operator.ScAgentID()) f.Params.Approval().SetValue(approval) - f.Func.TransferIotas(1).Post() + f.Func.Post() } -func transferFrom(ctx *wasmsolo.SoloContext, sender, from, to *wasmsolo.SoloAgent, tokenID wasmlib.ScHash) { +func transferFrom(ctx *wasmsolo.SoloContext, sender, from, to *wasmsolo.SoloAgent, tokenID wasmtypes.ScHash) { f := erc721.ScFuncs.TransferFrom(ctx.Sign(sender)) f.Params.From().SetValue(from.ScAgentID()) f.Params.To().SetValue(to.ScAgentID()) f.Params.TokenID().SetValue(tokenID) - f.Func.TransferIotas(1).Post() + f.Func.Post() } diff --git a/contracts/wasm/erc721/ts/erc721/consts.ts b/contracts/wasm/erc721/ts/erc721/consts.ts index e32306cfa0..ce4dd6ae97 100644 --- a/contracts/wasm/erc721/ts/erc721/consts.ts +++ b/contracts/wasm/erc721/ts/erc721/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "erc721"; export const ScDescription = "ERC-721 NFT PoC for IOTA Smart Contracts"; -export const HScName = new wasmlib.ScHname(0xd967c216); +export const HScName = new wasmtypes.ScHname(0xd967c216); export const ParamApproval = "approval"; export const ParamApproved = "approved"; @@ -54,17 +54,17 @@ export const ViewOwnerOf = "ownerOf"; export const ViewSymbol = "symbol"; export const ViewTokenURI = "tokenURI"; -export const HFuncApprove = new wasmlib.ScHname(0xa0661268); -export const HFuncBurn = new wasmlib.ScHname(0x7bc1efb1); -export const HFuncInit = new wasmlib.ScHname(0x1f44d644); -export const HFuncMint = new wasmlib.ScHname(0xa29addcf); -export const HFuncSafeTransferFrom = new wasmlib.ScHname(0x130ce158); -export const HFuncSetApprovalForAll = new wasmlib.ScHname(0xb8d8c776); -export const HFuncTransferFrom = new wasmlib.ScHname(0xd5e0a602); -export const HViewBalanceOf = new wasmlib.ScHname(0x67ef8df4); -export const HViewGetApproved = new wasmlib.ScHname(0xbe34b6ba); -export const HViewIsApprovedForAll = new wasmlib.ScHname(0x3251b0f0); -export const HViewName = new wasmlib.ScHname(0x0df7da3a); -export const HViewOwnerOf = new wasmlib.ScHname(0x1246f5ad); -export const HViewSymbol = new wasmlib.ScHname(0x3e93d19b); -export const HViewTokenURI = new wasmlib.ScHname(0x4e1a7397); +export const HFuncApprove = new wasmtypes.ScHname(0xa0661268); +export const HFuncBurn = new wasmtypes.ScHname(0x7bc1efb1); +export const HFuncInit = new wasmtypes.ScHname(0x1f44d644); +export const HFuncMint = new wasmtypes.ScHname(0xa29addcf); +export const HFuncSafeTransferFrom = new wasmtypes.ScHname(0x130ce158); +export const HFuncSetApprovalForAll = new wasmtypes.ScHname(0xb8d8c776); +export const HFuncTransferFrom = new wasmtypes.ScHname(0xd5e0a602); +export const HViewBalanceOf = new wasmtypes.ScHname(0x67ef8df4); +export const HViewGetApproved = new wasmtypes.ScHname(0xbe34b6ba); +export const HViewIsApprovedForAll = new wasmtypes.ScHname(0x3251b0f0); +export const HViewName = new wasmtypes.ScHname(0x0df7da3a); +export const HViewOwnerOf = new wasmtypes.ScHname(0x1246f5ad); +export const HViewSymbol = new wasmtypes.ScHname(0x3e93d19b); +export const HViewTokenURI = new wasmtypes.ScHname(0x4e1a7397); diff --git a/contracts/wasm/erc721/ts/erc721/contract.ts b/contracts/wasm/erc721/ts/erc721/contract.ts index e14506cc23..be0d18e294 100644 --- a/contracts/wasm/erc721/ts/erc721/contract.ts +++ b/contracts/wasm/erc721/ts/erc721/contract.ts @@ -10,243 +10,248 @@ import * as sc from "./index"; export class ApproveCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncApprove); - params: sc.MutableApproveParams = new sc.MutableApproveParams(); + params: sc.MutableApproveParams = new sc.MutableApproveParams(wasmlib.ScView.nilProxy); } export class ApproveContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableApproveParams = new sc.ImmutableApproveParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableApproveParams = new sc.ImmutableApproveParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class BurnCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncBurn); - params: sc.MutableBurnParams = new sc.MutableBurnParams(); + params: sc.MutableBurnParams = new sc.MutableBurnParams(wasmlib.ScView.nilProxy); } export class BurnContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableBurnParams = new sc.ImmutableBurnParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableBurnParams = new sc.ImmutableBurnParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); - params: sc.MutableInitParams = new sc.MutableInitParams(); + params: sc.MutableInitParams = new sc.MutableInitParams(wasmlib.ScView.nilProxy); } export class InitContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableInitParams = new sc.ImmutableInitParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class MintCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMint); - params: sc.MutableMintParams = new sc.MutableMintParams(); + params: sc.MutableMintParams = new sc.MutableMintParams(wasmlib.ScView.nilProxy); } export class MintContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableMintParams = new sc.ImmutableMintParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableMintParams = new sc.ImmutableMintParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class SafeTransferFromCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSafeTransferFrom); - params: sc.MutableSafeTransferFromParams = new sc.MutableSafeTransferFromParams(); + params: sc.MutableSafeTransferFromParams = new sc.MutableSafeTransferFromParams(wasmlib.ScView.nilProxy); } export class SafeTransferFromContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableSafeTransferFromParams = new sc.ImmutableSafeTransferFromParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableSafeTransferFromParams = new sc.ImmutableSafeTransferFromParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class SetApprovalForAllCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetApprovalForAll); - params: sc.MutableSetApprovalForAllParams = new sc.MutableSetApprovalForAllParams(); + params: sc.MutableSetApprovalForAllParams = new sc.MutableSetApprovalForAllParams(wasmlib.ScView.nilProxy); } export class SetApprovalForAllContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableSetApprovalForAllParams = new sc.ImmutableSetApprovalForAllParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableSetApprovalForAllParams = new sc.ImmutableSetApprovalForAllParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class TransferFromCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTransferFrom); - params: sc.MutableTransferFromParams = new sc.MutableTransferFromParams(); + params: sc.MutableTransferFromParams = new sc.MutableTransferFromParams(wasmlib.ScView.nilProxy); } export class TransferFromContext { events: sc.Erc721Events = new sc.Erc721Events(); - params: sc.ImmutableTransferFromParams = new sc.ImmutableTransferFromParams(); - state: sc.MutableErc721State = new sc.MutableErc721State(); + params: sc.ImmutableTransferFromParams = new sc.ImmutableTransferFromParams(wasmlib.paramsProxy()); + state: sc.MutableErc721State = new sc.MutableErc721State(wasmlib.ScState.proxy()); } export class BalanceOfCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBalanceOf); - params: sc.MutableBalanceOfParams = new sc.MutableBalanceOfParams(); - results: sc.ImmutableBalanceOfResults = new sc.ImmutableBalanceOfResults(); + params: sc.MutableBalanceOfParams = new sc.MutableBalanceOfParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableBalanceOfResults = new sc.ImmutableBalanceOfResults(wasmlib.ScView.nilProxy); } export class BalanceOfContext { - params: sc.ImmutableBalanceOfParams = new sc.ImmutableBalanceOfParams(); - results: sc.MutableBalanceOfResults = new sc.MutableBalanceOfResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + params: sc.ImmutableBalanceOfParams = new sc.ImmutableBalanceOfParams(wasmlib.paramsProxy()); + results: sc.MutableBalanceOfResults = new sc.MutableBalanceOfResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class GetApprovedCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetApproved); - params: sc.MutableGetApprovedParams = new sc.MutableGetApprovedParams(); - results: sc.ImmutableGetApprovedResults = new sc.ImmutableGetApprovedResults(); + params: sc.MutableGetApprovedParams = new sc.MutableGetApprovedParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetApprovedResults = new sc.ImmutableGetApprovedResults(wasmlib.ScView.nilProxy); } export class GetApprovedContext { - params: sc.ImmutableGetApprovedParams = new sc.ImmutableGetApprovedParams(); - results: sc.MutableGetApprovedResults = new sc.MutableGetApprovedResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + params: sc.ImmutableGetApprovedParams = new sc.ImmutableGetApprovedParams(wasmlib.paramsProxy()); + results: sc.MutableGetApprovedResults = new sc.MutableGetApprovedResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class IsApprovedForAllCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewIsApprovedForAll); - params: sc.MutableIsApprovedForAllParams = new sc.MutableIsApprovedForAllParams(); - results: sc.ImmutableIsApprovedForAllResults = new sc.ImmutableIsApprovedForAllResults(); + params: sc.MutableIsApprovedForAllParams = new sc.MutableIsApprovedForAllParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableIsApprovedForAllResults = new sc.ImmutableIsApprovedForAllResults(wasmlib.ScView.nilProxy); } export class IsApprovedForAllContext { - params: sc.ImmutableIsApprovedForAllParams = new sc.ImmutableIsApprovedForAllParams(); - results: sc.MutableIsApprovedForAllResults = new sc.MutableIsApprovedForAllResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + params: sc.ImmutableIsApprovedForAllParams = new sc.ImmutableIsApprovedForAllParams(wasmlib.paramsProxy()); + results: sc.MutableIsApprovedForAllResults = new sc.MutableIsApprovedForAllResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class NameCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewName); - results: sc.ImmutableNameResults = new sc.ImmutableNameResults(); + results: sc.ImmutableNameResults = new sc.ImmutableNameResults(wasmlib.ScView.nilProxy); } export class NameContext { - results: sc.MutableNameResults = new sc.MutableNameResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + results: sc.MutableNameResults = new sc.MutableNameResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class OwnerOfCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewOwnerOf); - params: sc.MutableOwnerOfParams = new sc.MutableOwnerOfParams(); - results: sc.ImmutableOwnerOfResults = new sc.ImmutableOwnerOfResults(); + params: sc.MutableOwnerOfParams = new sc.MutableOwnerOfParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableOwnerOfResults = new sc.ImmutableOwnerOfResults(wasmlib.ScView.nilProxy); } export class OwnerOfContext { - params: sc.ImmutableOwnerOfParams = new sc.ImmutableOwnerOfParams(); - results: sc.MutableOwnerOfResults = new sc.MutableOwnerOfResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + params: sc.ImmutableOwnerOfParams = new sc.ImmutableOwnerOfParams(wasmlib.paramsProxy()); + results: sc.MutableOwnerOfResults = new sc.MutableOwnerOfResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class SymbolCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewSymbol); - results: sc.ImmutableSymbolResults = new sc.ImmutableSymbolResults(); + results: sc.ImmutableSymbolResults = new sc.ImmutableSymbolResults(wasmlib.ScView.nilProxy); } export class SymbolContext { - results: sc.MutableSymbolResults = new sc.MutableSymbolResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + results: sc.MutableSymbolResults = new sc.MutableSymbolResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class TokenURICall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTokenURI); - params: sc.MutableTokenURIParams = new sc.MutableTokenURIParams(); - results: sc.ImmutableTokenURIResults = new sc.ImmutableTokenURIResults(); + params: sc.MutableTokenURIParams = new sc.MutableTokenURIParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableTokenURIResults = new sc.ImmutableTokenURIResults(wasmlib.ScView.nilProxy); } export class TokenURIContext { - params: sc.ImmutableTokenURIParams = new sc.ImmutableTokenURIParams(); - results: sc.MutableTokenURIResults = new sc.MutableTokenURIResults(); - state: sc.ImmutableErc721State = new sc.ImmutableErc721State(); + params: sc.ImmutableTokenURIParams = new sc.ImmutableTokenURIParams(wasmlib.paramsProxy()); + results: sc.MutableTokenURIResults = new sc.MutableTokenURIResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableErc721State = new sc.ImmutableErc721State(wasmlib.ScState.proxy()); } export class ScFuncs { - static approve(ctx: wasmlib.ScFuncCallContext): ApproveCall { - let f = new ApproveCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static burn(ctx: wasmlib.ScFuncCallContext): BurnCall { - let f = new BurnCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static init(ctx: wasmlib.ScFuncCallContext): InitCall { - let f = new InitCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static mint(ctx: wasmlib.ScFuncCallContext): MintCall { - let f = new MintCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static safeTransferFrom(ctx: wasmlib.ScFuncCallContext): SafeTransferFromCall { - let f = new SafeTransferFromCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setApprovalForAll(ctx: wasmlib.ScFuncCallContext): SetApprovalForAllCall { - let f = new SetApprovalForAllCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static transferFrom(ctx: wasmlib.ScFuncCallContext): TransferFromCall { - let f = new TransferFromCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static balanceOf(ctx: wasmlib.ScViewCallContext): BalanceOfCall { - let f = new BalanceOfCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getApproved(ctx: wasmlib.ScViewCallContext): GetApprovedCall { - let f = new GetApprovedCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static isApprovedForAll(ctx: wasmlib.ScViewCallContext): IsApprovedForAllCall { - let f = new IsApprovedForAllCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static name(ctx: wasmlib.ScViewCallContext): NameCall { - let f = new NameCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static ownerOf(ctx: wasmlib.ScViewCallContext): OwnerOfCall { - let f = new OwnerOfCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static symbol(ctx: wasmlib.ScViewCallContext): SymbolCall { - let f = new SymbolCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static tokenURI(ctx: wasmlib.ScViewCallContext): TokenURICall { - let f = new TokenURICall(); - f.func.setPtrs(f.params, f.results); - return f; - } + static approve(_ctx: wasmlib.ScFuncCallContext): ApproveCall { + const f = new ApproveCall(); + f.params = new sc.MutableApproveParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static burn(_ctx: wasmlib.ScFuncCallContext): BurnCall { + const f = new BurnCall(); + f.params = new sc.MutableBurnParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static init(_ctx: wasmlib.ScFuncCallContext): InitCall { + const f = new InitCall(); + f.params = new sc.MutableInitParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static mint(_ctx: wasmlib.ScFuncCallContext): MintCall { + const f = new MintCall(); + f.params = new sc.MutableMintParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static safeTransferFrom(_ctx: wasmlib.ScFuncCallContext): SafeTransferFromCall { + const f = new SafeTransferFromCall(); + f.params = new sc.MutableSafeTransferFromParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setApprovalForAll(_ctx: wasmlib.ScFuncCallContext): SetApprovalForAllCall { + const f = new SetApprovalForAllCall(); + f.params = new sc.MutableSetApprovalForAllParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static transferFrom(_ctx: wasmlib.ScFuncCallContext): TransferFromCall { + const f = new TransferFromCall(); + f.params = new sc.MutableTransferFromParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static balanceOf(_ctx: wasmlib.ScViewCallContext): BalanceOfCall { + const f = new BalanceOfCall(); + f.params = new sc.MutableBalanceOfParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableBalanceOfResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getApproved(_ctx: wasmlib.ScViewCallContext): GetApprovedCall { + const f = new GetApprovedCall(); + f.params = new sc.MutableGetApprovedParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetApprovedResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static isApprovedForAll(_ctx: wasmlib.ScViewCallContext): IsApprovedForAllCall { + const f = new IsApprovedForAllCall(); + f.params = new sc.MutableIsApprovedForAllParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableIsApprovedForAllResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static name(_ctx: wasmlib.ScViewCallContext): NameCall { + const f = new NameCall(); + f.results = new sc.ImmutableNameResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static ownerOf(_ctx: wasmlib.ScViewCallContext): OwnerOfCall { + const f = new OwnerOfCall(); + f.params = new sc.MutableOwnerOfParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableOwnerOfResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static symbol(_ctx: wasmlib.ScViewCallContext): SymbolCall { + const f = new SymbolCall(); + f.results = new sc.ImmutableSymbolResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static tokenURI(_ctx: wasmlib.ScViewCallContext): TokenURICall { + const f = new TokenURICall(); + f.params = new sc.MutableTokenURIParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableTokenURIResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/erc721/ts/erc721/erc721.ts b/contracts/wasm/erc721/ts/erc721/erc721.ts index 3a0612f769..de8b9052f7 100644 --- a/contracts/wasm/erc721/ts/erc721/erc721.ts +++ b/contracts/wasm/erc721/ts/erc721/erc721.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; // Follows ERC-721 standard as closely as possible @@ -16,12 +17,12 @@ import * as sc from "./index"; // set the required base URI, to which the base58 encoded token ID will be concatenated const BASE_URI = "my/special/base/uri/"; -const ZERO = new wasmlib.ScAgentID() +const ZERO = wasmtypes.agentIDFromBytes([]); /////////////////////////// HELPER FUNCTIONS //////////////////////////// // checks if caller is owner, or one of its delegated operators -function canOperate(state: sc.MutableErc721State, caller: wasmlib.ScAgentID, owner: wasmlib.ScAgentID): boolean { +function canOperate(state: sc.MutableErc721State, caller: wasmlib.ScAgentID, owner: wasmlib.ScAgentID): bool { if (caller.equals(owner)) { return true; } @@ -31,7 +32,7 @@ function canOperate(state: sc.MutableErc721State, caller: wasmlib.ScAgentID, own } // checks if caller is owner, or one of its delegated operators, or approved account for tokenID -function canTransfer(state: sc.MutableErc721State, caller: wasmlib.ScAgentID, owner: wasmlib.ScAgentID, tokenID: wasmlib.ScHash): boolean { +function canTransfer(state: sc.MutableErc721State, caller: wasmlib.ScAgentID, owner: wasmlib.ScAgentID, tokenID: wasmlib.ScHash): bool { if (canOperate(state, caller, owner)) { return true; } diff --git a/contracts/wasm/erc721/ts/erc721/events.ts b/contracts/wasm/erc721/ts/erc721/events.ts index 6407257600..dfed76da6f 100644 --- a/contracts/wasm/erc721/ts/erc721/events.ts +++ b/contracts/wasm/erc721/ts/erc721/events.ts @@ -6,45 +6,46 @@ // Change the json schema instead import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Erc721Events { - approval(approved: wasmlib.ScAgentID, owner: wasmlib.ScAgentID, tokenID: wasmlib.ScHash): void { - new wasmlib.EventEncoder("erc721.approval"). - agentID(approved). - agentID(owner). - hash(tokenID). - emit(); + approval(approved: wasmtypes.ScAgentID, owner: wasmtypes.ScAgentID, tokenID: wasmtypes.ScHash): void { + const evt = new wasmlib.EventEncoder("erc721.approval"); + evt.encode(wasmtypes.agentIDToString(approved)); + evt.encode(wasmtypes.agentIDToString(owner)); + evt.encode(wasmtypes.hashToString(tokenID)); + evt.emit(); } - approvalForAll(approval: bool, operator: wasmlib.ScAgentID, owner: wasmlib.ScAgentID): void { - new wasmlib.EventEncoder("erc721.approvalForAll"). - bool(approval). - agentID(operator). - agentID(owner). - emit(); + approvalForAll(approval: bool, operator: wasmtypes.ScAgentID, owner: wasmtypes.ScAgentID): void { + const evt = new wasmlib.EventEncoder("erc721.approvalForAll"); + evt.encode(wasmtypes.boolToString(approval)); + evt.encode(wasmtypes.agentIDToString(operator)); + evt.encode(wasmtypes.agentIDToString(owner)); + evt.emit(); } init(name: string, symbol: string): void { - new wasmlib.EventEncoder("erc721.init"). - string(name). - string(symbol). - emit(); + const evt = new wasmlib.EventEncoder("erc721.init"); + evt.encode(wasmtypes.stringToString(name)); + evt.encode(wasmtypes.stringToString(symbol)); + evt.emit(); } - mint(balance: u64, owner: wasmlib.ScAgentID, tokenID: wasmlib.ScHash): void { - new wasmlib.EventEncoder("erc721.mint"). - uint64(balance). - agentID(owner). - hash(tokenID). - emit(); + mint(balance: u64, owner: wasmtypes.ScAgentID, tokenID: wasmtypes.ScHash): void { + const evt = new wasmlib.EventEncoder("erc721.mint"); + evt.encode(wasmtypes.uint64ToString(balance)); + evt.encode(wasmtypes.agentIDToString(owner)); + evt.encode(wasmtypes.hashToString(tokenID)); + evt.emit(); } - transfer(from: wasmlib.ScAgentID, to: wasmlib.ScAgentID, tokenID: wasmlib.ScHash): void { - new wasmlib.EventEncoder("erc721.transfer"). - agentID(from). - agentID(to). - hash(tokenID). - emit(); + transfer(from: wasmtypes.ScAgentID, to: wasmtypes.ScAgentID, tokenID: wasmtypes.ScHash): void { + const evt = new wasmlib.EventEncoder("erc721.transfer"); + evt.encode(wasmtypes.agentIDToString(from)); + evt.encode(wasmtypes.agentIDToString(to)); + evt.encode(wasmtypes.hashToString(tokenID)); + evt.emit(); } } diff --git a/contracts/wasm/erc721/ts/erc721/index.ts b/contracts/wasm/erc721/ts/erc721/index.ts index 11f170837f..0e8f70153c 100644 --- a/contracts/wasm/erc721/ts/erc721/index.ts +++ b/contracts/wasm/erc721/ts/erc721/index.ts @@ -10,7 +10,6 @@ export * from "./erc721"; export * from "./consts"; export * from "./contract"; export * from "./events"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/erc721/ts/erc721/keys.ts b/contracts/wasm/erc721/ts/erc721/keys.ts deleted file mode 100644 index fc32f134a8..0000000000 --- a/contracts/wasm/erc721/ts/erc721/keys.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamApproval = 0; -export const IdxParamApproved = 1; -export const IdxParamData = 2; -export const IdxParamFrom = 3; -export const IdxParamName = 4; -export const IdxParamOperator = 5; -export const IdxParamOwner = 6; -export const IdxParamSymbol = 7; -export const IdxParamTo = 8; -export const IdxParamTokenID = 9; -export const IdxParamTokenURI = 10; - -export const IdxResultAmount = 11; -export const IdxResultApproval = 12; -export const IdxResultApproved = 13; -export const IdxResultName = 14; -export const IdxResultOwner = 15; -export const IdxResultSymbol = 16; -export const IdxResultTokenURI = 17; - -export const IdxStateApprovedAccounts = 18; -export const IdxStateApprovedOperators = 19; -export const IdxStateBalances = 20; -export const IdxStateName = 21; -export const IdxStateOwners = 22; -export const IdxStateSymbol = 23; -export const IdxStateTokenURIs = 24; - -export let keyMap: string[] = [ - sc.ParamApproval, - sc.ParamApproved, - sc.ParamData, - sc.ParamFrom, - sc.ParamName, - sc.ParamOperator, - sc.ParamOwner, - sc.ParamSymbol, - sc.ParamTo, - sc.ParamTokenID, - sc.ParamTokenURI, - sc.ResultAmount, - sc.ResultApproval, - sc.ResultApproved, - sc.ResultName, - sc.ResultOwner, - sc.ResultSymbol, - sc.ResultTokenURI, - sc.StateApprovedAccounts, - sc.StateApprovedOperators, - sc.StateBalances, - sc.StateName, - sc.StateOwners, - sc.StateSymbol, - sc.StateTokenURIs, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/erc721/ts/erc721/lib.ts b/contracts/wasm/erc721/ts/erc721/lib.ts index ba6a48b663..e23f0e2d70 100644 --- a/contracts/wasm/erc721/ts/erc721/lib.ts +++ b/contracts/wasm/erc721/ts/erc721/lib.ts @@ -8,37 +8,54 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncApprove, + sc.FuncBurn, + sc.FuncInit, + sc.FuncMint, + sc.FuncSafeTransferFrom, + sc.FuncSetApprovalForAll, + sc.FuncTransferFrom, + sc.ViewBalanceOf, + sc.ViewGetApproved, + sc.ViewIsApprovedForAll, + sc.ViewName, + sc.ViewOwnerOf, + sc.ViewSymbol, + sc.ViewTokenURI, + ], + funcs: [ + funcApproveThunk, + funcBurnThunk, + funcInitThunk, + funcMintThunk, + funcSafeTransferFromThunk, + funcSetApprovalForAllThunk, + funcTransferFromThunk, + ], + views: [ + viewBalanceOfThunk, + viewGetApprovedThunk, + viewIsApprovedForAllThunk, + viewNameThunk, + viewOwnerOfThunk, + viewSymbolThunk, + viewTokenURIThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncApprove, funcApproveThunk); - exports.addFunc(sc.FuncBurn, funcBurnThunk); - exports.addFunc(sc.FuncInit, funcInitThunk); - exports.addFunc(sc.FuncMint, funcMintThunk); - exports.addFunc(sc.FuncSafeTransferFrom, funcSafeTransferFromThunk); - exports.addFunc(sc.FuncSetApprovalForAll, funcSetApprovalForAllThunk); - exports.addFunc(sc.FuncTransferFrom, funcTransferFromThunk); - exports.addView(sc.ViewBalanceOf, viewBalanceOfThunk); - exports.addView(sc.ViewGetApproved, viewGetApprovedThunk); - exports.addView(sc.ViewIsApprovedForAll, viewIsApprovedForAllThunk); - exports.addView(sc.ViewName, viewNameThunk); - exports.addView(sc.ViewOwnerOf, viewOwnerOfThunk); - exports.addView(sc.ViewSymbol, viewSymbolThunk); - exports.addView(sc.ViewTokenURI, viewTokenURIThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcApproveThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcApprove"); let f = new sc.ApproveContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.funcApprove(ctx, f); ctx.log("erc721.funcApprove ok"); @@ -47,8 +64,6 @@ function funcApproveThunk(ctx: wasmlib.ScFuncContext): void { function funcBurnThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcBurn"); let f = new sc.BurnContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.funcBurn(ctx, f); ctx.log("erc721.funcBurn ok"); @@ -57,8 +72,6 @@ function funcBurnThunk(ctx: wasmlib.ScFuncContext): void { function funcInitThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcInit"); let f = new sc.InitContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.name().exists(), "missing mandatory name"); ctx.require(f.params.symbol().exists(), "missing mandatory symbol"); sc.funcInit(ctx, f); @@ -68,8 +81,6 @@ function funcInitThunk(ctx: wasmlib.ScFuncContext): void { function funcMintThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcMint"); let f = new sc.MintContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.funcMint(ctx, f); ctx.log("erc721.funcMint ok"); @@ -78,8 +89,6 @@ function funcMintThunk(ctx: wasmlib.ScFuncContext): void { function funcSafeTransferFromThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcSafeTransferFrom"); let f = new sc.SafeTransferFromContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.from().exists(), "missing mandatory from"); ctx.require(f.params.to().exists(), "missing mandatory to"); ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); @@ -90,8 +99,6 @@ function funcSafeTransferFromThunk(ctx: wasmlib.ScFuncContext): void { function funcSetApprovalForAllThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcSetApprovalForAll"); let f = new sc.SetApprovalForAllContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.approval().exists(), "missing mandatory approval"); ctx.require(f.params.operator().exists(), "missing mandatory operator"); sc.funcSetApprovalForAll(ctx, f); @@ -101,8 +108,6 @@ function funcSetApprovalForAllThunk(ctx: wasmlib.ScFuncContext): void { function funcTransferFromThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("erc721.funcTransferFrom"); let f = new sc.TransferFromContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.from().exists(), "missing mandatory from"); ctx.require(f.params.to().exists(), "missing mandatory to"); ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); @@ -113,73 +118,75 @@ function funcTransferFromThunk(ctx: wasmlib.ScFuncContext): void { function viewBalanceOfThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewBalanceOf"); let f = new sc.BalanceOfContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableBalanceOfResults(results.asProxy()); ctx.require(f.params.owner().exists(), "missing mandatory owner"); sc.viewBalanceOf(ctx, f); + ctx.results(results); ctx.log("erc721.viewBalanceOf ok"); } function viewGetApprovedThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewGetApproved"); let f = new sc.GetApprovedContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetApprovedResults(results.asProxy()); ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.viewGetApproved(ctx, f); + ctx.results(results); ctx.log("erc721.viewGetApproved ok"); } function viewIsApprovedForAllThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewIsApprovedForAll"); let f = new sc.IsApprovedForAllContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableIsApprovedForAllResults(results.asProxy()); ctx.require(f.params.operator().exists(), "missing mandatory operator"); ctx.require(f.params.owner().exists(), "missing mandatory owner"); sc.viewIsApprovedForAll(ctx, f); + ctx.results(results); ctx.log("erc721.viewIsApprovedForAll ok"); } function viewNameThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewName"); let f = new sc.NameContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableNameResults(results.asProxy()); sc.viewName(ctx, f); + ctx.results(results); ctx.log("erc721.viewName ok"); } function viewOwnerOfThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewOwnerOf"); let f = new sc.OwnerOfContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableOwnerOfResults(results.asProxy()); ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.viewOwnerOf(ctx, f); + ctx.results(results); ctx.log("erc721.viewOwnerOf ok"); } function viewSymbolThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewSymbol"); let f = new sc.SymbolContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableSymbolResults(results.asProxy()); sc.viewSymbol(ctx, f); + ctx.results(results); ctx.log("erc721.viewSymbol ok"); } function viewTokenURIThunk(ctx: wasmlib.ScViewContext): void { ctx.log("erc721.viewTokenURI"); let f = new sc.TokenURIContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableTokenURIResults(results.asProxy()); ctx.require(f.params.tokenID().exists(), "missing mandatory tokenID"); sc.viewTokenURI(ctx, f); + ctx.results(results); ctx.log("erc721.viewTokenURI ok"); } diff --git a/contracts/wasm/erc721/ts/erc721/params.ts b/contracts/wasm/erc721/ts/erc721/params.ts index 509be4795f..08b4d903c6 100644 --- a/contracts/wasm/erc721/ts/erc721/params.ts +++ b/contracts/wasm/erc721/ts/erc721/params.ts @@ -5,229 +5,229 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableApproveParams extends wasmlib.ScMapID { - approved(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamApproved)); +export class ImmutableApproveParams extends wasmtypes.ScProxy { + approved(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamApproved)); } - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableApproveParams extends wasmlib.ScMapID { - approved(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamApproved)); +export class MutableApproveParams extends wasmtypes.ScProxy { + approved(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamApproved)); } - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableBurnParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class ImmutableBurnParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableBurnParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class MutableBurnParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableInitParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, sc.idxMap[sc.IdxParamName]); +export class ImmutableInitParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } - symbol(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, sc.idxMap[sc.IdxParamSymbol]); + symbol(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamSymbol)); } } -export class MutableInitParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, sc.idxMap[sc.IdxParamName]); +export class MutableInitParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } - symbol(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, sc.idxMap[sc.IdxParamSymbol]); + symbol(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamSymbol)); } } -export class ImmutableMintParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class ImmutableMintParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } - tokenURI(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenURI)); + tokenURI(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamTokenURI)); } } -export class MutableMintParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class MutableMintParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } - tokenURI(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenURI)); + tokenURI(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamTokenURI)); } } -export class ImmutableSafeTransferFromParams extends wasmlib.ScMapID { - data(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ParamData)); +export class ImmutableSafeTransferFromParams extends wasmtypes.ScProxy { + data(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ParamData)); } - from(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamFrom)); + from(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamFrom)); } - to(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamTo)); + to(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamTo)); } - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableSafeTransferFromParams extends wasmlib.ScMapID { - data(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ParamData)); +export class MutableSafeTransferFromParams extends wasmtypes.ScProxy { + data(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ParamData)); } - from(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamFrom)); + from(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamFrom)); } - to(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamTo)); + to(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamTo)); } - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableSetApprovalForAllParams extends wasmlib.ScMapID { - approval(): wasmlib.ScImmutableBool { - return new wasmlib.ScImmutableBool(this.mapID, wasmlib.Key32.fromString(sc.ParamApproval)); +export class ImmutableSetApprovalForAllParams extends wasmtypes.ScProxy { + approval(): wasmtypes.ScImmutableBool { + return new wasmtypes.ScImmutableBool(this.proxy.root(sc.ParamApproval)); } - operator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOperator)); + operator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOperator)); } } -export class MutableSetApprovalForAllParams extends wasmlib.ScMapID { - approval(): wasmlib.ScMutableBool { - return new wasmlib.ScMutableBool(this.mapID, wasmlib.Key32.fromString(sc.ParamApproval)); +export class MutableSetApprovalForAllParams extends wasmtypes.ScProxy { + approval(): wasmtypes.ScMutableBool { + return new wasmtypes.ScMutableBool(this.proxy.root(sc.ParamApproval)); } - operator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOperator)); + operator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOperator)); } } -export class ImmutableTransferFromParams extends wasmlib.ScMapID { - from(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamFrom)); +export class ImmutableTransferFromParams extends wasmtypes.ScProxy { + from(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamFrom)); } - to(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamTo)); + to(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamTo)); } - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableTransferFromParams extends wasmlib.ScMapID { - from(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamFrom)); +export class MutableTransferFromParams extends wasmtypes.ScProxy { + from(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamFrom)); } - to(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamTo)); + to(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamTo)); } - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableBalanceOfParams extends wasmlib.ScMapID { - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); +export class ImmutableBalanceOfParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class MutableBalanceOfParams extends wasmlib.ScMapID { - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); +export class MutableBalanceOfParams extends wasmtypes.ScProxy { + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class ImmutableGetApprovedParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class ImmutableGetApprovedParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableGetApprovedParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class MutableGetApprovedParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableIsApprovedForAllParams extends wasmlib.ScMapID { - operator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOperator)); +export class ImmutableIsApprovedForAllParams extends wasmtypes.ScProxy { + operator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOperator)); } - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class MutableIsApprovedForAllParams extends wasmlib.ScMapID { - operator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOperator)); +export class MutableIsApprovedForAllParams extends wasmtypes.ScProxy { + operator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOperator)); } - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamOwner)); + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamOwner)); } } -export class ImmutableOwnerOfParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class ImmutableOwnerOfParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableOwnerOfParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class MutableOwnerOfParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class ImmutableTokenURIParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class ImmutableTokenURIParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamTokenID)); } } -export class MutableTokenURIParams extends wasmlib.ScMapID { - tokenID(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamTokenID)); +export class MutableTokenURIParams extends wasmtypes.ScProxy { + tokenID(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamTokenID)); } } diff --git a/contracts/wasm/erc721/ts/erc721/results.ts b/contracts/wasm/erc721/ts/erc721/results.ts index 30edca4097..6a8c25761c 100644 --- a/contracts/wasm/erc721/ts/erc721/results.ts +++ b/contracts/wasm/erc721/ts/erc721/results.ts @@ -5,89 +5,89 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableBalanceOfResults extends wasmlib.ScMapID { - amount(): wasmlib.ScImmutableUint64 { - return new wasmlib.ScImmutableUint64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class ImmutableBalanceOfResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class MutableBalanceOfResults extends wasmlib.ScMapID { - amount(): wasmlib.ScMutableUint64 { - return new wasmlib.ScMutableUint64(this.mapID, wasmlib.Key32.fromString(sc.ResultAmount)); +export class MutableBalanceOfResults extends wasmtypes.ScProxy { + amount(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultAmount)); } } -export class ImmutableGetApprovedResults extends wasmlib.ScMapID { - approved(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultApproved)); +export class ImmutableGetApprovedResults extends wasmtypes.ScProxy { + approved(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultApproved)); } } -export class MutableGetApprovedResults extends wasmlib.ScMapID { - approved(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultApproved)); +export class MutableGetApprovedResults extends wasmtypes.ScProxy { + approved(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultApproved)); } } -export class ImmutableIsApprovedForAllResults extends wasmlib.ScMapID { - approval(): wasmlib.ScImmutableBool { - return new wasmlib.ScImmutableBool(this.mapID, wasmlib.Key32.fromString(sc.ResultApproval)); +export class ImmutableIsApprovedForAllResults extends wasmtypes.ScProxy { + approval(): wasmtypes.ScImmutableBool { + return new wasmtypes.ScImmutableBool(this.proxy.root(sc.ResultApproval)); } } -export class MutableIsApprovedForAllResults extends wasmlib.ScMapID { - approval(): wasmlib.ScMutableBool { - return new wasmlib.ScMutableBool(this.mapID, wasmlib.Key32.fromString(sc.ResultApproval)); +export class MutableIsApprovedForAllResults extends wasmtypes.ScProxy { + approval(): wasmtypes.ScMutableBool { + return new wasmtypes.ScMutableBool(this.proxy.root(sc.ResultApproval)); } } -export class ImmutableNameResults extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultName)); +export class ImmutableNameResults extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultName)); } } -export class MutableNameResults extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultName)); +export class MutableNameResults extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultName)); } } -export class ImmutableOwnerOfResults extends wasmlib.ScMapID { - owner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultOwner)); +export class ImmutableOwnerOfResults extends wasmtypes.ScProxy { + owner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultOwner)); } } -export class MutableOwnerOfResults extends wasmlib.ScMapID { - owner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultOwner)); +export class MutableOwnerOfResults extends wasmtypes.ScProxy { + owner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultOwner)); } } -export class ImmutableSymbolResults extends wasmlib.ScMapID { - symbol(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultSymbol)); +export class ImmutableSymbolResults extends wasmtypes.ScProxy { + symbol(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultSymbol)); } } -export class MutableSymbolResults extends wasmlib.ScMapID { - symbol(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultSymbol)); +export class MutableSymbolResults extends wasmtypes.ScProxy { + symbol(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultSymbol)); } } -export class ImmutableTokenURIResults extends wasmlib.ScMapID { - tokenURI(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultTokenURI)); +export class ImmutableTokenURIResults extends wasmtypes.ScProxy { + tokenURI(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultTokenURI)); } } -export class MutableTokenURIResults extends wasmlib.ScMapID { - tokenURI(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultTokenURI)); +export class MutableTokenURIResults extends wasmtypes.ScProxy { + tokenURI(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultTokenURI)); } } diff --git a/contracts/wasm/erc721/ts/erc721/state.ts b/contracts/wasm/erc721/ts/erc721/state.ts index b16ed14851..0c5467f9d3 100644 --- a/contracts/wasm/erc721/ts/erc721/state.ts +++ b/contracts/wasm/erc721/ts/erc721/state.ts @@ -5,195 +5,141 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapHashToImmutableAgentID { - objID: i32; +export class MapHashToImmutableAgentID extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getAgentID(key: wasmlib.ScHash): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.objID, key.getKeyID()); - } + getAgentID(key: wasmtypes.ScHash): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.key(wasmtypes.hashToBytes(key))); + } } -export class MapAgentIDToImmutableOperators { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToImmutableOperators extends wasmtypes.ScProxy { - getOperators(key: wasmlib.ScAgentID): sc.ImmutableOperators { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.ImmutableOperators(subID); - } + getOperators(key: wasmtypes.ScAgentID): sc.ImmutableOperators { + return new sc.ImmutableOperators(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MapAgentIDToImmutableUint64 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToImmutableUint64 extends wasmtypes.ScProxy { - getUint64(key: wasmlib.ScAgentID): wasmlib.ScImmutableUint64 { - return new wasmlib.ScImmutableUint64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAgentID): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MapHashToImmutableString { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapHashToImmutableString extends wasmtypes.ScProxy { - getString(key: wasmlib.ScHash): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.objID, key.getKeyID()); - } + getString(key: wasmtypes.ScHash): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.key(wasmtypes.hashToBytes(key))); + } } -export class ImmutableErc721State extends wasmlib.ScMapID { - approvedAccounts(): sc.MapHashToImmutableAgentID { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateApprovedAccounts), wasmlib.TYPE_MAP); - return new sc.MapHashToImmutableAgentID(mapID); +export class ImmutableErc721State extends wasmtypes.ScProxy { + approvedAccounts(): sc.MapHashToImmutableAgentID { + return new sc.MapHashToImmutableAgentID(this.proxy.root(sc.StateApprovedAccounts)); } - approvedOperators(): sc.MapAgentIDToImmutableOperators { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateApprovedOperators), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToImmutableOperators(mapID); + approvedOperators(): sc.MapAgentIDToImmutableOperators { + return new sc.MapAgentIDToImmutableOperators(this.proxy.root(sc.StateApprovedOperators)); } - balances(): sc.MapAgentIDToImmutableUint64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBalances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToImmutableUint64(mapID); + balances(): sc.MapAgentIDToImmutableUint64 { + return new sc.MapAgentIDToImmutableUint64(this.proxy.root(sc.StateBalances)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.StateName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.StateName)); } - owners(): sc.MapHashToImmutableAgentID { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateOwners), wasmlib.TYPE_MAP); - return new sc.MapHashToImmutableAgentID(mapID); + owners(): sc.MapHashToImmutableAgentID { + return new sc.MapHashToImmutableAgentID(this.proxy.root(sc.StateOwners)); } - symbol(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.StateSymbol)); + symbol(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.StateSymbol)); } - tokenURIs(): sc.MapHashToImmutableString { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateTokenURIs), wasmlib.TYPE_MAP); - return new sc.MapHashToImmutableString(mapID); + tokenURIs(): sc.MapHashToImmutableString { + return new sc.MapHashToImmutableString(this.proxy.root(sc.StateTokenURIs)); } } -export class MapHashToMutableAgentID { - objID: i32; +export class MapHashToMutableAgentID extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getAgentID(key: wasmlib.ScHash): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.objID, key.getKeyID()); - } + getAgentID(key: wasmtypes.ScHash): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.key(wasmtypes.hashToBytes(key))); + } } -export class MapAgentIDToMutableOperators { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableOperators extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getOperators(key: wasmlib.ScAgentID): sc.MutableOperators { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.MutableOperators(subID); - } + getOperators(key: wasmtypes.ScAgentID): sc.MutableOperators { + return new sc.MutableOperators(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MapAgentIDToMutableUint64 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableUint64 extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getUint64(key: wasmlib.ScAgentID): wasmlib.ScMutableUint64 { - return new wasmlib.ScMutableUint64(this.objID, key.getKeyID()); - } + getUint64(key: wasmtypes.ScAgentID): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } -export class MapHashToMutableString { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapHashToMutableString extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getString(key: wasmlib.ScHash): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.objID, key.getKeyID()); - } + getString(key: wasmtypes.ScHash): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.key(wasmtypes.hashToBytes(key))); + } } -export class MutableErc721State extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableErc721State { - const imm = new sc.ImmutableErc721State(); - imm.mapID = this.mapID; - return imm; +export class MutableErc721State extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableErc721State { + return new sc.ImmutableErc721State(this.proxy); } - approvedAccounts(): sc.MapHashToMutableAgentID { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateApprovedAccounts), wasmlib.TYPE_MAP); - return new sc.MapHashToMutableAgentID(mapID); + approvedAccounts(): sc.MapHashToMutableAgentID { + return new sc.MapHashToMutableAgentID(this.proxy.root(sc.StateApprovedAccounts)); } - approvedOperators(): sc.MapAgentIDToMutableOperators { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateApprovedOperators), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToMutableOperators(mapID); + approvedOperators(): sc.MapAgentIDToMutableOperators { + return new sc.MapAgentIDToMutableOperators(this.proxy.root(sc.StateApprovedOperators)); } - balances(): sc.MapAgentIDToMutableUint64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBalances), wasmlib.TYPE_MAP); - return new sc.MapAgentIDToMutableUint64(mapID); + balances(): sc.MapAgentIDToMutableUint64 { + return new sc.MapAgentIDToMutableUint64(this.proxy.root(sc.StateBalances)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.StateName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.StateName)); } - owners(): sc.MapHashToMutableAgentID { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateOwners), wasmlib.TYPE_MAP); - return new sc.MapHashToMutableAgentID(mapID); + owners(): sc.MapHashToMutableAgentID { + return new sc.MapHashToMutableAgentID(this.proxy.root(sc.StateOwners)); } - symbol(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.StateSymbol)); + symbol(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.StateSymbol)); } - tokenURIs(): sc.MapHashToMutableString { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateTokenURIs), wasmlib.TYPE_MAP); - return new sc.MapHashToMutableString(mapID); + tokenURIs(): sc.MapHashToMutableString { + return new sc.MapHashToMutableString(this.proxy.root(sc.StateTokenURIs)); } } diff --git a/contracts/wasm/erc721/ts/erc721/typedefs.ts b/contracts/wasm/erc721/ts/erc721/typedefs.ts index a058931ce3..389d9007f7 100644 --- a/contracts/wasm/erc721/ts/erc721/typedefs.ts +++ b/contracts/wasm/erc721/ts/erc721/typedefs.ts @@ -5,39 +5,29 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapAgentIDToImmutableBool { - objID: i32; +export class MapAgentIDToImmutableBool extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getBool(key: wasmlib.ScAgentID): wasmlib.ScImmutableBool { - return new wasmlib.ScImmutableBool(this.objID, key.getKeyID()); - } + getBool(key: wasmtypes.ScAgentID): wasmtypes.ScImmutableBool { + return new wasmtypes.ScImmutableBool(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } export class ImmutableOperators extends MapAgentIDToImmutableBool { -}; - -export class MapAgentIDToMutableBool { - objID: i32; +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableBool extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getBool(key: wasmlib.ScAgentID): wasmlib.ScMutableBool { - return new wasmlib.ScMutableBool(this.objID, key.getKeyID()); - } + getBool(key: wasmtypes.ScAgentID): wasmtypes.ScMutableBool { + return new wasmtypes.ScMutableBool(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } export class MutableOperators extends MapAgentIDToMutableBool { -}; +} diff --git a/contracts/wasm/erc721/ts/erc721client/events.ts b/contracts/wasm/erc721/ts/erc721client/events.ts new file mode 100644 index 0000000000..7da84f52ec --- /dev/null +++ b/contracts/wasm/erc721/ts/erc721client/events.ts @@ -0,0 +1,116 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmclient from "wasmclient" + +const erc721Handlers = new Map void>([ + ["erc721.approval", (evt: Erc721Events, msg: string[]) => evt.approval(new EventApproval(msg))], + ["erc721.approvalForAll", (evt: Erc721Events, msg: string[]) => evt.approvalForAll(new EventApprovalForAll(msg))], + ["erc721.init", (evt: Erc721Events, msg: string[]) => evt.init(new EventInit(msg))], + ["erc721.mint", (evt: Erc721Events, msg: string[]) => evt.mint(new EventMint(msg))], + ["erc721.transfer", (evt: Erc721Events, msg: string[]) => evt.transfer(new EventTransfer(msg))], +]); + +export class Erc721Events implements wasmclient.IEventHandler { +/* eslint-disable @typescript-eslint/no-empty-function */ + approval: (evt: EventApproval) => void = () => {}; + approvalForAll: (evt: EventApprovalForAll) => void = () => {}; + init: (evt: EventInit) => void = () => {}; + mint: (evt: EventMint) => void = () => {}; + transfer: (evt: EventTransfer) => void = () => {}; +/* eslint-enable @typescript-eslint/no-empty-function */ + + public callHandler(topic: string, params: string[]): void { + const handler = erc721Handlers.get(topic); + if (handler) { + handler(this, params); + } + } + + public onErc721Approval(handler: (evt: EventApproval) => void): void { + this.approval = handler; + } + + public onErc721ApprovalForAll(handler: (evt: EventApprovalForAll) => void): void { + this.approvalForAll = handler; + } + + public onErc721Init(handler: (evt: EventInit) => void): void { + this.init = handler; + } + + public onErc721Mint(handler: (evt: EventMint) => void): void { + this.mint = handler; + } + + public onErc721Transfer(handler: (evt: EventTransfer) => void): void { + this.transfer = handler; + } +} + +export class EventApproval extends wasmclient.Event { + public readonly approved: wasmclient.AgentID; + public readonly owner: wasmclient.AgentID; + public readonly tokenID: wasmclient.Hash; + + public constructor(msg: string[]) { + super(msg); + this.approved = this.nextAgentID(); + this.owner = this.nextAgentID(); + this.tokenID = this.nextHash(); + } +} + +export class EventApprovalForAll extends wasmclient.Event { + public readonly approval: wasmclient.Bool; + public readonly operator: wasmclient.AgentID; + public readonly owner: wasmclient.AgentID; + + public constructor(msg: string[]) { + super(msg); + this.approval = this.nextBool(); + this.operator = this.nextAgentID(); + this.owner = this.nextAgentID(); + } +} + +export class EventInit extends wasmclient.Event { + public readonly name: wasmclient.String; + public readonly symbol: wasmclient.String; + + public constructor(msg: string[]) { + super(msg); + this.name = this.nextString(); + this.symbol = this.nextString(); + } +} + +export class EventMint extends wasmclient.Event { + public readonly balance: wasmclient.Uint64; + public readonly owner: wasmclient.AgentID; + public readonly tokenID: wasmclient.Hash; + + public constructor(msg: string[]) { + super(msg); + this.balance = this.nextUint64(); + this.owner = this.nextAgentID(); + this.tokenID = this.nextHash(); + } +} + +export class EventTransfer extends wasmclient.Event { + public readonly from: wasmclient.AgentID; + public readonly to: wasmclient.AgentID; + public readonly tokenID: wasmclient.Hash; + + public constructor(msg: string[]) { + super(msg); + this.from = this.nextAgentID(); + this.to = this.nextAgentID(); + this.tokenID = this.nextHash(); + } +} diff --git a/contracts/wasm/erc721/ts/erc721client/index.ts b/contracts/wasm/erc721/ts/erc721client/index.ts new file mode 100644 index 0000000000..1c2d312bca --- /dev/null +++ b/contracts/wasm/erc721/ts/erc721client/index.ts @@ -0,0 +1,9 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +export * from "./events"; +export * from "./service"; diff --git a/contracts/wasm/erc721/ts/erc721client/service.ts b/contracts/wasm/erc721/ts/erc721client/service.ts new file mode 100644 index 0000000000..6d9d89a3f4 --- /dev/null +++ b/contracts/wasm/erc721/ts/erc721client/service.ts @@ -0,0 +1,426 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmclient from "wasmclient" +import * as events from "./events" + +const ArgApproval = "approval"; +const ArgApproved = "approved"; +const ArgData = "data"; +const ArgFrom = "from"; +const ArgName = "n"; +const ArgOperator = "operator"; +const ArgOwner = "owner"; +const ArgSymbol = "s"; +const ArgTo = "to"; +const ArgTokenID = "tokenID"; +const ArgTokenURI = "tokenURI"; + +const ResAmount = "amount"; +const ResApproval = "approval"; +const ResApproved = "approved"; +const ResName = "name"; +const ResOwner = "owner"; +const ResSymbol = "symbol"; +const ResTokenURI = "tokenURI"; + +///////////////////////////// approve ///////////////////////////// + +export class ApproveFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public approved(v: wasmclient.AgentID): void { + this.args.set(ArgApproved, this.args.fromAgentID(v)); + } + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgTokenID); + return await super.post(0xa0661268, this.args); + } +} + +///////////////////////////// burn ///////////////////////////// + +export class BurnFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgTokenID); + return await super.post(0x7bc1efb1, this.args); + } +} + +///////////////////////////// init ///////////////////////////// + +export class InitFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public name(v: string): void { + this.args.set(ArgName, this.args.fromString(v)); + } + + public symbol(v: string): void { + this.args.set(ArgSymbol, this.args.fromString(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgName); + this.args.mandatory(ArgSymbol); + return await super.post(0x1f44d644, this.args); + } +} + +///////////////////////////// mint ///////////////////////////// + +export class MintFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public tokenURI(v: string): void { + this.args.set(ArgTokenURI, this.args.fromString(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgTokenID); + return await super.post(0xa29addcf, this.args); + } +} + +///////////////////////////// safeTransferFrom ///////////////////////////// + +export class SafeTransferFromFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public data(v: wasmclient.Bytes): void { + this.args.set(ArgData, this.args.fromBytes(v)); + } + + public from(v: wasmclient.AgentID): void { + this.args.set(ArgFrom, this.args.fromAgentID(v)); + } + + public to(v: wasmclient.AgentID): void { + this.args.set(ArgTo, this.args.fromAgentID(v)); + } + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgFrom); + this.args.mandatory(ArgTo); + this.args.mandatory(ArgTokenID); + return await super.post(0x130ce158, this.args); + } +} + +///////////////////////////// setApprovalForAll ///////////////////////////// + +export class SetApprovalForAllFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public approval(v: boolean): void { + this.args.set(ArgApproval, this.args.fromBool(v)); + } + + public operator(v: wasmclient.AgentID): void { + this.args.set(ArgOperator, this.args.fromAgentID(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgApproval); + this.args.mandatory(ArgOperator); + return await super.post(0xb8d8c776, this.args); + } +} + +///////////////////////////// transferFrom ///////////////////////////// + +export class TransferFromFunc extends wasmclient.ClientFunc { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public from(v: wasmclient.AgentID): void { + this.args.set(ArgFrom, this.args.fromAgentID(v)); + } + + public to(v: wasmclient.AgentID): void { + this.args.set(ArgTo, this.args.fromAgentID(v)); + } + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async post(): Promise { + this.args.mandatory(ArgFrom); + this.args.mandatory(ArgTo); + this.args.mandatory(ArgTokenID); + return await super.post(0xd5e0a602, this.args); + } +} + +///////////////////////////// balanceOf ///////////////////////////// + +export class BalanceOfView extends wasmclient.ClientView { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public owner(v: wasmclient.AgentID): void { + this.args.set(ArgOwner, this.args.fromAgentID(v)); + } + + public async call(): Promise { + this.args.mandatory(ArgOwner); + const res = new BalanceOfResults(); + await this.callView("balanceOf", this.args, res); + return res; + } +} + +export class BalanceOfResults extends wasmclient.Results { + + amountExists(): boolean { + return this.exists(ResAmount) + } + + amount(): wasmclient.Uint64 { + return this.toUint64(this.get(ResAmount)); + } +} + +///////////////////////////// getApproved ///////////////////////////// + +export class GetApprovedView extends wasmclient.ClientView { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async call(): Promise { + this.args.mandatory(ArgTokenID); + const res = new GetApprovedResults(); + await this.callView("getApproved", this.args, res); + return res; + } +} + +export class GetApprovedResults extends wasmclient.Results { + + approvedExists(): boolean { + return this.exists(ResApproved) + } + + approved(): wasmclient.AgentID { + return this.toAgentID(this.get(ResApproved)); + } +} + +///////////////////////////// isApprovedForAll ///////////////////////////// + +export class IsApprovedForAllView extends wasmclient.ClientView { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public operator(v: wasmclient.AgentID): void { + this.args.set(ArgOperator, this.args.fromAgentID(v)); + } + + public owner(v: wasmclient.AgentID): void { + this.args.set(ArgOwner, this.args.fromAgentID(v)); + } + + public async call(): Promise { + this.args.mandatory(ArgOperator); + this.args.mandatory(ArgOwner); + const res = new IsApprovedForAllResults(); + await this.callView("isApprovedForAll", this.args, res); + return res; + } +} + +export class IsApprovedForAllResults extends wasmclient.Results { + + approvalExists(): boolean { + return this.exists(ResApproval) + } + + approval(): boolean { + return this.toBool(this.get(ResApproval)); + } +} + +///////////////////////////// name ///////////////////////////// + +export class NameView extends wasmclient.ClientView { + + public async call(): Promise { + const res = new NameResults(); + await this.callView("name", null, res); + return res; + } +} + +export class NameResults extends wasmclient.Results { + + name(): string { + return this.toString(this.get(ResName)); + } +} + +///////////////////////////// ownerOf ///////////////////////////// + +export class OwnerOfView extends wasmclient.ClientView { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async call(): Promise { + this.args.mandatory(ArgTokenID); + const res = new OwnerOfResults(); + await this.callView("ownerOf", this.args, res); + return res; + } +} + +export class OwnerOfResults extends wasmclient.Results { + + ownerExists(): boolean { + return this.exists(ResOwner) + } + + owner(): wasmclient.AgentID { + return this.toAgentID(this.get(ResOwner)); + } +} + +///////////////////////////// symbol ///////////////////////////// + +export class SymbolView extends wasmclient.ClientView { + + public async call(): Promise { + const res = new SymbolResults(); + await this.callView("symbol", null, res); + return res; + } +} + +export class SymbolResults extends wasmclient.Results { + + symbol(): string { + return this.toString(this.get(ResSymbol)); + } +} + +///////////////////////////// tokenURI ///////////////////////////// + +export class TokenURIView extends wasmclient.ClientView { + private args: wasmclient.Arguments = new wasmclient.Arguments(); + + public tokenID(v: wasmclient.Hash): void { + this.args.set(ArgTokenID, this.args.fromHash(v)); + } + + public async call(): Promise { + this.args.mandatory(ArgTokenID); + const res = new TokenURIResults(); + await this.callView("tokenURI", this.args, res); + return res; + } +} + +export class TokenURIResults extends wasmclient.Results { + + tokenURIExists(): boolean { + return this.exists(ResTokenURI) + } + + tokenURI(): string { + return this.toString(this.get(ResTokenURI)); + } +} + +///////////////////////////// Erc721Service ///////////////////////////// + +export class Erc721Service extends wasmclient.Service { + + public constructor(cl: wasmclient.ServiceClient) { + super(cl, 0xd967c216); + } + + public newEventHandler(): events.Erc721Events { + return new events.Erc721Events(); + } + + public approve(): ApproveFunc { + return new ApproveFunc(this); + } + + public burn(): BurnFunc { + return new BurnFunc(this); + } + + public init(): InitFunc { + return new InitFunc(this); + } + + public mint(): MintFunc { + return new MintFunc(this); + } + + public safeTransferFrom(): SafeTransferFromFunc { + return new SafeTransferFromFunc(this); + } + + public setApprovalForAll(): SetApprovalForAllFunc { + return new SetApprovalForAllFunc(this); + } + + public transferFrom(): TransferFromFunc { + return new TransferFromFunc(this); + } + + public balanceOf(): BalanceOfView { + return new BalanceOfView(this); + } + + public getApproved(): GetApprovedView { + return new GetApprovedView(this); + } + + public isApprovedForAll(): IsApprovedForAllView { + return new IsApprovedForAllView(this); + } + + public name(): NameView { + return new NameView(this); + } + + public ownerOf(): OwnerOfView { + return new OwnerOfView(this); + } + + public symbol(): SymbolView { + return new SymbolView(this); + } + + public tokenURI(): TokenURIView { + return new TokenURIView(this); + } +} diff --git a/contracts/wasm/erc721/ts/erc721client/tsconfig.json b/contracts/wasm/erc721/ts/erc721client/tsconfig.json new file mode 100644 index 0000000000..bc17186726 --- /dev/null +++ b/contracts/wasm/erc721/ts/erc721client/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es2020"], + "target": "es2020", + "sourceMap": true + }, + "exclude": [ + "node_modules" + ], +} diff --git a/contracts/wasm/fairauction/Cargo.toml b/contracts/wasm/fairauction/Cargo.toml index b9fd6aa045..4061ecf84a 100644 --- a/contracts/wasm/fairauction/Cargo.toml +++ b/contracts/wasm/fairauction/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/fairauction/go/fairauction/consts.go b/contracts/wasm/fairauction/go/fairauction/consts.go index a64184d793..f90609bbed 100644 --- a/contracts/wasm/fairauction/go/fairauction/consts.go +++ b/contracts/wasm/fairauction/go/fairauction/consts.go @@ -7,12 +7,12 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "fairauction" ScDescription = "Decentralized auction to securely sell tokens to the highest bidder" - HScName = wasmlib.ScHname(0x1b5c43b1) + HScName = wasmtypes.ScHname(0x1b5c43b1) ) const ( @@ -54,9 +54,9 @@ const ( ) const ( - HFuncFinalizeAuction = wasmlib.ScHname(0x8d534ddc) - HFuncPlaceBid = wasmlib.ScHname(0x9bd72fa9) - HFuncSetOwnerMargin = wasmlib.ScHname(0x1774461a) - HFuncStartAuction = wasmlib.ScHname(0xd5b7bacb) - HViewGetInfo = wasmlib.ScHname(0xcfedba5f) + HFuncFinalizeAuction = wasmtypes.ScHname(0x8d534ddc) + HFuncPlaceBid = wasmtypes.ScHname(0x9bd72fa9) + HFuncSetOwnerMargin = wasmtypes.ScHname(0x1774461a) + HFuncStartAuction = wasmtypes.ScHname(0xd5b7bacb) + HViewGetInfo = wasmtypes.ScHname(0xcfedba5f) ) diff --git a/contracts/wasm/fairauction/go/fairauction/contract.go b/contracts/wasm/fairauction/go/fairauction/contract.go index 2d5922d91b..28d874db4b 100644 --- a/contracts/wasm/fairauction/go/fairauction/contract.go +++ b/contracts/wasm/fairauction/go/fairauction/contract.go @@ -7,7 +7,7 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type FinalizeAuctionCall struct { Func *wasmlib.ScFunc @@ -41,30 +41,31 @@ var ScFuncs Funcs func (sc Funcs) FinalizeAuction(ctx wasmlib.ScFuncCallContext) *FinalizeAuctionCall { f := &FinalizeAuctionCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncFinalizeAuction)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) PlaceBid(ctx wasmlib.ScFuncCallContext) *PlaceBidCall { f := &PlaceBidCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncPlaceBid)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetOwnerMargin(ctx wasmlib.ScFuncCallContext) *SetOwnerMarginCall { f := &SetOwnerMarginCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetOwnerMargin)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) StartAuction(ctx wasmlib.ScFuncCallContext) *StartAuctionCall { f := &StartAuctionCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncStartAuction)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GetInfo(ctx wasmlib.ScViewCallContext) *GetInfoCall { f := &GetInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetInfo)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/fairauction/go/fairauction/fairauction.go b/contracts/wasm/fairauction/go/fairauction/fairauction.go index c987fcc0a0..9f11e5494c 100644 --- a/contracts/wasm/fairauction/go/fairauction/fairauction.go +++ b/contracts/wasm/fairauction/go/fairauction/fairauction.go @@ -4,7 +4,8 @@ package fairauction import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) const ( @@ -22,16 +23,16 @@ func funcFinalizeAuction(ctx wasmlib.ScFuncContext, f *FinalizeAuctionContext) { currentAuction := f.State.Auctions().GetAuction(color) ctx.Require(currentAuction.Exists(), "Missing auction info") auction := currentAuction.Value() - if auction.HighestBid < 0 { + if auction.HighestBid == 0 { ctx.Log("No one bid on " + color.String()) ownerFee := auction.MinimumBid * auction.OwnerMargin / 1000 if ownerFee == 0 { ownerFee = 1 } // finalizeAuction request token was probably not confirmed yet - transferTokens(ctx, ctx.ContractCreator(), wasmlib.IOTA, ownerFee-1) + transferTokens(ctx, ctx.ContractCreator(), wasmtypes.IOTA, ownerFee-1) transferTokens(ctx, auction.Creator, auction.Color, auction.NumTokens) - transferTokens(ctx, auction.Creator, wasmlib.IOTA, auction.Deposit-ownerFee) + transferTokens(ctx, auction.Creator, wasmtypes.IOTA, auction.Deposit-ownerFee) return } @@ -44,22 +45,22 @@ func funcFinalizeAuction(ctx wasmlib.ScFuncContext, f *FinalizeAuctionContext) { bids := f.State.Bids().GetBids(color) bidderList := f.State.BidderList().GetBidderList(color) size := bidderList.Length() - for i := int32(0); i < size; i++ { + for i := uint32(0); i < size; i++ { loser := bidderList.GetAgentID(i).Value() if loser != auction.HighestBidder { bid := bids.GetBid(loser).Value() - transferTokens(ctx, loser, wasmlib.IOTA, bid.Amount) + transferTokens(ctx, loser, wasmtypes.IOTA, bid.Amount) } } // finalizeAuction request token was probably not confirmed yet - transferTokens(ctx, ctx.ContractCreator(), wasmlib.IOTA, ownerFee-1) + transferTokens(ctx, ctx.ContractCreator(), wasmtypes.IOTA, ownerFee-1) transferTokens(ctx, auction.HighestBidder, auction.Color, auction.NumTokens) - transferTokens(ctx, auction.Creator, wasmlib.IOTA, auction.Deposit+auction.HighestBid-ownerFee) + transferTokens(ctx, auction.Creator, wasmtypes.IOTA, auction.Deposit+auction.HighestBid-ownerFee) } func funcPlaceBid(ctx wasmlib.ScFuncContext, f *PlaceBidContext) { - bidAmount := ctx.Incoming().Balance(wasmlib.IOTA) + bidAmount := ctx.Incoming().Balance(wasmtypes.IOTA) ctx.Require(bidAmount > 0, "Missing bid amount") color := f.Params.Color().Value() @@ -82,7 +83,7 @@ func funcPlaceBid(ctx wasmlib.ScFuncContext, f *PlaceBidContext) { ctx.Require(bidAmount >= auction.MinimumBid, "Insufficient bid amount") ctx.Log("New bid from: " + caller.String()) index := bidderList.Length() - bidderList.GetAgentID(index).SetValue(caller) + bidderList.AppendAgentID().SetValue(caller) bid := &Bid{ Index: index, Amount: bidAmount, @@ -111,7 +112,7 @@ func funcSetOwnerMargin(ctx wasmlib.ScFuncContext, f *SetOwnerMarginContext) { func funcStartAuction(ctx wasmlib.ScFuncContext, f *StartAuctionContext) { color := f.Params.Color().Value() - if color == wasmlib.IOTA || color == wasmlib.MINT { + if color == wasmtypes.IOTA || color == wasmtypes.MINT { ctx.Panic("Reserved auction token color") } numTokens := ctx.Incoming().Balance(color) @@ -152,7 +153,7 @@ func funcStartAuction(ctx wasmlib.ScFuncContext, f *StartAuctionContext) { if margin == 0 { margin = 1 } - deposit := ctx.Incoming().Balance(wasmlib.IOTA) + deposit := ctx.Incoming().Balance(wasmtypes.IOTA) if deposit < margin { ctx.Panic("Insufficient deposit") } @@ -168,8 +169,8 @@ func funcStartAuction(ctx wasmlib.ScFuncContext, f *StartAuctionContext) { Deposit: deposit, Description: description, Duration: duration, - HighestBid: -1, - HighestBidder: wasmlib.ScAgentID{}, + HighestBid: 0, + HighestBidder: wasmtypes.ScAgentID{}, MinimumBid: minimumBid, NumTokens: numTokens, OwnerMargin: ownerMargin, @@ -179,7 +180,7 @@ func funcStartAuction(ctx wasmlib.ScFuncContext, f *StartAuctionContext) { fa := ScFuncs.FinalizeAuction(ctx) fa.Params.Color().SetValue(auction.Color) - fa.Func.Delay(duration * 60).TransferIotas(1).Post() + fa.Func.Delay(duration * 60).Post() } func viewGetInfo(ctx wasmlib.ScViewContext, f *GetInfoContext) { @@ -206,13 +207,13 @@ func viewGetInfo(ctx wasmlib.ScViewContext, f *GetInfoContext) { f.Results.Bidders().SetValue(bidderList.Length()) } -func transferTokens(ctx wasmlib.ScFuncContext, agent wasmlib.ScAgentID, color wasmlib.ScColor, amount int64) { +func transferTokens(ctx wasmlib.ScFuncContext, agent wasmtypes.ScAgentID, color wasmtypes.ScColor, amount uint64) { if agent.IsAddress() { // send back to original Tangle address - ctx.TransferToAddress(agent.Address(), wasmlib.NewScTransfer(color, amount)) + ctx.Send(agent.Address(), wasmlib.NewScTransfer(color, amount)) return } // TODO not an address, deposit into account on chain - ctx.TransferToAddress(agent.Address(), wasmlib.NewScTransfer(color, amount)) + ctx.Send(agent.Address(), wasmlib.NewScTransfer(color, amount)) } diff --git a/contracts/wasm/fairauction/go/fairauction/keys.go b/contracts/wasm/fairauction/go/fairauction/keys.go deleted file mode 100644 index c66bce5659..0000000000 --- a/contracts/wasm/fairauction/go/fairauction/keys.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package fairauction - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamColor = 0 - IdxParamDescription = 1 - IdxParamDuration = 2 - IdxParamMinimumBid = 3 - IdxParamOwnerMargin = 4 - - IdxResultBidders = 5 - IdxResultColor = 6 - IdxResultCreator = 7 - IdxResultDeposit = 8 - IdxResultDescription = 9 - IdxResultDuration = 10 - IdxResultHighestBid = 11 - IdxResultHighestBidder = 12 - IdxResultMinimumBid = 13 - IdxResultNumTokens = 14 - IdxResultOwnerMargin = 15 - IdxResultWhenStarted = 16 - - IdxStateAuctions = 17 - IdxStateBidderList = 18 - IdxStateBids = 19 - IdxStateOwnerMargin = 20 -) - -const keyMapLen = 21 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamColor, - ParamDescription, - ParamDuration, - ParamMinimumBid, - ParamOwnerMargin, - ResultBidders, - ResultColor, - ResultCreator, - ResultDeposit, - ResultDescription, - ResultDuration, - ResultHighestBid, - ResultHighestBidder, - ResultMinimumBid, - ResultNumTokens, - ResultOwnerMargin, - ResultWhenStarted, - StateAuctions, - StateBidderList, - StateBids, - StateOwnerMargin, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/fairauction/go/fairauction/lib.go b/contracts/wasm/fairauction/go/fairauction/lib.go index 7e27fcdd01..f3e99cd8fa 100644 --- a/contracts/wasm/fairauction/go/fairauction/lib.go +++ b/contracts/wasm/fairauction/go/fairauction/lib.go @@ -7,19 +7,34 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncFinalizeAuction, funcFinalizeAuctionThunk) - exports.AddFunc(FuncPlaceBid, funcPlaceBidThunk) - exports.AddFunc(FuncSetOwnerMargin, funcSetOwnerMarginThunk) - exports.AddFunc(FuncStartAuction, funcStartAuctionThunk) - exports.AddView(ViewGetInfo, viewGetInfoThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncFinalizeAuction, + FuncPlaceBid, + FuncSetOwnerMargin, + FuncStartAuction, + ViewGetInfo, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcFinalizeAuctionThunk, + funcPlaceBidThunk, + funcSetOwnerMarginThunk, + funcStartAuctionThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetInfoThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type FinalizeAuctionContext struct { @@ -29,18 +44,18 @@ type FinalizeAuctionContext struct { func funcFinalizeAuctionThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairauction.funcFinalizeAuction") - - // only SC itself can invoke this function - ctx.Require(ctx.Caller() == ctx.AccountID(), "no permission") - f := &FinalizeAuctionContext{ Params: ImmutableFinalizeAuctionParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairAuctionState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC itself can invoke this function + ctx.Require(ctx.Caller() == ctx.AccountID(), "no permission") + ctx.Require(f.Params.Color().Exists(), "missing mandatory color") funcFinalizeAuction(ctx, f) ctx.Log("fairauction.funcFinalizeAuction ok") @@ -55,10 +70,10 @@ func funcPlaceBidThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairauction.funcPlaceBid") f := &PlaceBidContext{ Params: ImmutablePlaceBidParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairAuctionState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Color().Exists(), "missing mandatory color") @@ -73,18 +88,18 @@ type SetOwnerMarginContext struct { func funcSetOwnerMarginThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairauction.funcSetOwnerMargin") - - // only SC creator can set owner margin - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &SetOwnerMarginContext{ Params: ImmutableSetOwnerMarginParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairAuctionState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC creator can set owner margin + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + ctx.Require(f.Params.OwnerMargin().Exists(), "missing mandatory ownerMargin") funcSetOwnerMargin(ctx, f) ctx.Log("fairauction.funcSetOwnerMargin ok") @@ -99,10 +114,10 @@ func funcStartAuctionThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairauction.funcStartAuction") f := &StartAuctionContext{ Params: ImmutableStartAuctionParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairAuctionState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Color().Exists(), "missing mandatory color") @@ -119,18 +134,20 @@ type GetInfoContext struct { func viewGetInfoThunk(ctx wasmlib.ScViewContext) { ctx.Log("fairauction.viewGetInfo") + results := wasmlib.NewScDict() f := &GetInfoContext{ Params: ImmutableGetInfoParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableGetInfoResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableFairAuctionState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Color().Exists(), "missing mandatory color") viewGetInfo(ctx, f) + ctx.Results(results) ctx.Log("fairauction.viewGetInfo ok") } diff --git a/contracts/wasm/fairauction/go/fairauction/params.go b/contracts/wasm/fairauction/go/fairauction/params.go index 2174a6361a..cd237445aa 100644 --- a/contracts/wasm/fairauction/go/fairauction/params.go +++ b/contracts/wasm/fairauction/go/fairauction/params.go @@ -7,108 +7,108 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableFinalizeAuctionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableFinalizeAuctionParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableFinalizeAuctionParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutableFinalizeAuctionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableFinalizeAuctionParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableFinalizeAuctionParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } type ImmutablePlaceBidParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutablePlaceBidParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutablePlaceBidParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutablePlaceBidParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutablePlaceBidParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutablePlaceBidParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } type ImmutableSetOwnerMarginParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSetOwnerMarginParams) OwnerMargin() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamOwnerMargin)) +func (s ImmutableSetOwnerMarginParams) OwnerMargin() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamOwnerMargin)) } type MutableSetOwnerMarginParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSetOwnerMarginParams) OwnerMargin() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamOwnerMargin)) +func (s MutableSetOwnerMarginParams) OwnerMargin() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamOwnerMargin)) } type ImmutableStartAuctionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableStartAuctionParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableStartAuctionParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } -func (s ImmutableStartAuctionParams) Description() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamDescription)) +func (s ImmutableStartAuctionParams) Description() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamDescription)) } -func (s ImmutableStartAuctionParams) Duration() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamDuration)) +func (s ImmutableStartAuctionParams) Duration() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamDuration)) } -func (s ImmutableStartAuctionParams) MinimumBid() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamMinimumBid)) +func (s ImmutableStartAuctionParams) MinimumBid() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamMinimumBid)) } type MutableStartAuctionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableStartAuctionParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableStartAuctionParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } -func (s MutableStartAuctionParams) Description() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamDescription)) +func (s MutableStartAuctionParams) Description() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamDescription)) } -func (s MutableStartAuctionParams) Duration() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamDuration)) +func (s MutableStartAuctionParams) Duration() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamDuration)) } -func (s MutableStartAuctionParams) MinimumBid() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamMinimumBid)) +func (s MutableStartAuctionParams) MinimumBid() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamMinimumBid)) } type ImmutableGetInfoParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetInfoParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableGetInfoParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutableGetInfoParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetInfoParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableGetInfoParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } diff --git a/contracts/wasm/fairauction/go/fairauction/results.go b/contracts/wasm/fairauction/go/fairauction/results.go index 033177634d..5376ad3723 100644 --- a/contracts/wasm/fairauction/go/fairauction/results.go +++ b/contracts/wasm/fairauction/go/fairauction/results.go @@ -7,108 +7,108 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableGetInfoResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetInfoResults) Bidders() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultBidders)) +func (s ImmutableGetInfoResults) Bidders() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultBidders)) } -func (s ImmutableGetInfoResults) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ResultColor)) +func (s ImmutableGetInfoResults) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ResultColor)) } -func (s ImmutableGetInfoResults) Creator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultCreator)) +func (s ImmutableGetInfoResults) Creator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultCreator)) } -func (s ImmutableGetInfoResults) Deposit() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultDeposit)) +func (s ImmutableGetInfoResults) Deposit() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultDeposit)) } -func (s ImmutableGetInfoResults) Description() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultDescription)) +func (s ImmutableGetInfoResults) Description() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultDescription)) } -func (s ImmutableGetInfoResults) Duration() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultDuration)) +func (s ImmutableGetInfoResults) Duration() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultDuration)) } -func (s ImmutableGetInfoResults) HighestBid() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultHighestBid)) +func (s ImmutableGetInfoResults) HighestBid() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultHighestBid)) } -func (s ImmutableGetInfoResults) HighestBidder() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultHighestBidder)) +func (s ImmutableGetInfoResults) HighestBidder() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultHighestBidder)) } -func (s ImmutableGetInfoResults) MinimumBid() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultMinimumBid)) +func (s ImmutableGetInfoResults) MinimumBid() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultMinimumBid)) } -func (s ImmutableGetInfoResults) NumTokens() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultNumTokens)) +func (s ImmutableGetInfoResults) NumTokens() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultNumTokens)) } -func (s ImmutableGetInfoResults) OwnerMargin() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultOwnerMargin)) +func (s ImmutableGetInfoResults) OwnerMargin() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultOwnerMargin)) } -func (s ImmutableGetInfoResults) WhenStarted() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultWhenStarted)) +func (s ImmutableGetInfoResults) WhenStarted() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultWhenStarted)) } type MutableGetInfoResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetInfoResults) Bidders() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultBidders)) +func (s MutableGetInfoResults) Bidders() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultBidders)) } -func (s MutableGetInfoResults) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ResultColor)) +func (s MutableGetInfoResults) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ResultColor)) } -func (s MutableGetInfoResults) Creator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultCreator)) +func (s MutableGetInfoResults) Creator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultCreator)) } -func (s MutableGetInfoResults) Deposit() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultDeposit)) +func (s MutableGetInfoResults) Deposit() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultDeposit)) } -func (s MutableGetInfoResults) Description() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultDescription)) +func (s MutableGetInfoResults) Description() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultDescription)) } -func (s MutableGetInfoResults) Duration() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultDuration)) +func (s MutableGetInfoResults) Duration() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultDuration)) } -func (s MutableGetInfoResults) HighestBid() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultHighestBid)) +func (s MutableGetInfoResults) HighestBid() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultHighestBid)) } -func (s MutableGetInfoResults) HighestBidder() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultHighestBidder)) +func (s MutableGetInfoResults) HighestBidder() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultHighestBidder)) } -func (s MutableGetInfoResults) MinimumBid() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultMinimumBid)) +func (s MutableGetInfoResults) MinimumBid() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultMinimumBid)) } -func (s MutableGetInfoResults) NumTokens() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultNumTokens)) +func (s MutableGetInfoResults) NumTokens() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultNumTokens)) } -func (s MutableGetInfoResults) OwnerMargin() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultOwnerMargin)) +func (s MutableGetInfoResults) OwnerMargin() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultOwnerMargin)) } -func (s MutableGetInfoResults) WhenStarted() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultWhenStarted)) +func (s MutableGetInfoResults) WhenStarted() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultWhenStarted)) } diff --git a/contracts/wasm/fairauction/go/fairauction/state.go b/contracts/wasm/fairauction/go/fairauction/state.go index 4fce8d8fba..0dde9484fd 100644 --- a/contracts/wasm/fairauction/go/fairauction/state.go +++ b/contracts/wasm/fairauction/go/fairauction/state.go @@ -7,97 +7,90 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type MapColorToImmutableAuction struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapColorToImmutableAuction) GetAuction(key wasmlib.ScColor) ImmutableAuction { - return ImmutableAuction{objID: m.objID, keyID: key.KeyID()} +func (m MapColorToImmutableAuction) GetAuction(key wasmtypes.ScColor) ImmutableAuction { + return ImmutableAuction{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MapColorToImmutableBidderList struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapColorToImmutableBidderList) GetBidderList(key wasmlib.ScColor) ImmutableBidderList { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_AGENT_ID) - return ImmutableBidderList{objID: subID} +func (m MapColorToImmutableBidderList) GetBidderList(key wasmtypes.ScColor) ImmutableBidderList { + return ImmutableBidderList{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MapColorToImmutableBids struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapColorToImmutableBids) GetBids(key wasmlib.ScColor) ImmutableBids { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return ImmutableBids{objID: subID} +func (m MapColorToImmutableBids) GetBids(key wasmtypes.ScColor) ImmutableBids { + return ImmutableBids{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type ImmutableFairAuctionState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableFairAuctionState) Auctions() MapColorToImmutableAuction { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateAuctions), wasmlib.TYPE_MAP) - return MapColorToImmutableAuction{objID: mapID} + return MapColorToImmutableAuction{proxy: s.proxy.Root(StateAuctions)} } func (s ImmutableFairAuctionState) BidderList() MapColorToImmutableBidderList { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBidderList), wasmlib.TYPE_MAP) - return MapColorToImmutableBidderList{objID: mapID} + return MapColorToImmutableBidderList{proxy: s.proxy.Root(StateBidderList)} } func (s ImmutableFairAuctionState) Bids() MapColorToImmutableBids { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBids), wasmlib.TYPE_MAP) - return MapColorToImmutableBids{objID: mapID} + return MapColorToImmutableBids{proxy: s.proxy.Root(StateBids)} } -func (s ImmutableFairAuctionState) OwnerMargin() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateOwnerMargin)) +func (s ImmutableFairAuctionState) OwnerMargin() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateOwnerMargin)) } type MapColorToMutableAuction struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapColorToMutableAuction) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapColorToMutableAuction) GetAuction(key wasmlib.ScColor) MutableAuction { - return MutableAuction{objID: m.objID, keyID: key.KeyID()} +func (m MapColorToMutableAuction) GetAuction(key wasmtypes.ScColor) MutableAuction { + return MutableAuction{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MapColorToMutableBidderList struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapColorToMutableBidderList) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapColorToMutableBidderList) GetBidderList(key wasmlib.ScColor) MutableBidderList { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_AGENT_ID) - return MutableBidderList{objID: subID} +func (m MapColorToMutableBidderList) GetBidderList(key wasmtypes.ScColor) MutableBidderList { + return MutableBidderList{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MapColorToMutableBids struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapColorToMutableBids) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapColorToMutableBids) GetBids(key wasmlib.ScColor) MutableBids { - subID := wasmlib.GetObjectID(m.objID, key.KeyID(), wasmlib.TYPE_MAP) - return MutableBids{objID: subID} +func (m MapColorToMutableBids) GetBids(key wasmtypes.ScColor) MutableBids { + return MutableBids{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MutableFairAuctionState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableFairAuctionState) AsImmutable() ImmutableFairAuctionState { @@ -105,20 +98,17 @@ func (s MutableFairAuctionState) AsImmutable() ImmutableFairAuctionState { } func (s MutableFairAuctionState) Auctions() MapColorToMutableAuction { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateAuctions), wasmlib.TYPE_MAP) - return MapColorToMutableAuction{objID: mapID} + return MapColorToMutableAuction{proxy: s.proxy.Root(StateAuctions)} } func (s MutableFairAuctionState) BidderList() MapColorToMutableBidderList { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBidderList), wasmlib.TYPE_MAP) - return MapColorToMutableBidderList{objID: mapID} + return MapColorToMutableBidderList{proxy: s.proxy.Root(StateBidderList)} } func (s MutableFairAuctionState) Bids() MapColorToMutableBids { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBids), wasmlib.TYPE_MAP) - return MapColorToMutableBids{objID: mapID} + return MapColorToMutableBids{proxy: s.proxy.Root(StateBids)} } -func (s MutableFairAuctionState) OwnerMargin() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateOwnerMargin)) +func (s MutableFairAuctionState) OwnerMargin() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateOwnerMargin)) } diff --git a/contracts/wasm/fairauction/go/fairauction/structs.go b/contracts/wasm/fairauction/go/fairauction/structs.go index ef4c7a49d2..a53661f4a6 100644 --- a/contracts/wasm/fairauction/go/fairauction/structs.go +++ b/contracts/wasm/fairauction/go/fairauction/structs.go @@ -7,144 +7,140 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type Auction struct { - Color wasmlib.ScColor // color of tokens for sale - Creator wasmlib.ScAgentID // issuer of start_auction transaction - Deposit int64 // deposit by auction owner to cover the SC fees - Description string // auction description - Duration int32 // auction duration in minutes - HighestBid int64 // the current highest bid amount - HighestBidder wasmlib.ScAgentID // the current highest bidder - MinimumBid int64 // minimum bid amount - NumTokens int64 // number of tokens for sale - OwnerMargin int64 // auction owner's margin in promilles - WhenStarted int64 // timestamp when auction started -} - -func NewAuctionFromBytes(bytes []byte) *Auction { - decode := wasmlib.NewBytesDecoder(bytes) + Color wasmtypes.ScColor // color of tokens for sale + Creator wasmtypes.ScAgentID // issuer of start_auction transaction + Deposit uint64 // deposit by auction owner to cover the SC fees + Description string // auction description + Duration uint32 // auction duration in minutes + HighestBid uint64 // the current highest bid amount + HighestBidder wasmtypes.ScAgentID // the current highest bidder + MinimumBid uint64 // minimum bid amount + NumTokens uint64 // number of tokens for sale + OwnerMargin uint64 // auction owner's margin in promilles + WhenStarted uint64 // timestamp when auction started +} + +func NewAuctionFromBytes(buf []byte) *Auction { + dec := wasmtypes.NewWasmDecoder(buf) data := &Auction{} - data.Color = decode.Color() - data.Creator = decode.AgentID() - data.Deposit = decode.Int64() - data.Description = decode.String() - data.Duration = decode.Int32() - data.HighestBid = decode.Int64() - data.HighestBidder = decode.AgentID() - data.MinimumBid = decode.Int64() - data.NumTokens = decode.Int64() - data.OwnerMargin = decode.Int64() - data.WhenStarted = decode.Int64() - decode.Close() + data.Color = wasmtypes.ColorDecode(dec) + data.Creator = wasmtypes.AgentIDDecode(dec) + data.Deposit = wasmtypes.Uint64Decode(dec) + data.Description = wasmtypes.StringDecode(dec) + data.Duration = wasmtypes.Uint32Decode(dec) + data.HighestBid = wasmtypes.Uint64Decode(dec) + data.HighestBidder = wasmtypes.AgentIDDecode(dec) + data.MinimumBid = wasmtypes.Uint64Decode(dec) + data.NumTokens = wasmtypes.Uint64Decode(dec) + data.OwnerMargin = wasmtypes.Uint64Decode(dec) + data.WhenStarted = wasmtypes.Uint64Decode(dec) + dec.Close() return data } func (o *Auction) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Color(o.Color). - AgentID(o.Creator). - Int64(o.Deposit). - String(o.Description). - Int32(o.Duration). - Int64(o.HighestBid). - AgentID(o.HighestBidder). - Int64(o.MinimumBid). - Int64(o.NumTokens). - Int64(o.OwnerMargin). - Int64(o.WhenStarted). - Data() + enc := wasmtypes.NewWasmEncoder() + wasmtypes.ColorEncode(enc, o.Color) + wasmtypes.AgentIDEncode(enc, o.Creator) + wasmtypes.Uint64Encode(enc, o.Deposit) + wasmtypes.StringEncode(enc, o.Description) + wasmtypes.Uint32Encode(enc, o.Duration) + wasmtypes.Uint64Encode(enc, o.HighestBid) + wasmtypes.AgentIDEncode(enc, o.HighestBidder) + wasmtypes.Uint64Encode(enc, o.MinimumBid) + wasmtypes.Uint64Encode(enc, o.NumTokens) + wasmtypes.Uint64Encode(enc, o.OwnerMargin) + wasmtypes.Uint64Encode(enc, o.WhenStarted) + return enc.Buf() } type ImmutableAuction struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o ImmutableAuction) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o ImmutableAuction) Value() *Auction { - return NewAuctionFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewAuctionFromBytes(o.proxy.Get()) } type MutableAuction struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o MutableAuction) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } func (o MutableAuction) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o MutableAuction) SetValue(value *Auction) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } func (o MutableAuction) Value() *Auction { - return NewAuctionFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewAuctionFromBytes(o.proxy.Get()) } type Bid struct { - Amount int64 // cumulative amount of bids from same bidder - Index int32 // index of bidder in bidder list - Timestamp int64 // timestamp of most recent bid + Amount uint64 // cumulative amount of bids from same bidder + Index uint32 // index of bidder in bidder list + Timestamp uint64 // timestamp of most recent bid } -func NewBidFromBytes(bytes []byte) *Bid { - decode := wasmlib.NewBytesDecoder(bytes) +func NewBidFromBytes(buf []byte) *Bid { + dec := wasmtypes.NewWasmDecoder(buf) data := &Bid{} - data.Amount = decode.Int64() - data.Index = decode.Int32() - data.Timestamp = decode.Int64() - decode.Close() + data.Amount = wasmtypes.Uint64Decode(dec) + data.Index = wasmtypes.Uint32Decode(dec) + data.Timestamp = wasmtypes.Uint64Decode(dec) + dec.Close() return data } func (o *Bid) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Int64(o.Amount). - Int32(o.Index). - Int64(o.Timestamp). - Data() + enc := wasmtypes.NewWasmEncoder() + wasmtypes.Uint64Encode(enc, o.Amount) + wasmtypes.Uint32Encode(enc, o.Index) + wasmtypes.Uint64Encode(enc, o.Timestamp) + return enc.Buf() } type ImmutableBid struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o ImmutableBid) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o ImmutableBid) Value() *Bid { - return NewBidFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewBidFromBytes(o.proxy.Get()) } type MutableBid struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o MutableBid) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } func (o MutableBid) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o MutableBid) SetValue(value *Bid) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } func (o MutableBid) Value() *Bid { - return NewBidFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewBidFromBytes(o.proxy.Get()) } diff --git a/contracts/wasm/fairauction/go/fairauction/typedefs.go b/contracts/wasm/fairauction/go/fairauction/typedefs.go index 719567b083..9cfe81f2b9 100644 --- a/contracts/wasm/fairauction/go/fairauction/typedefs.go +++ b/contracts/wasm/fairauction/go/fairauction/typedefs.go @@ -7,60 +7,64 @@ package fairauction -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableAgentID struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableAgentID) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableAgentID) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableAgentID) GetAgentID(index int32) wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(a.objID, wasmlib.Key32(index)) +func (a ArrayOfImmutableAgentID) GetAgentID(index uint32) wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(a.proxy.Index(index)) } type ImmutableBidderList = ArrayOfImmutableAgentID type ArrayOfMutableAgentID struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableAgentID) AppendAgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(a.proxy.Append()) } func (a ArrayOfMutableAgentID) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableAgentID) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableAgentID) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableAgentID) GetAgentID(index int32) wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(a.objID, wasmlib.Key32(index)) +func (a ArrayOfMutableAgentID) GetAgentID(index uint32) wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(a.proxy.Index(index)) } type MutableBidderList = ArrayOfMutableAgentID type MapAgentIDToImmutableBid struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapAgentIDToImmutableBid) GetBid(key wasmlib.ScAgentID) ImmutableBid { - return ImmutableBid{objID: m.objID, keyID: key.KeyID()} +func (m MapAgentIDToImmutableBid) GetBid(key wasmtypes.ScAgentID) ImmutableBid { + return ImmutableBid{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type ImmutableBids = MapAgentIDToImmutableBid type MapAgentIDToMutableBid struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapAgentIDToMutableBid) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapAgentIDToMutableBid) GetBid(key wasmlib.ScAgentID) MutableBid { - return MutableBid{objID: m.objID, keyID: key.KeyID()} +func (m MapAgentIDToMutableBid) GetBid(key wasmtypes.ScAgentID) MutableBid { + return MutableBid{proxy: m.proxy.Key(wasmtypes.AgentIDToBytes(key))} } type MutableBids = MapAgentIDToMutableBid diff --git a/contracts/wasm/fairauction/go/main.go b/contracts/wasm/fairauction/go/main.go index 031df458fb..233c37738c 100644 --- a/contracts/wasm/fairauction/go/main.go +++ b/contracts/wasm/fairauction/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/fairauction/go/fairauction" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + fairauction.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - fairauction.OnLoad() + fairauction.OnLoad(-1) } diff --git a/contracts/wasm/fairauction/schema.yaml b/contracts/wasm/fairauction/schema.yaml index d75cf891cd..bb890b6b15 100644 --- a/contracts/wasm/fairauction/schema.yaml +++ b/contracts/wasm/fairauction/schema.yaml @@ -4,19 +4,19 @@ structs: Auction: color: Color // color of tokens for sale creator: AgentID // issuer of start_auction transaction - deposit: Int64 // deposit by auction owner to cover the SC fees + deposit: Uint64 // deposit by auction owner to cover the SC fees description: String // auction description - duration: Int32 // auction duration in minutes - highestBid: Int64 // the current highest bid amount + duration: Uint32 // auction duration in minutes + highestBid: Uint64 // the current highest bid amount highestBidder: AgentID // the current highest bidder - minimumBid: Int64 // minimum bid amount - numTokens: Int64 // number of tokens for sale - ownerMargin: Int64 // auction owner's margin in promilles - whenStarted: Int64 // timestamp when auction started + minimumBid: Uint64 // minimum bid amount + numTokens: Uint64 // number of tokens for sale + ownerMargin: Uint64 // auction owner's margin in promilles + whenStarted: Uint64 // timestamp when auction started Bid: - amount: Int64 // cumulative amount of bids from same bidder - index: Int32 // index of bidder in bidder list - timestamp: Int64 // timestamp of most recent bid + amount: Uint64 // cumulative amount of bids from same bidder + index: Uint32 // index of bidder in bidder list + timestamp: Uint64 // timestamp of most recent bid typedefs: BidderList: AgentID[] Bids: map[AgentID]Bid @@ -24,7 +24,7 @@ state: auctions: map[Color]Auction bidderList: map[Color]BidderList bids: map[Color]Bids - ownerMargin: Int64 // default auction owner's margin in promilles + ownerMargin: Uint64 // default auction owner's margin in promilles funcs: finalizeAuction: access: self // only SC itself can invoke this function @@ -36,27 +36,27 @@ funcs: setOwnerMargin: access: creator // only SC creator can set owner margin params: - ownerMargin: Int64 // new SC owner margin in promilles + ownerMargin: Uint64 // new SC owner margin in promilles startAuction: params: color: Color // color of the tokens being auctioned description: String? // description of the tokens being auctioned - duration: Int32? // duration of auction in minutes - minimumBid: Int64 // minimum required amount for any bid + duration: Uint32? // duration of auction in minutes + minimumBid: Uint64 // minimum required amount for any bid views: getInfo: params: color: Color // color identifies the auction results: - bidders: Int32 // nr of bidders + bidders: Uint32 // nr of bidders color: Color // color of tokens for sale creator: AgentID // issuer of start_auction transaction - deposit: Int64 // deposit by auction owner to cover the SC fees + deposit: Uint64 // deposit by auction owner to cover the SC fees description: String // auction description - duration: Int32 // auction duration in minutes - highestBid: Int64 // the current highest bid amount + duration: Uint32 // auction duration in minutes + highestBid: Uint64 // the current highest bid amount highestBidder: AgentID // the current highest bidder - minimumBid: Int64 // minimum bid amount - numTokens: Int64 // number of tokens for sale - ownerMargin: Int64 // auction owner's margin in promilles - whenStarted: Int64 // timestamp when auction started + minimumBid: Uint64 // minimum bid amount + numTokens: Uint64 // number of tokens for sale + ownerMargin: Uint64 // auction owner's margin in promilles + whenStarted: Uint64 // timestamp when auction started diff --git a/contracts/wasm/fairauction/src/contract.rs b/contracts/wasm/fairauction/src/contract.rs index 78cd2681ae..92d96f2b31 100644 --- a/contracts/wasm/fairauction/src/contract.rs +++ b/contracts/wasm/fairauction/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct FinalizeAuctionCall { pub func: ScFunc, @@ -45,49 +40,50 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn finalize_auction(_ctx: & dyn ScFuncCallContext) -> FinalizeAuctionCall { + pub fn finalize_auction(_ctx: &dyn ScFuncCallContext) -> FinalizeAuctionCall { let mut f = FinalizeAuctionCall { func: ScFunc::new(HSC_NAME, HFUNC_FINALIZE_AUCTION), - params: MutableFinalizeAuctionParams { id: 0 }, + params: MutableFinalizeAuctionParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn place_bid(_ctx: & dyn ScFuncCallContext) -> PlaceBidCall { + pub fn place_bid(_ctx: &dyn ScFuncCallContext) -> PlaceBidCall { let mut f = PlaceBidCall { func: ScFunc::new(HSC_NAME, HFUNC_PLACE_BID), - params: MutablePlaceBidParams { id: 0 }, + params: MutablePlaceBidParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_owner_margin(_ctx: & dyn ScFuncCallContext) -> SetOwnerMarginCall { + pub fn set_owner_margin(_ctx: &dyn ScFuncCallContext) -> SetOwnerMarginCall { let mut f = SetOwnerMarginCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_OWNER_MARGIN), - params: MutableSetOwnerMarginParams { id: 0 }, + params: MutableSetOwnerMarginParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn start_auction(_ctx: & dyn ScFuncCallContext) -> StartAuctionCall { + pub fn start_auction(_ctx: &dyn ScFuncCallContext) -> StartAuctionCall { let mut f = StartAuctionCall { func: ScFunc::new(HSC_NAME, HFUNC_START_AUCTION), - params: MutableStartAuctionParams { id: 0 }, + params: MutableStartAuctionParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn get_info(_ctx: & dyn ScViewCallContext) -> GetInfoCall { + pub fn get_info(_ctx: &dyn ScViewCallContext) -> GetInfoCall { let mut f = GetInfoCall { func: ScView::new(HSC_NAME, HVIEW_GET_INFO), - params: MutableGetInfoParams { id: 0 }, - results: ImmutableGetInfoResults { id: 0 }, + params: MutableGetInfoParams { proxy: Proxy::nil() }, + results: ImmutableGetInfoResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/fairauction/src/fairauction.rs b/contracts/wasm/fairauction/src/fairauction.rs index 822eed784b..76a6b30e66 100644 --- a/contracts/wasm/fairauction/src/fairauction.rs +++ b/contracts/wasm/fairauction/src/fairauction.rs @@ -7,20 +7,20 @@ use crate::*; use crate::contract::*; use crate::structs::*; -const DURATION_DEFAULT: i32 = 60; -const DURATION_MIN: i32 = 1; -const DURATION_MAX: i32 = 120; +const DURATION_DEFAULT: u32 = 60; +const DURATION_MIN: u32 = 1; +const DURATION_MAX: u32 = 120; const MAX_DESCRIPTION_LENGTH: usize = 150; -const OWNER_MARGIN_DEFAULT: i64 = 50; -const OWNER_MARGIN_MIN: i64 = 5; -const OWNER_MARGIN_MAX: i64 = 100; +const OWNER_MARGIN_DEFAULT: u64 = 50; +const OWNER_MARGIN_MIN: u64 = 5; +const OWNER_MARGIN_MAX: u64 = 100; pub fn func_finalize_auction(ctx: &ScFuncContext, f: &FinalizeAuctionContext) { let color = f.params.color().value(); let current_auction = f.state.auctions().get_auction(&color); ctx.require(current_auction.exists(), "Missing auction info"); let auction = current_auction.value(); - if auction.highest_bid < 0 { + if auction.highest_bid == 0 { ctx.log(&("No one bid on ".to_string() + &color.to_string())); let mut owner_fee = auction.minimum_bid * auction.owner_margin / 1000; if owner_fee == 0 { @@ -80,7 +80,7 @@ pub fn func_place_bid(ctx: &ScFuncContext, f: &PlaceBidContext) { ctx.require(bid_amount >= auction.minimum_bid, "Insufficient bid amount"); ctx.log(&("New bid from: ".to_string() + &caller.to_string())); let index = bidder_list.length(); - bidder_list.get_agent_id(index).set_value(&caller); + bidder_list.append_agent_id().set_value(&caller); let bid = Bid { index: index, amount: bid_amount, @@ -166,8 +166,8 @@ pub fn func_start_auction(ctx: &ScFuncContext, f: &StartAuctionContext) { deposit: deposit, description: description, duration: duration, - highest_bid: -1, - highest_bidder: ScAgentID::from_bytes(&[0; 37]), + highest_bid: 0, + highest_bidder: agent_id_from_bytes(&[]), minimum_bid: minimum_bid, num_tokens: num_tokens, owner_margin: owner_margin, @@ -177,7 +177,7 @@ pub fn func_start_auction(ctx: &ScFuncContext, f: &StartAuctionContext) { let fa = ScFuncs::finalize_auction(ctx); fa.params.color().set_value(&auction.color); - fa.func.delay(duration * 60).transfer_iotas(1).post(); + fa.func.delay(duration * 60).post(); } pub fn view_get_info(ctx: &ScViewContext, f: &GetInfoContext) { @@ -202,13 +202,13 @@ pub fn view_get_info(ctx: &ScViewContext, f: &GetInfoContext) { f.results.bidders().set_value(bidder_list.length()); } -fn transfer_tokens(ctx: &ScFuncContext, agent: &ScAgentID, color: &ScColor, amount: i64) { +fn transfer_tokens(ctx: &ScFuncContext, agent: &ScAgentID, color: &ScColor, amount: u64) { if agent.is_address() { // send back to original Tangle address - ctx.transfer_to_address(&agent.address(), ScTransfers::transfer(color, amount)); + ctx.send(&agent.address(), &ScTransfers::transfer(color, amount)); return; } // TODO not an address, deposit into account on chain - ctx.transfer_to_address(&agent.address(), ScTransfers::transfer(color, amount)); + ctx.send(&agent.address(), &ScTransfers::transfer(color, amount)); } diff --git a/contracts/wasm/fairauction/src/keys.rs b/contracts/wasm/fairauction/src/keys.rs deleted file mode 100644 index 843e56e642..0000000000 --- a/contracts/wasm/fairauction/src/keys.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_COLOR : usize = 0; -pub(crate) const IDX_PARAM_DESCRIPTION : usize = 1; -pub(crate) const IDX_PARAM_DURATION : usize = 2; -pub(crate) const IDX_PARAM_MINIMUM_BID : usize = 3; -pub(crate) const IDX_PARAM_OWNER_MARGIN : usize = 4; - -pub(crate) const IDX_RESULT_BIDDERS : usize = 5; -pub(crate) const IDX_RESULT_COLOR : usize = 6; -pub(crate) const IDX_RESULT_CREATOR : usize = 7; -pub(crate) const IDX_RESULT_DEPOSIT : usize = 8; -pub(crate) const IDX_RESULT_DESCRIPTION : usize = 9; -pub(crate) const IDX_RESULT_DURATION : usize = 10; -pub(crate) const IDX_RESULT_HIGHEST_BID : usize = 11; -pub(crate) const IDX_RESULT_HIGHEST_BIDDER : usize = 12; -pub(crate) const IDX_RESULT_MINIMUM_BID : usize = 13; -pub(crate) const IDX_RESULT_NUM_TOKENS : usize = 14; -pub(crate) const IDX_RESULT_OWNER_MARGIN : usize = 15; -pub(crate) const IDX_RESULT_WHEN_STARTED : usize = 16; - -pub(crate) const IDX_STATE_AUCTIONS : usize = 17; -pub(crate) const IDX_STATE_BIDDER_LIST : usize = 18; -pub(crate) const IDX_STATE_BIDS : usize = 19; -pub(crate) const IDX_STATE_OWNER_MARGIN : usize = 20; - -pub const KEY_MAP_LEN: usize = 21; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_COLOR, - PARAM_DESCRIPTION, - PARAM_DURATION, - PARAM_MINIMUM_BID, - PARAM_OWNER_MARGIN, - RESULT_BIDDERS, - RESULT_COLOR, - RESULT_CREATOR, - RESULT_DEPOSIT, - RESULT_DESCRIPTION, - RESULT_DURATION, - RESULT_HIGHEST_BID, - RESULT_HIGHEST_BIDDER, - RESULT_MINIMUM_BID, - RESULT_NUM_TOKENS, - RESULT_OWNER_MARGIN, - RESULT_WHEN_STARTED, - STATE_AUCTIONS, - STATE_BIDDER_LIST, - STATE_BIDS, - STATE_OWNER_MARGIN, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/fairauction/src/lib.rs b/contracts/wasm/fairauction/src/lib.rs index 97dec4b38d..d5fff469b1 100644 --- a/contracts/wasm/fairauction/src/lib.rs +++ b/contracts/wasm/fairauction/src/lib.rs @@ -10,38 +10,51 @@ use fairauction::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::structs::*; +use crate::typedefs::*; mod consts; mod contract; -mod keys; mod params; mod results; mod state; mod structs; mod typedefs; + mod fairauction; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_FINALIZE_AUCTION, + FUNC_PLACE_BID, + FUNC_SET_OWNER_MARGIN, + FUNC_START_AUCTION, + VIEW_GET_INFO, + ], + funcs: &[ + func_finalize_auction_thunk, + func_place_bid_thunk, + func_set_owner_margin_thunk, + func_start_auction_thunk, + ], + views: &[ + view_get_info_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_FINALIZE_AUCTION, func_finalize_auction_thunk); - exports.add_func(FUNC_PLACE_BID, func_place_bid_thunk); - exports.add_func(FUNC_SET_OWNER_MARGIN, func_set_owner_margin_thunk); - exports.add_func(FUNC_START_AUCTION, func_start_auction_thunk); - exports.add_view(VIEW_GET_INFO, view_get_info_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct FinalizeAuctionContext { @@ -51,18 +64,14 @@ pub struct FinalizeAuctionContext { fn func_finalize_auction_thunk(ctx: &ScFuncContext) { ctx.log("fairauction.funcFinalizeAuction"); + let f = FinalizeAuctionContext { + params: ImmutableFinalizeAuctionParams { proxy: params_proxy() }, + state: MutableFairAuctionState { proxy: state_proxy() }, + }; // only SC itself can invoke this function ctx.require(ctx.caller() == ctx.account_id(), "no permission"); - let f = FinalizeAuctionContext { - params: ImmutableFinalizeAuctionParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairAuctionState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.color().exists(), "missing mandatory color"); func_finalize_auction(ctx, &f); ctx.log("fairauction.funcFinalizeAuction ok"); @@ -76,12 +85,8 @@ pub struct PlaceBidContext { fn func_place_bid_thunk(ctx: &ScFuncContext) { ctx.log("fairauction.funcPlaceBid"); let f = PlaceBidContext { - params: ImmutablePlaceBidParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairAuctionState { - id: OBJ_ID_STATE, - }, + params: ImmutablePlaceBidParams { proxy: params_proxy() }, + state: MutableFairAuctionState { proxy: state_proxy() }, }; ctx.require(f.params.color().exists(), "missing mandatory color"); func_place_bid(ctx, &f); @@ -95,18 +100,14 @@ pub struct SetOwnerMarginContext { fn func_set_owner_margin_thunk(ctx: &ScFuncContext) { ctx.log("fairauction.funcSetOwnerMargin"); + let f = SetOwnerMarginContext { + params: ImmutableSetOwnerMarginParams { proxy: params_proxy() }, + state: MutableFairAuctionState { proxy: state_proxy() }, + }; // only SC creator can set owner margin ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = SetOwnerMarginContext { - params: ImmutableSetOwnerMarginParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairAuctionState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.owner_margin().exists(), "missing mandatory ownerMargin"); func_set_owner_margin(ctx, &f); ctx.log("fairauction.funcSetOwnerMargin ok"); @@ -120,12 +121,8 @@ pub struct StartAuctionContext { fn func_start_auction_thunk(ctx: &ScFuncContext) { ctx.log("fairauction.funcStartAuction"); let f = StartAuctionContext { - params: ImmutableStartAuctionParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairAuctionState { - id: OBJ_ID_STATE, - }, + params: ImmutableStartAuctionParams { proxy: params_proxy() }, + state: MutableFairAuctionState { proxy: state_proxy() }, }; ctx.require(f.params.color().exists(), "missing mandatory color"); ctx.require(f.params.minimum_bid().exists(), "missing mandatory minimumBid"); @@ -142,17 +139,12 @@ pub struct GetInfoContext { fn view_get_info_thunk(ctx: &ScViewContext) { ctx.log("fairauction.viewGetInfo"); let f = GetInfoContext { - params: ImmutableGetInfoParams { - id: OBJ_ID_PARAMS, - }, - results: MutableGetInfoResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableFairAuctionState { - id: OBJ_ID_STATE, - }, + params: ImmutableGetInfoParams { proxy: params_proxy() }, + results: MutableGetInfoResults { proxy: results_proxy() }, + state: ImmutableFairAuctionState { proxy: state_proxy() }, }; ctx.require(f.params.color().exists(), "missing mandatory color"); view_get_info(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("fairauction.viewGetInfo ok"); } diff --git a/contracts/wasm/fairauction/src/params.rs b/contracts/wasm/fairauction/src/params.rs index bcc902b795..06a6b55eb2 100644 --- a/contracts/wasm/fairauction/src/params.rs +++ b/contracts/wasm/fairauction/src/params.rs @@ -9,143 +9,138 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFinalizeAuctionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFinalizeAuctionParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFinalizeAuctionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFinalizeAuctionParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutablePlaceBidParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutablePlaceBidParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutablePlaceBidParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutablePlaceBidParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetOwnerMarginParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetOwnerMarginParams { - pub fn owner_margin(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_OWNER_MARGIN)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetOwnerMarginParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetOwnerMarginParams { - pub fn owner_margin(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_OWNER_MARGIN)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableStartAuctionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableStartAuctionParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } pub fn description(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } - pub fn duration(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_DURATION.get_key_id()) + pub fn duration(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_DURATION)) } - pub fn minimum_bid(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_MINIMUM_BID.get_key_id()) + pub fn minimum_bid(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_MINIMUM_BID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableStartAuctionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableStartAuctionParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } pub fn description(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } - pub fn duration(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_DURATION.get_key_id()) + pub fn duration(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_DURATION)) } - pub fn minimum_bid(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_MINIMUM_BID.get_key_id()) + pub fn minimum_bid(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_MINIMUM_BID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetInfoParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetInfoParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } diff --git a/contracts/wasm/fairauction/src/results.rs b/contracts/wasm/fairauction/src/results.rs index 649bd85b43..e0769eb70d 100644 --- a/contracts/wasm/fairauction/src/results.rs +++ b/contracts/wasm/fairauction/src/results.rs @@ -9,119 +9,114 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetInfoResults { - pub fn bidders(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_BIDDERS.get_key_id()) + pub fn bidders(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_BIDDERS)) } pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, RESULT_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(RESULT_COLOR)) } pub fn creator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_CREATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_CREATOR)) } - pub fn deposit(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_DEPOSIT.get_key_id()) + pub fn deposit(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_DEPOSIT)) } pub fn description(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_DESCRIPTION.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_DESCRIPTION)) } - pub fn duration(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_DURATION.get_key_id()) + pub fn duration(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_DURATION)) } - pub fn highest_bid(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_HIGHEST_BID.get_key_id()) + pub fn highest_bid(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_HIGHEST_BID)) } pub fn highest_bidder(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_HIGHEST_BIDDER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_HIGHEST_BIDDER)) } - pub fn minimum_bid(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_MINIMUM_BID.get_key_id()) + pub fn minimum_bid(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_MINIMUM_BID)) } - pub fn num_tokens(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_NUM_TOKENS.get_key_id()) + pub fn num_tokens(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_NUM_TOKENS)) } - pub fn owner_margin(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_OWNER_MARGIN)) } - pub fn when_started(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_WHEN_STARTED.get_key_id()) + pub fn when_started(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_WHEN_STARTED)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetInfoResults { - pub fn bidders(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_BIDDERS.get_key_id()) + pub fn bidders(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_BIDDERS)) } pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, RESULT_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(RESULT_COLOR)) } pub fn creator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_CREATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_CREATOR)) } - pub fn deposit(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_DEPOSIT.get_key_id()) + pub fn deposit(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_DEPOSIT)) } pub fn description(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_DESCRIPTION.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_DESCRIPTION)) } - pub fn duration(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_DURATION.get_key_id()) + pub fn duration(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_DURATION)) } - pub fn highest_bid(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_HIGHEST_BID.get_key_id()) + pub fn highest_bid(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_HIGHEST_BID)) } pub fn highest_bidder(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_HIGHEST_BIDDER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_HIGHEST_BIDDER)) } - pub fn minimum_bid(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_MINIMUM_BID.get_key_id()) + pub fn minimum_bid(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_MINIMUM_BID)) } - pub fn num_tokens(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_NUM_TOKENS.get_key_id()) + pub fn num_tokens(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_NUM_TOKENS)) } - pub fn owner_margin(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_OWNER_MARGIN)) } - pub fn when_started(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_WHEN_STARTED.get_key_id()) + pub fn when_started(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_WHEN_STARTED)) } } diff --git a/contracts/wasm/fairauction/src/state.rs b/contracts/wasm/fairauction/src/state.rs index 8f7b0007f1..82cc101b0c 100644 --- a/contracts/wasm/fairauction/src/state.rs +++ b/contracts/wasm/fairauction/src/state.rs @@ -9,147 +9,133 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::structs::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToImmutableAuction { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToImmutableAuction { pub fn get_auction(&self, key: &ScColor) -> ImmutableAuction { - ImmutableAuction { obj_id: self.obj_id, key_id: key.get_key_id() } + ImmutableAuction { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToImmutableBidderList { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToImmutableBidderList { pub fn get_bidder_list(&self, key: &ScColor) -> ImmutableBidderList { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ARRAY | TYPE_AGENT_ID); - ImmutableBidderList { obj_id: sub_id } + ImmutableBidderList { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToImmutableBids { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToImmutableBids { pub fn get_bids(&self, key: &ScColor) -> ImmutableBids { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ImmutableBids { obj_id: sub_id } + ImmutableBids { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFairAuctionState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFairAuctionState { pub fn auctions(&self) -> MapColorToImmutableAuction { - let map_id = get_object_id(self.id, STATE_AUCTIONS.get_key_id(), TYPE_MAP); - MapColorToImmutableAuction { obj_id: map_id } + MapColorToImmutableAuction { proxy: self.proxy.root(STATE_AUCTIONS) } } pub fn bidder_list(&self) -> MapColorToImmutableBidderList { - let map_id = get_object_id(self.id, STATE_BIDDER_LIST.get_key_id(), TYPE_MAP); - MapColorToImmutableBidderList { obj_id: map_id } + MapColorToImmutableBidderList { proxy: self.proxy.root(STATE_BIDDER_LIST) } } pub fn bids(&self) -> MapColorToImmutableBids { - let map_id = get_object_id(self.id, STATE_BIDS.get_key_id(), TYPE_MAP); - MapColorToImmutableBids { obj_id: map_id } + MapColorToImmutableBids { proxy: self.proxy.root(STATE_BIDS) } } - pub fn owner_margin(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_OWNER_MARGIN)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToMutableAuction { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToMutableAuction { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_auction(&self, key: &ScColor) -> MutableAuction { - MutableAuction { obj_id: self.obj_id, key_id: key.get_key_id() } + MutableAuction { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToMutableBidderList { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToMutableBidderList { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bidder_list(&self, key: &ScColor) -> MutableBidderList { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ARRAY | TYPE_AGENT_ID); - MutableBidderList { obj_id: sub_id } + MutableBidderList { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToMutableBids { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToMutableBids { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bids(&self, key: &ScColor) -> MutableBids { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - MutableBids { obj_id: sub_id } + MutableBids { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFairAuctionState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFairAuctionState { pub fn as_immutable(&self) -> ImmutableFairAuctionState { - ImmutableFairAuctionState { id: self.id } + ImmutableFairAuctionState { proxy: self.proxy.root("") } } pub fn auctions(&self) -> MapColorToMutableAuction { - let map_id = get_object_id(self.id, STATE_AUCTIONS.get_key_id(), TYPE_MAP); - MapColorToMutableAuction { obj_id: map_id } + MapColorToMutableAuction { proxy: self.proxy.root(STATE_AUCTIONS) } } pub fn bidder_list(&self) -> MapColorToMutableBidderList { - let map_id = get_object_id(self.id, STATE_BIDDER_LIST.get_key_id(), TYPE_MAP); - MapColorToMutableBidderList { obj_id: map_id } + MapColorToMutableBidderList { proxy: self.proxy.root(STATE_BIDDER_LIST) } } pub fn bids(&self) -> MapColorToMutableBids { - let map_id = get_object_id(self.id, STATE_BIDS.get_key_id(), TYPE_MAP); - MapColorToMutableBids { obj_id: map_id } + MapColorToMutableBids { proxy: self.proxy.root(STATE_BIDS) } } - pub fn owner_margin(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_OWNER_MARGIN.get_key_id()) + pub fn owner_margin(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_OWNER_MARGIN)) } } diff --git a/contracts/wasm/fairauction/src/structs.rs b/contracts/wasm/fairauction/src/structs.rs index 8a0f7e7194..026b1171a3 100644 --- a/contracts/wasm/fairauction/src/structs.rs +++ b/contracts/wasm/fairauction/src/structs.rs @@ -9,161 +9,155 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; -use crate::typedefs::*; #[derive(Clone)] pub struct Auction { pub color : ScColor, // color of tokens for sale pub creator : ScAgentID, // issuer of start_auction transaction - pub deposit : i64, // deposit by auction owner to cover the SC fees + pub deposit : u64, // deposit by auction owner to cover the SC fees pub description : String, // auction description - pub duration : i32, // auction duration in minutes - pub highest_bid : i64, // the current highest bid amount + pub duration : u32, // auction duration in minutes + pub highest_bid : u64, // the current highest bid amount pub highest_bidder : ScAgentID, // the current highest bidder - pub minimum_bid : i64, // minimum bid amount - pub num_tokens : i64, // number of tokens for sale - pub owner_margin : i64, // auction owner's margin in promilles - pub when_started : i64, // timestamp when auction started + pub minimum_bid : u64, // minimum bid amount + pub num_tokens : u64, // number of tokens for sale + pub owner_margin : u64, // auction owner's margin in promilles + pub when_started : u64, // timestamp when auction started } impl Auction { pub fn from_bytes(bytes: &[u8]) -> Auction { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); Auction { - color : decode.color(), - creator : decode.agent_id(), - deposit : decode.int64(), - description : decode.string(), - duration : decode.int32(), - highest_bid : decode.int64(), - highest_bidder : decode.agent_id(), - minimum_bid : decode.int64(), - num_tokens : decode.int64(), - owner_margin : decode.int64(), - when_started : decode.int64(), + color : color_decode(&mut dec), + creator : agent_id_decode(&mut dec), + deposit : uint64_decode(&mut dec), + description : string_decode(&mut dec), + duration : uint32_decode(&mut dec), + highest_bid : uint64_decode(&mut dec), + highest_bidder : agent_id_decode(&mut dec), + minimum_bid : uint64_decode(&mut dec), + num_tokens : uint64_decode(&mut dec), + owner_margin : uint64_decode(&mut dec), + when_started : uint64_decode(&mut dec), } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.color(&self.color); - encode.agent_id(&self.creator); - encode.int64(self.deposit); - encode.string(&self.description); - encode.int32(self.duration); - encode.int64(self.highest_bid); - encode.agent_id(&self.highest_bidder); - encode.int64(self.minimum_bid); - encode.int64(self.num_tokens); - encode.int64(self.owner_margin); - encode.int64(self.when_started); - return encode.data(); + let mut enc = WasmEncoder::new(); + color_encode(&mut enc, &self.color); + agent_id_encode(&mut enc, &self.creator); + uint64_encode(&mut enc, self.deposit); + string_encode(&mut enc, &self.description); + uint32_encode(&mut enc, self.duration); + uint64_encode(&mut enc, self.highest_bid); + agent_id_encode(&mut enc, &self.highest_bidder); + uint64_encode(&mut enc, self.minimum_bid); + uint64_encode(&mut enc, self.num_tokens); + uint64_encode(&mut enc, self.owner_margin); + uint64_encode(&mut enc, self.when_started); + enc.buf() } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableAuction { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl ImmutableAuction { pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn value(&self) -> Auction { - Auction::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Auction::from_bytes(&self.proxy.get()) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableAuction { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl MutableAuction { pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn set_value(&self, value: &Auction) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } pub fn value(&self) -> Auction { - Auction::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Auction::from_bytes(&self.proxy.get()) } } #[derive(Clone)] pub struct Bid { - pub amount : i64, // cumulative amount of bids from same bidder - pub index : i32, // index of bidder in bidder list - pub timestamp : i64, // timestamp of most recent bid + pub amount : u64, // cumulative amount of bids from same bidder + pub index : u32, // index of bidder in bidder list + pub timestamp : u64, // timestamp of most recent bid } impl Bid { pub fn from_bytes(bytes: &[u8]) -> Bid { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); Bid { - amount : decode.int64(), - index : decode.int32(), - timestamp : decode.int64(), + amount : uint64_decode(&mut dec), + index : uint32_decode(&mut dec), + timestamp : uint64_decode(&mut dec), } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.int64(self.amount); - encode.int32(self.index); - encode.int64(self.timestamp); - return encode.data(); + let mut enc = WasmEncoder::new(); + uint64_encode(&mut enc, self.amount); + uint32_encode(&mut enc, self.index); + uint64_encode(&mut enc, self.timestamp); + enc.buf() } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBid { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl ImmutableBid { pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn value(&self) -> Bid { - Bid::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Bid::from_bytes(&self.proxy.get()) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBid { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl MutableBid { pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn set_value(&self, value: &Bid) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } pub fn value(&self) -> Bid { - Bid::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Bid::from_bytes(&self.proxy.get()) } } diff --git a/contracts/wasm/fairauction/src/typedefs.rs b/contracts/wasm/fairauction/src/typedefs.rs index 83938d4385..c9ce72b805 100644 --- a/contracts/wasm/fairauction/src/typedefs.rs +++ b/contracts/wasm/fairauction/src/typedefs.rs @@ -8,72 +8,75 @@ #![allow(dead_code)] use wasmlib::*; -use wasmlib::host::*; -use crate::structs::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableAgentID { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableAgentID { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_agent_id(&self, index: i32) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.obj_id, Key32(index)) + pub fn get_agent_id(&self, index: u32) -> ScImmutableAgentID { + ScImmutableAgentID::new(self.proxy.index(index)) } } pub type ImmutableBidderList = ArrayOfImmutableAgentID; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableAgentID { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableAgentID { - pub fn clear(&self) { - clear(self.obj_id); + pub fn append_agent_id(&self) -> ScMutableAgentID { + ScMutableAgentID::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_agent_id(&self, index: i32) -> ScMutableAgentID { - ScMutableAgentID::new(self.obj_id, Key32(index)) + pub fn get_agent_id(&self, index: u32) -> ScMutableAgentID { + ScMutableAgentID::new(self.proxy.index(index)) } } pub type MutableBidderList = ArrayOfMutableAgentID; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableBid { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableBid { pub fn get_bid(&self, key: &ScAgentID) -> ImmutableBid { - ImmutableBid { obj_id: self.obj_id, key_id: key.get_key_id() } + ImmutableBid { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } pub type ImmutableBids = MapAgentIDToImmutableBid; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableBid { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableBid { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bid(&self, key: &ScAgentID) -> MutableBid { - MutableBid { obj_id: self.obj_id, key_id: key.get_key_id() } + MutableBid { proxy: self.proxy.key(&agent_id_to_bytes(key)) } } } diff --git a/contracts/wasm/fairauction/test/fairauction_bg.wasm b/contracts/wasm/fairauction/test/fairauction_bg.wasm index e2ded07e63..edb7f27971 100644 Binary files a/contracts/wasm/fairauction/test/fairauction_bg.wasm and b/contracts/wasm/fairauction/test/fairauction_bg.wasm differ diff --git a/contracts/wasm/fairauction/test/fairauction_test.go b/contracts/wasm/fairauction/test/fairauction_test.go index 389ea409ad..b4efe52675 100644 --- a/contracts/wasm/fairauction/test/fairauction_test.go +++ b/contracts/wasm/fairauction/test/fairauction_test.go @@ -9,14 +9,14 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/fairauction/go/fairauction" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) var ( auctioneer *wasmsolo.SoloAgent - tokenColor wasmlib.ScColor + tokenColor wasmtypes.ScColor ) func startAuction(t *testing.T) *wasmsolo.SoloContext { @@ -35,8 +35,8 @@ func startAuction(t *testing.T) *wasmsolo.SoloContext { sa.Params.MinimumBid().SetValue(500) sa.Params.Description().SetValue("Cool tokens for sale!") transfer := ctx.Transfer() - transfer.Set(wasmlib.IOTA, 25) // deposit, must be >=minimum*margin - transfer.Set(tokenColor, 10) // the tokens to auction + transfer.Set(wasmtypes.IOTA, 25) // deposit, must be >=minimum*margin + transfer.Set(tokenColor, 10) // the tokens to auction sa.Func.Transfer(transfer).Post() require.NoError(t, ctx.Err) return ctx @@ -97,7 +97,6 @@ func TestFaNoBids(t *testing.T) { func TestFaOneBidTooLow(t *testing.T) { ctx := startAuction(t) - chain := ctx.Chain bidder := ctx.NewSoloAgent() placeBid := fairauction.ScFuncs.PlaceBid(ctx.Sign(bidder)) @@ -105,9 +104,15 @@ func TestFaOneBidTooLow(t *testing.T) { placeBid.Func.TransferIotas(100).Post() require.Error(t, ctx.Err) + // TODO this should be a simple 1 request to wait for, but sometimes + // the finalizeAuction will have already been triggered (bug), so + // instead of waiting for that single finalizeAuction request we + // will (erroneously) wait for the inbuf and outbuf counts to equalize + info := ctx.Chain.MempoolInfo() + // wait for finalize_auction - chain.Env.AdvanceClockBy(61 * time.Minute) - require.True(t, ctx.WaitForPendingRequests(1)) + ctx.AdvanceClockBy(61 * time.Minute) + require.True(t, ctx.WaitForPendingRequests(-info.InBufCounter)) getInfo := fairauction.ScFuncs.GetInfo(ctx) getInfo.Params.Color().SetValue(tokenColor) @@ -115,22 +120,27 @@ func TestFaOneBidTooLow(t *testing.T) { require.NoError(t, ctx.Err) require.EqualValues(t, 0, getInfo.Results.Bidders().Value()) - require.EqualValues(t, -1, getInfo.Results.HighestBid().Value()) + require.EqualValues(t, 0, getInfo.Results.HighestBid().Value()) } func TestFaOneBid(t *testing.T) { ctx := startAuction(t) - chain := ctx.Chain bidder := ctx.NewSoloAgent() placeBid := fairauction.ScFuncs.PlaceBid(ctx.Sign(bidder)) placeBid.Params.Color().SetValue(tokenColor) - placeBid.Func.TransferIotas(500).Post() + placeBid.Func.TransferIotas(5000).Post() require.NoError(t, ctx.Err) + // TODO this should be a simple 1 request to wait for, but sometimes + // the finalizeAuction will have already been triggered (bug), so + // instead of waiting for that single finalizeAuction request we + // will (erroneously) wait for the inbuf and outbuf counts to equalize + info := ctx.Chain.MempoolInfo() + // wait for finalize_auction - chain.Env.AdvanceClockBy(61 * time.Minute) - require.True(t, ctx.WaitForPendingRequests(1)) + ctx.AdvanceClockBy(61 * time.Minute) + require.True(t, ctx.WaitForPendingRequests(-info.InBufCounter)) getInfo := fairauction.ScFuncs.GetInfo(ctx) getInfo.Params.Color().SetValue(tokenColor) @@ -138,6 +148,6 @@ func TestFaOneBid(t *testing.T) { require.NoError(t, ctx.Err) require.EqualValues(t, 1, getInfo.Results.Bidders().Value()) - require.EqualValues(t, 500, getInfo.Results.HighestBid().Value()) + require.EqualValues(t, 5000, getInfo.Results.HighestBid().Value()) require.Equal(t, bidder.ScAddress().AsAgentID(), getInfo.Results.HighestBidder().Value()) } diff --git a/contracts/wasm/fairauction/ts/fairauction/consts.ts b/contracts/wasm/fairauction/ts/fairauction/consts.ts index e4b544c88d..da2894b4cc 100644 --- a/contracts/wasm/fairauction/ts/fairauction/consts.ts +++ b/contracts/wasm/fairauction/ts/fairauction/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "fairauction"; export const ScDescription = "Decentralized auction to securely sell tokens to the highest bidder"; -export const HScName = new wasmlib.ScHname(0x1b5c43b1); +export const HScName = new wasmtypes.ScHname(0x1b5c43b1); export const ParamColor = "color"; export const ParamDescription = "description"; @@ -41,8 +41,8 @@ export const FuncSetOwnerMargin = "setOwnerMargin"; export const FuncStartAuction = "startAuction"; export const ViewGetInfo = "getInfo"; -export const HFuncFinalizeAuction = new wasmlib.ScHname(0x8d534ddc); -export const HFuncPlaceBid = new wasmlib.ScHname(0x9bd72fa9); -export const HFuncSetOwnerMargin = new wasmlib.ScHname(0x1774461a); -export const HFuncStartAuction = new wasmlib.ScHname(0xd5b7bacb); -export const HViewGetInfo = new wasmlib.ScHname(0xcfedba5f); +export const HFuncFinalizeAuction = new wasmtypes.ScHname(0x8d534ddc); +export const HFuncPlaceBid = new wasmtypes.ScHname(0x9bd72fa9); +export const HFuncSetOwnerMargin = new wasmtypes.ScHname(0x1774461a); +export const HFuncStartAuction = new wasmtypes.ScHname(0xd5b7bacb); +export const HViewGetInfo = new wasmtypes.ScHname(0xcfedba5f); diff --git a/contracts/wasm/fairauction/ts/fairauction/contract.ts b/contracts/wasm/fairauction/ts/fairauction/contract.ts index 56b06394f3..643489772f 100644 --- a/contracts/wasm/fairauction/ts/fairauction/contract.ts +++ b/contracts/wasm/fairauction/ts/fairauction/contract.ts @@ -10,84 +10,85 @@ import * as sc from "./index"; export class FinalizeAuctionCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncFinalizeAuction); - params: sc.MutableFinalizeAuctionParams = new sc.MutableFinalizeAuctionParams(); + params: sc.MutableFinalizeAuctionParams = new sc.MutableFinalizeAuctionParams(wasmlib.ScView.nilProxy); } export class FinalizeAuctionContext { - params: sc.ImmutableFinalizeAuctionParams = new sc.ImmutableFinalizeAuctionParams(); - state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(); + params: sc.ImmutableFinalizeAuctionParams = new sc.ImmutableFinalizeAuctionParams(wasmlib.paramsProxy()); + state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(wasmlib.ScState.proxy()); } export class PlaceBidCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncPlaceBid); - params: sc.MutablePlaceBidParams = new sc.MutablePlaceBidParams(); + params: sc.MutablePlaceBidParams = new sc.MutablePlaceBidParams(wasmlib.ScView.nilProxy); } export class PlaceBidContext { - params: sc.ImmutablePlaceBidParams = new sc.ImmutablePlaceBidParams(); - state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(); + params: sc.ImmutablePlaceBidParams = new sc.ImmutablePlaceBidParams(wasmlib.paramsProxy()); + state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(wasmlib.ScState.proxy()); } export class SetOwnerMarginCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetOwnerMargin); - params: sc.MutableSetOwnerMarginParams = new sc.MutableSetOwnerMarginParams(); + params: sc.MutableSetOwnerMarginParams = new sc.MutableSetOwnerMarginParams(wasmlib.ScView.nilProxy); } export class SetOwnerMarginContext { - params: sc.ImmutableSetOwnerMarginParams = new sc.ImmutableSetOwnerMarginParams(); - state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(); + params: sc.ImmutableSetOwnerMarginParams = new sc.ImmutableSetOwnerMarginParams(wasmlib.paramsProxy()); + state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(wasmlib.ScState.proxy()); } export class StartAuctionCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncStartAuction); - params: sc.MutableStartAuctionParams = new sc.MutableStartAuctionParams(); + params: sc.MutableStartAuctionParams = new sc.MutableStartAuctionParams(wasmlib.ScView.nilProxy); } export class StartAuctionContext { - params: sc.ImmutableStartAuctionParams = new sc.ImmutableStartAuctionParams(); - state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(); + params: sc.ImmutableStartAuctionParams = new sc.ImmutableStartAuctionParams(wasmlib.paramsProxy()); + state: sc.MutableFairAuctionState = new sc.MutableFairAuctionState(wasmlib.ScState.proxy()); } export class GetInfoCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetInfo); - params: sc.MutableGetInfoParams = new sc.MutableGetInfoParams(); - results: sc.ImmutableGetInfoResults = new sc.ImmutableGetInfoResults(); + params: sc.MutableGetInfoParams = new sc.MutableGetInfoParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetInfoResults = new sc.ImmutableGetInfoResults(wasmlib.ScView.nilProxy); } export class GetInfoContext { - params: sc.ImmutableGetInfoParams = new sc.ImmutableGetInfoParams(); - results: sc.MutableGetInfoResults = new sc.MutableGetInfoResults(); - state: sc.ImmutableFairAuctionState = new sc.ImmutableFairAuctionState(); + params: sc.ImmutableGetInfoParams = new sc.ImmutableGetInfoParams(wasmlib.paramsProxy()); + results: sc.MutableGetInfoResults = new sc.MutableGetInfoResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableFairAuctionState = new sc.ImmutableFairAuctionState(wasmlib.ScState.proxy()); } export class ScFuncs { - static finalizeAuction(ctx: wasmlib.ScFuncCallContext): FinalizeAuctionCall { - let f = new FinalizeAuctionCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static placeBid(ctx: wasmlib.ScFuncCallContext): PlaceBidCall { - let f = new PlaceBidCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setOwnerMargin(ctx: wasmlib.ScFuncCallContext): SetOwnerMarginCall { - let f = new SetOwnerMarginCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static startAuction(ctx: wasmlib.ScFuncCallContext): StartAuctionCall { - let f = new StartAuctionCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static getInfo(ctx: wasmlib.ScViewCallContext): GetInfoCall { - let f = new GetInfoCall(); - f.func.setPtrs(f.params, f.results); - return f; - } + static finalizeAuction(_ctx: wasmlib.ScFuncCallContext): FinalizeAuctionCall { + const f = new FinalizeAuctionCall(); + f.params = new sc.MutableFinalizeAuctionParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static placeBid(_ctx: wasmlib.ScFuncCallContext): PlaceBidCall { + const f = new PlaceBidCall(); + f.params = new sc.MutablePlaceBidParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setOwnerMargin(_ctx: wasmlib.ScFuncCallContext): SetOwnerMarginCall { + const f = new SetOwnerMarginCall(); + f.params = new sc.MutableSetOwnerMarginParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static startAuction(_ctx: wasmlib.ScFuncCallContext): StartAuctionCall { + const f = new StartAuctionCall(); + f.params = new sc.MutableStartAuctionParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static getInfo(_ctx: wasmlib.ScViewCallContext): GetInfoCall { + const f = new GetInfoCall(); + f.params = new sc.MutableGetInfoParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/fairauction/ts/fairauction/fairauction.ts b/contracts/wasm/fairauction/ts/fairauction/fairauction.ts index 936a50dddc..8f3e31efca 100644 --- a/contracts/wasm/fairauction/ts/fairauction/fairauction.ts +++ b/contracts/wasm/fairauction/ts/fairauction/fairauction.ts @@ -2,31 +2,32 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -const DURATION_DEFAULT: i32 = 60; -const DURATION_MIN: i32 = 1; -const DURATION_MAX: i32 = 120; +const DURATION_DEFAULT: u32 = 60; +const DURATION_MIN: u32 = 1; +const DURATION_MAX: u32 = 120; const MAX_DESCRIPTION_LENGTH: i32 = 150; -const OWNER_MARGIN_DEFAULT: i64 = 50; -const OWNER_MARGIN_MIN: i64 = 5; -const OWNER_MARGIN_MAX: i64 = 100; +const OWNER_MARGIN_DEFAULT: u64 = 50; +const OWNER_MARGIN_MIN: u64 = 5; +const OWNER_MARGIN_MAX: u64 = 100; export function funcFinalizeAuction(ctx: wasmlib.ScFuncContext, f: sc.FinalizeAuctionContext): void { let color = f.params.color().value(); let currentAuction = f.state.auctions().getAuction(color); ctx.require(currentAuction.exists(), "Missing auction info"); let auction = currentAuction.value(); - if (auction.highestBid < 0) { + if (auction.highestBid == 0) { ctx.log("No one bid on " + color.toString()); let ownerFee = auction.minimumBid * auction.ownerMargin / 1000; if (ownerFee == 0) { ownerFee = 1; } // finalizeAuction request token was probably not confirmed yet - transferTokens(ctx, ctx.contractCreator(), wasmlib.ScColor.IOTA, ownerFee - 1); + transferTokens(ctx, ctx.contractCreator(), wasmtypes.IOTA, ownerFee - 1); transferTokens(ctx, auction.creator, auction.color, auction.numTokens); - transferTokens(ctx, auction.creator, wasmlib.ScColor.IOTA, auction.deposit - ownerFee); + transferTokens(ctx, auction.creator, wasmtypes.IOTA, auction.deposit - ownerFee); return; } @@ -39,22 +40,22 @@ export function funcFinalizeAuction(ctx: wasmlib.ScFuncContext, f: sc.FinalizeAu let bids = f.state.bids().getBids(color); let bidderList = f.state.bidderList().getBidderList(color); let size = bidderList.length(); - for (let i = 0; i < size; i++) { + for (let i: u32 = 0; i < size; i++) { let loser = bidderList.getAgentID(i).value(); - if (loser != auction.highestBidder) { + if (!loser.equals(auction.highestBidder)) { let bid = bids.getBid(loser).value(); - transferTokens(ctx, loser, wasmlib.ScColor.IOTA, bid.amount); + transferTokens(ctx, loser, wasmtypes.IOTA, bid.amount); } } // finalizeAuction request token was probably not confirmed yet - transferTokens(ctx, ctx.contractCreator(), wasmlib.ScColor.IOTA, ownerFee - 1); + transferTokens(ctx, ctx.contractCreator(), wasmtypes.IOTA, ownerFee - 1); transferTokens(ctx, auction.highestBidder, auction.color, auction.numTokens); - transferTokens(ctx, auction.creator, wasmlib.ScColor.IOTA, auction.deposit + auction.highestBid - ownerFee); + transferTokens(ctx, auction.creator, wasmtypes.IOTA, auction.deposit + auction.highestBid - ownerFee); } export function funcPlaceBid(ctx: wasmlib.ScFuncContext, f: sc.PlaceBidContext): void { - let bidAmount = ctx.incoming().balance(wasmlib.ScColor.IOTA); + let bidAmount = ctx.incoming().balance(wasmtypes.IOTA); ctx.require(bidAmount > 0, "Missing bid amount"); let color = f.params.color().value(); @@ -77,7 +78,7 @@ export function funcPlaceBid(ctx: wasmlib.ScFuncContext, f: sc.PlaceBidContext): ctx.require(bidAmount >= auction.minimumBid, "Insufficient bid amount"); ctx.log("New bid from: " + caller.toString()); let index = bidderList.length(); - bidderList.getAgentID(index).setValue(caller); + bidderList.appendAgentID().setValue(caller); let bid = new sc.Bid(); bid.index = index; bid.amount = bidAmount; @@ -105,7 +106,7 @@ export function funcSetOwnerMargin(ctx: wasmlib.ScFuncContext, f: sc.SetOwnerMar export function funcStartAuction(ctx: wasmlib.ScFuncContext, f: sc.StartAuctionContext): void { let color = f.params.color().value(); - if (color == wasmlib.ScColor.IOTA || color == wasmlib.ScColor.MINT) { + if (color == wasmtypes.IOTA || color == wasmtypes.MINT) { ctx.panic("Reserved auction token color"); } let numTokens = ctx.incoming().balance(color); @@ -145,7 +146,7 @@ export function funcStartAuction(ctx: wasmlib.ScFuncContext, f: sc.StartAuctionC if (margin == 0) { margin = 1; } - let deposit = ctx.incoming().balance(wasmlib.ScColor.IOTA); + let deposit = ctx.incoming().balance(wasmtypes.IOTA); if (deposit < margin) { ctx.panic("Insufficient deposit"); } @@ -161,8 +162,8 @@ export function funcStartAuction(ctx: wasmlib.ScFuncContext, f: sc.StartAuctionC auction.deposit = deposit; auction.description = description; auction.duration = duration; - auction.highestBid = -1; - auction.highestBidder = new wasmlib.ScAgentID(); + auction.highestBid = 0; + auction.highestBidder = wasmtypes.agentIDFromBytes([]); auction.minimumBid = minimumBid; auction.numTokens = numTokens; auction.ownerMargin = ownerMargin; @@ -171,7 +172,7 @@ export function funcStartAuction(ctx: wasmlib.ScFuncContext, f: sc.StartAuctionC let fa = sc.ScFuncs.finalizeAuction(ctx); fa.params.color().setValue(auction.color); - fa.func.delay(duration * 60).transferIotas(1).post(); + fa.func.delay(duration * 60).post(); } export function viewGetInfo(ctx: wasmlib.ScViewContext, f: sc.GetInfoContext): void { @@ -199,10 +200,10 @@ export function viewGetInfo(ctx: wasmlib.ScViewContext, f: sc.GetInfoContext): v function transferTokens(ctx: wasmlib.ScFuncContext, agent: wasmlib.ScAgentID, color: wasmlib.ScColor, amount: i64): void { if (agent.isAddress()) { // send back to original Tangle address - ctx.transferToAddress(agent.address(), wasmlib.ScTransfers.transfer(color, amount)); + ctx.send(agent.address(), wasmlib.ScTransfers.transfer(color, amount)); return; } // TODO not an address, deposit into account on chain - ctx.transferToAddress(agent.address(), wasmlib.ScTransfers.transfer(color, amount)); + ctx.send(agent.address(), wasmlib.ScTransfers.transfer(color, amount)); } diff --git a/contracts/wasm/fairauction/ts/fairauction/index.ts b/contracts/wasm/fairauction/ts/fairauction/index.ts index e8011fbe09..f4705cc7cf 100644 --- a/contracts/wasm/fairauction/ts/fairauction/index.ts +++ b/contracts/wasm/fairauction/ts/fairauction/index.ts @@ -9,7 +9,6 @@ export * from "./fairauction"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/fairauction/ts/fairauction/keys.ts b/contracts/wasm/fairauction/ts/fairauction/keys.ts deleted file mode 100644 index b4d09d3c3a..0000000000 --- a/contracts/wasm/fairauction/ts/fairauction/keys.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamColor = 0; -export const IdxParamDescription = 1; -export const IdxParamDuration = 2; -export const IdxParamMinimumBid = 3; -export const IdxParamOwnerMargin = 4; - -export const IdxResultBidders = 5; -export const IdxResultColor = 6; -export const IdxResultCreator = 7; -export const IdxResultDeposit = 8; -export const IdxResultDescription = 9; -export const IdxResultDuration = 10; -export const IdxResultHighestBid = 11; -export const IdxResultHighestBidder = 12; -export const IdxResultMinimumBid = 13; -export const IdxResultNumTokens = 14; -export const IdxResultOwnerMargin = 15; -export const IdxResultWhenStarted = 16; - -export const IdxStateAuctions = 17; -export const IdxStateBidderList = 18; -export const IdxStateBids = 19; -export const IdxStateOwnerMargin = 20; - -export let keyMap: string[] = [ - sc.ParamColor, - sc.ParamDescription, - sc.ParamDuration, - sc.ParamMinimumBid, - sc.ParamOwnerMargin, - sc.ResultBidders, - sc.ResultColor, - sc.ResultCreator, - sc.ResultDeposit, - sc.ResultDescription, - sc.ResultDuration, - sc.ResultHighestBid, - sc.ResultHighestBidder, - sc.ResultMinimumBid, - sc.ResultNumTokens, - sc.ResultOwnerMargin, - sc.ResultWhenStarted, - sc.StateAuctions, - sc.StateBidderList, - sc.StateBids, - sc.StateOwnerMargin, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/fairauction/ts/fairauction/lib.ts b/contracts/wasm/fairauction/ts/fairauction/lib.ts index 2f7ea11525..f465d4cc3e 100644 --- a/contracts/wasm/fairauction/ts/fairauction/lib.ts +++ b/contracts/wasm/fairauction/ts/fairauction/lib.ts @@ -8,32 +8,40 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncFinalizeAuction, + sc.FuncPlaceBid, + sc.FuncSetOwnerMargin, + sc.FuncStartAuction, + sc.ViewGetInfo, + ], + funcs: [ + funcFinalizeAuctionThunk, + funcPlaceBidThunk, + funcSetOwnerMarginThunk, + funcStartAuctionThunk, + ], + views: [ + viewGetInfoThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncFinalizeAuction, funcFinalizeAuctionThunk); - exports.addFunc(sc.FuncPlaceBid, funcPlaceBidThunk); - exports.addFunc(sc.FuncSetOwnerMargin, funcSetOwnerMarginThunk); - exports.addFunc(sc.FuncStartAuction, funcStartAuctionThunk); - exports.addView(sc.ViewGetInfo, viewGetInfoThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcFinalizeAuctionThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairauction.funcFinalizeAuction"); + let f = new sc.FinalizeAuctionContext(); // only SC itself can invoke this function ctx.require(ctx.caller().equals(ctx.accountID()), "no permission"); - let f = new sc.FinalizeAuctionContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); sc.funcFinalizeAuction(ctx, f); ctx.log("fairauction.funcFinalizeAuction ok"); @@ -42,8 +50,6 @@ function funcFinalizeAuctionThunk(ctx: wasmlib.ScFuncContext): void { function funcPlaceBidThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairauction.funcPlaceBid"); let f = new sc.PlaceBidContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); sc.funcPlaceBid(ctx, f); ctx.log("fairauction.funcPlaceBid ok"); @@ -51,13 +57,11 @@ function funcPlaceBidThunk(ctx: wasmlib.ScFuncContext): void { function funcSetOwnerMarginThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairauction.funcSetOwnerMargin"); + let f = new sc.SetOwnerMarginContext(); // only SC creator can set owner margin ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.SetOwnerMarginContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.ownerMargin().exists(), "missing mandatory ownerMargin"); sc.funcSetOwnerMargin(ctx, f); ctx.log("fairauction.funcSetOwnerMargin ok"); @@ -66,8 +70,6 @@ function funcSetOwnerMarginThunk(ctx: wasmlib.ScFuncContext): void { function funcStartAuctionThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairauction.funcStartAuction"); let f = new sc.StartAuctionContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); ctx.require(f.params.minimumBid().exists(), "missing mandatory minimumBid"); sc.funcStartAuction(ctx, f); @@ -77,10 +79,10 @@ function funcStartAuctionThunk(ctx: wasmlib.ScFuncContext): void { function viewGetInfoThunk(ctx: wasmlib.ScViewContext): void { ctx.log("fairauction.viewGetInfo"); let f = new sc.GetInfoContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetInfoResults(results.asProxy()); ctx.require(f.params.color().exists(), "missing mandatory color"); sc.viewGetInfo(ctx, f); + ctx.results(results); ctx.log("fairauction.viewGetInfo ok"); } diff --git a/contracts/wasm/fairauction/ts/fairauction/params.ts b/contracts/wasm/fairauction/ts/fairauction/params.ts index ee3ad774c6..42400d05b3 100644 --- a/contracts/wasm/fairauction/ts/fairauction/params.ts +++ b/contracts/wasm/fairauction/ts/fairauction/params.ts @@ -5,89 +5,89 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableFinalizeAuctionParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableFinalizeAuctionParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutableFinalizeAuctionParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableFinalizeAuctionParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } -export class ImmutablePlaceBidParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutablePlaceBidParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutablePlaceBidParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutablePlaceBidParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } -export class ImmutableSetOwnerMarginParams extends wasmlib.ScMapID { - ownerMargin(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerMargin)); +export class ImmutableSetOwnerMarginParams extends wasmtypes.ScProxy { + ownerMargin(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamOwnerMargin)); } } -export class MutableSetOwnerMarginParams extends wasmlib.ScMapID { - ownerMargin(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerMargin)); +export class MutableSetOwnerMarginParams extends wasmtypes.ScProxy { + ownerMargin(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamOwnerMargin)); } } -export class ImmutableStartAuctionParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableStartAuctionParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } - description(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); + description(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamDescription)); } - duration(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamDuration)); + duration(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamDuration)); } - minimumBid(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamMinimumBid)); + minimumBid(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamMinimumBid)); } } -export class MutableStartAuctionParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableStartAuctionParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } - description(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); + description(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamDescription)); } - duration(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamDuration)); + duration(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamDuration)); } - minimumBid(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamMinimumBid)); + minimumBid(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamMinimumBid)); } } -export class ImmutableGetInfoParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableGetInfoParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutableGetInfoParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableGetInfoParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } diff --git a/contracts/wasm/fairauction/ts/fairauction/results.ts b/contracts/wasm/fairauction/ts/fairauction/results.ts index 659f739093..978c34f919 100644 --- a/contracts/wasm/fairauction/ts/fairauction/results.ts +++ b/contracts/wasm/fairauction/ts/fairauction/results.ts @@ -5,105 +5,105 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableGetInfoResults extends wasmlib.ScMapID { - bidders(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBidders)); +export class ImmutableGetInfoResults extends wasmtypes.ScProxy { + bidders(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultBidders)); } - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultColor)); + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ResultColor)); } - creator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultCreator)); + creator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultCreator)); } - deposit(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDeposit)); + deposit(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultDeposit)); } - description(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultDescription)); + description(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultDescription)); } - duration(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultDuration)); + duration(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultDuration)); } - highestBid(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultHighestBid)); + highestBid(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultHighestBid)); } - highestBidder(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultHighestBidder)); + highestBidder(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultHighestBidder)); } - minimumBid(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMinimumBid)); + minimumBid(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultMinimumBid)); } - numTokens(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultNumTokens)); + numTokens(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultNumTokens)); } - ownerMargin(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultOwnerMargin)); + ownerMargin(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultOwnerMargin)); } - whenStarted(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultWhenStarted)); + whenStarted(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultWhenStarted)); } } -export class MutableGetInfoResults extends wasmlib.ScMapID { - bidders(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBidders)); +export class MutableGetInfoResults extends wasmtypes.ScProxy { + bidders(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultBidders)); } - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultColor)); + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ResultColor)); } - creator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultCreator)); + creator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultCreator)); } - deposit(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDeposit)); + deposit(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultDeposit)); } - description(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultDescription)); + description(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultDescription)); } - duration(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultDuration)); + duration(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultDuration)); } - highestBid(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultHighestBid)); + highestBid(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultHighestBid)); } - highestBidder(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultHighestBidder)); + highestBidder(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultHighestBidder)); } - minimumBid(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMinimumBid)); + minimumBid(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultMinimumBid)); } - numTokens(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultNumTokens)); + numTokens(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultNumTokens)); } - ownerMargin(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultOwnerMargin)); + ownerMargin(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultOwnerMargin)); } - whenStarted(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultWhenStarted)); + whenStarted(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultWhenStarted)); } } diff --git a/contracts/wasm/fairauction/ts/fairauction/state.ts b/contracts/wasm/fairauction/ts/fairauction/state.ts index 5c87258728..ff51404fc2 100644 --- a/contracts/wasm/fairauction/ts/fairauction/state.ts +++ b/contracts/wasm/fairauction/ts/fairauction/state.ts @@ -5,141 +5,99 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapColorToImmutableAuction { - objID: i32; +export class MapColorToImmutableAuction extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getAuction(key: wasmlib.ScColor): sc.ImmutableAuction { - return new sc.ImmutableAuction(this.objID, key.getKeyID()); - } + getAuction(key: wasmtypes.ScColor): sc.ImmutableAuction { + return new sc.ImmutableAuction(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MapColorToImmutableBidderList { - objID: i32; +export class MapColorToImmutableBidderList extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getBidderList(key: wasmlib.ScColor): sc.ImmutableBidderList { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_AGENT_ID); - return new sc.ImmutableBidderList(subID); - } + getBidderList(key: wasmtypes.ScColor): sc.ImmutableBidderList { + return new sc.ImmutableBidderList(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MapColorToImmutableBids { - objID: i32; +export class MapColorToImmutableBids extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getBids(key: wasmlib.ScColor): sc.ImmutableBids { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.ImmutableBids(subID); - } + getBids(key: wasmtypes.ScColor): sc.ImmutableBids { + return new sc.ImmutableBids(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class ImmutableFairAuctionState extends wasmlib.ScMapID { - auctions(): sc.MapColorToImmutableAuction { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateAuctions), wasmlib.TYPE_MAP); - return new sc.MapColorToImmutableAuction(mapID); +export class ImmutableFairAuctionState extends wasmtypes.ScProxy { + auctions(): sc.MapColorToImmutableAuction { + return new sc.MapColorToImmutableAuction(this.proxy.root(sc.StateAuctions)); } - bidderList(): sc.MapColorToImmutableBidderList { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBidderList), wasmlib.TYPE_MAP); - return new sc.MapColorToImmutableBidderList(mapID); + bidderList(): sc.MapColorToImmutableBidderList { + return new sc.MapColorToImmutableBidderList(this.proxy.root(sc.StateBidderList)); } - bids(): sc.MapColorToImmutableBids { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBids), wasmlib.TYPE_MAP); - return new sc.MapColorToImmutableBids(mapID); + bids(): sc.MapColorToImmutableBids { + return new sc.MapColorToImmutableBids(this.proxy.root(sc.StateBids)); } - ownerMargin(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateOwnerMargin)); + ownerMargin(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateOwnerMargin)); } } -export class MapColorToMutableAuction { - objID: i32; +export class MapColorToMutableAuction extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getAuction(key: wasmlib.ScColor): sc.MutableAuction { - return new sc.MutableAuction(this.objID, key.getKeyID()); - } + getAuction(key: wasmtypes.ScColor): sc.MutableAuction { + return new sc.MutableAuction(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MapColorToMutableBidderList { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapColorToMutableBidderList extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getBidderList(key: wasmlib.ScColor): sc.MutableBidderList { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_AGENT_ID); - return new sc.MutableBidderList(subID); - } + getBidderList(key: wasmtypes.ScColor): sc.MutableBidderList { + return new sc.MutableBidderList(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MapColorToMutableBids { - objID: i32; +export class MapColorToMutableBids extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getBids(key: wasmlib.ScColor): sc.MutableBids { - let subID = wasmlib.getObjectID(this.objID, key.getKeyID(), wasmlib.TYPE_MAP); - return new sc.MutableBids(subID); - } + getBids(key: wasmtypes.ScColor): sc.MutableBids { + return new sc.MutableBids(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MutableFairAuctionState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableFairAuctionState { - const imm = new sc.ImmutableFairAuctionState(); - imm.mapID = this.mapID; - return imm; +export class MutableFairAuctionState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableFairAuctionState { + return new sc.ImmutableFairAuctionState(this.proxy); } - auctions(): sc.MapColorToMutableAuction { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateAuctions), wasmlib.TYPE_MAP); - return new sc.MapColorToMutableAuction(mapID); + auctions(): sc.MapColorToMutableAuction { + return new sc.MapColorToMutableAuction(this.proxy.root(sc.StateAuctions)); } - bidderList(): sc.MapColorToMutableBidderList { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBidderList), wasmlib.TYPE_MAP); - return new sc.MapColorToMutableBidderList(mapID); + bidderList(): sc.MapColorToMutableBidderList { + return new sc.MapColorToMutableBidderList(this.proxy.root(sc.StateBidderList)); } - bids(): sc.MapColorToMutableBids { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBids), wasmlib.TYPE_MAP); - return new sc.MapColorToMutableBids(mapID); + bids(): sc.MapColorToMutableBids { + return new sc.MapColorToMutableBids(this.proxy.root(sc.StateBids)); } - ownerMargin(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateOwnerMargin)); + ownerMargin(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateOwnerMargin)); } } diff --git a/contracts/wasm/fairauction/ts/fairauction/structs.ts b/contracts/wasm/fairauction/ts/fairauction/structs.ts index 2325e38180..eab976f668 100644 --- a/contracts/wasm/fairauction/ts/fairauction/structs.ts +++ b/contracts/wasm/fairauction/ts/fairauction/structs.ts @@ -5,164 +5,136 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Auction { - color : wasmlib.ScColor = new wasmlib.ScColor(0); // color of tokens for sale - creator : wasmlib.ScAgentID = new wasmlib.ScAgentID(); // issuer of start_auction transaction - deposit : i64 = 0; // deposit by auction owner to cover the SC fees - description : string = ""; // auction description - duration : i32 = 0; // auction duration in minutes - highestBid : i64 = 0; // the current highest bid amount - highestBidder : wasmlib.ScAgentID = new wasmlib.ScAgentID(); // the current highest bidder - minimumBid : i64 = 0; // minimum bid amount - numTokens : i64 = 0; // number of tokens for sale - ownerMargin : i64 = 0; // auction owner's margin in promilles - whenStarted : i64 = 0; // timestamp when auction started - - static fromBytes(bytes: u8[]): Auction { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Auction(); - data.color = decode.color(); - data.creator = decode.agentID(); - data.deposit = decode.int64(); - data.description = decode.string(); - data.duration = decode.int32(); - data.highestBid = decode.int64(); - data.highestBidder = decode.agentID(); - data.minimumBid = decode.int64(); - data.numTokens = decode.int64(); - data.ownerMargin = decode.int64(); - data.whenStarted = decode.int64(); - decode.close(); - return data; - } - - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - color(this.color). - agentID(this.creator). - int64(this.deposit). - string(this.description). - int32(this.duration). - int64(this.highestBid). - agentID(this.highestBidder). - int64(this.minimumBid). - int64(this.numTokens). - int64(this.ownerMargin). - int64(this.whenStarted). - data(); - } + color : wasmtypes.ScColor = new wasmtypes.ScColor(0); // color of tokens for sale + creator : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); // issuer of start_auction transaction + deposit : u64 = 0; // deposit by auction owner to cover the SC fees + description : string = ""; // auction description + duration : u32 = 0; // auction duration in minutes + highestBid : u64 = 0; // the current highest bid amount + highestBidder : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); // the current highest bidder + minimumBid : u64 = 0; // minimum bid amount + numTokens : u64 = 0; // number of tokens for sale + ownerMargin : u64 = 0; // auction owner's margin in promilles + whenStarted : u64 = 0; // timestamp when auction started + + static fromBytes(buf: u8[]): Auction { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new Auction(); + data.color = wasmtypes.colorDecode(dec); + data.creator = wasmtypes.agentIDDecode(dec); + data.deposit = wasmtypes.uint64Decode(dec); + data.description = wasmtypes.stringDecode(dec); + data.duration = wasmtypes.uint32Decode(dec); + data.highestBid = wasmtypes.uint64Decode(dec); + data.highestBidder = wasmtypes.agentIDDecode(dec); + data.minimumBid = wasmtypes.uint64Decode(dec); + data.numTokens = wasmtypes.uint64Decode(dec); + data.ownerMargin = wasmtypes.uint64Decode(dec); + data.whenStarted = wasmtypes.uint64Decode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.colorEncode(enc, this.color); + wasmtypes.agentIDEncode(enc, this.creator); + wasmtypes.uint64Encode(enc, this.deposit); + wasmtypes.stringEncode(enc, this.description); + wasmtypes.uint32Encode(enc, this.duration); + wasmtypes.uint64Encode(enc, this.highestBid); + wasmtypes.agentIDEncode(enc, this.highestBidder); + wasmtypes.uint64Encode(enc, this.minimumBid); + wasmtypes.uint64Encode(enc, this.numTokens); + wasmtypes.uint64Encode(enc, this.ownerMargin); + wasmtypes.uint64Encode(enc, this.whenStarted); + return enc.buf(); + } } -export class ImmutableAuction { - objID: i32; - keyID: wasmlib.Key32; +export class ImmutableAuction extends wasmtypes.ScProxy { - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } + exists(): bool { + return this.proxy.exists(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Auction { - return Auction.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Auction { + return Auction.fromBytes(this.proxy.get()); + } } -export class MutableAuction { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class MutableAuction extends wasmtypes.ScProxy { - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } - setValue(value: Auction): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: Auction): void { + this.proxy.set(value.bytes()); + } - value(): Auction { - return Auction.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Auction { + return Auction.fromBytes(this.proxy.get()); + } } export class Bid { - amount : i64 = 0; // cumulative amount of bids from same bidder - index : i32 = 0; // index of bidder in bidder list - timestamp : i64 = 0; // timestamp of most recent bid - - static fromBytes(bytes: u8[]): Bid { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Bid(); - data.amount = decode.int64(); - data.index = decode.int32(); - data.timestamp = decode.int64(); - decode.close(); - return data; - } - - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - int64(this.amount). - int32(this.index). - int64(this.timestamp). - data(); - } + amount : u64 = 0; // cumulative amount of bids from same bidder + index : u32 = 0; // index of bidder in bidder list + timestamp : u64 = 0; // timestamp of most recent bid + + static fromBytes(buf: u8[]): Bid { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new Bid(); + data.amount = wasmtypes.uint64Decode(dec); + data.index = wasmtypes.uint32Decode(dec); + data.timestamp = wasmtypes.uint64Decode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint64Encode(enc, this.amount); + wasmtypes.uint32Encode(enc, this.index); + wasmtypes.uint64Encode(enc, this.timestamp); + return enc.buf(); + } } -export class ImmutableBid { - objID: i32; - keyID: wasmlib.Key32; +export class ImmutableBid extends wasmtypes.ScProxy { - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } + exists(): bool { + return this.proxy.exists(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Bid { - return Bid.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Bid { + return Bid.fromBytes(this.proxy.get()); + } } -export class MutableBid { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class MutableBid extends wasmtypes.ScProxy { - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } - setValue(value: Bid): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: Bid): void { + this.proxy.set(value.bytes()); + } - value(): Bid { - return Bid.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Bid { + return Bid.fromBytes(this.proxy.get()); + } } diff --git a/contracts/wasm/fairauction/ts/fairauction/typedefs.ts b/contracts/wasm/fairauction/ts/fairauction/typedefs.ts index 246878fa3c..3c52c6a4a7 100644 --- a/contracts/wasm/fairauction/ts/fairauction/typedefs.ts +++ b/contracts/wasm/fairauction/ts/fairauction/typedefs.ts @@ -5,81 +5,65 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableAgentID { - objID: i32; +export class ArrayOfImmutableAgentID extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + length(): u32 { + return this.proxy.length(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getAgentID(index: i32): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.objID, new wasmlib.Key32(index)); - } + getAgentID(index: u32): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.index(index)); + } } export class ImmutableBidderList extends ArrayOfImmutableAgentID { -}; +} -export class ArrayOfMutableAgentID { - objID: i32; +export class ArrayOfMutableAgentID extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendAgentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getAgentID(index: i32): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.objID, new wasmlib.Key32(index)); - } + getAgentID(index: u32): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.index(index)); + } } export class MutableBidderList extends ArrayOfMutableAgentID { -}; - -export class MapAgentIDToImmutableBid { - objID: i32; +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToImmutableBid extends wasmtypes.ScProxy { - getBid(key: wasmlib.ScAgentID): sc.ImmutableBid { - return new sc.ImmutableBid(this.objID, key.getKeyID()); - } + getBid(key: wasmtypes.ScAgentID): sc.ImmutableBid { + return new sc.ImmutableBid(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } export class ImmutableBids extends MapAgentIDToImmutableBid { -}; - -export class MapAgentIDToMutableBid { - objID: i32; +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapAgentIDToMutableBid extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getBid(key: wasmlib.ScAgentID): sc.MutableBid { - return new sc.MutableBid(this.objID, key.getKeyID()); - } + getBid(key: wasmtypes.ScAgentID): sc.MutableBid { + return new sc.MutableBid(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } } export class MutableBids extends MapAgentIDToMutableBid { -}; +} diff --git a/contracts/wasm/fairroulette/Cargo.toml b/contracts/wasm/fairroulette/Cargo.toml index 101c6afcdc..0f67e54bd6 100644 --- a/contracts/wasm/fairroulette/Cargo.toml +++ b/contracts/wasm/fairroulette/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/fairroulette/frontend/Dockerfile b/contracts/wasm/fairroulette/frontend/Dockerfile index 5c6979f31f..d19e58571b 100644 --- a/contracts/wasm/fairroulette/frontend/Dockerfile +++ b/contracts/wasm/fairroulette/frontend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:current-alpine as build +FROM node:lts-buster as build COPY package.json . COPY package-lock.json . diff --git a/contracts/wasm/fairroulette/frontend/package-lock.json b/contracts/wasm/fairroulette/frontend/package-lock.json index cccc8d9e98..b82daf39e7 100644 --- a/contracts/wasm/fairroulette/frontend/package-lock.json +++ b/contracts/wasm/fairroulette/frontend/package-lock.json @@ -1,14 +1,5783 @@ { "name": "svelte-app", "version": "1.0.0", - "lockfileVersion": 1, + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "svelte-app", + "version": "1.0.0", + "dependencies": { + "@babel/eslint-parser": "^7.15.8", + "lottie-web": "^5.7.13", + "svelte-router-spa": "^6.0.2", + "tslib": "^2.3.1" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^17.0.0", + "@rollup/plugin-node-resolve": "^11.0.0", + "@rollup/plugin-replace": "^3.0.0", + "@rollup/plugin-typescript": "^8.2.5", + "@tsconfig/svelte": "^2.0.0", + "@types/gtag.js": "^0.0.7", + "@typescript-eslint/eslint-plugin": "^4.29.2", + "@typescript-eslint/parser": "^4.29.2", + "base64-js": "^1.5.1", + "blakejs": "^1.1.1", + "eslint": "^7.32.0", + "eslint-plugin-security": "^1.4.0", + "eslint-plugin-svelte3": "^3.2.0", + "ieee754": "^1.2.1", + "nanoevents": "^6.0.0", + "node-sass": "^6.0.1", + "prettier": "^2.3.2", + "random-number-csprng": "^1.0.2", + "rollup": "^2.3.4", + "rollup-plugin-css-only": "^3.1.0", + "rollup-plugin-livereload": "^2.0.0", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", + "rollup-plugin-svelte": "^7.0.0", + "rollup-plugin-terser": "^7.0.0", + "rollup-plugin-typescript2": "^0.30.0", + "rollup-plugin-web-worker-loader": "^1.6.1", + "sirv-cli": "^1.0.0", + "svelte": "^3.0.0", + "svelte-check": "^2.0.0", + "svelte-preprocess": "^4.0.0", + "threads": "^1.6.5", + "tweetnacl": "^1.0.3", + "typescript": "^4.0.0", + "uuid": "^8.3.2" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.12.11", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", + "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "dependencies": { + "@babel/highlight": "^7.10.4" + } + }, + "node_modules/@babel/eslint-parser": { + "version": "7.15.8", + "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.15.8.tgz", + "integrity": "sha512-fYP7QFngCvgxjUuw8O057SVH5jCXsbFFOoE77CFDcvzwBVgTOkMD/L4mIC5Ud1xf8chK/no2fRbSSn1wvNmKuQ==", + "dependencies": { + "eslint-scope": "^5.1.1", + "eslint-visitor-keys": "^2.1.0", + "semver": "^6.3.0" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || >=14.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.11.0", + "eslint": ">=7.5.0" + } + }, + "node_modules/@babel/eslint-parser/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.15.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", + "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", + "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", + "dependencies": { + "@babel/helper-validator-identifier": "^7.14.5", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", + "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.1.1", + "espree": "^7.3.0", + "globals": "^13.9.0", + "ignore": "^4.0.6", + "import-fresh": "^3.2.1", + "js-yaml": "^3.13.1", + "minimatch": "^3.0.4", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", + "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "dependencies": { + "@humanwhocodes/object-schema": "^1.2.0", + "debug": "^4.1.1", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", + "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==" + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.21", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz", + "integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g==", + "dev": true + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "17.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-17.1.0.tgz", + "integrity": "sha512-PoMdXCw0ZyvjpCMT5aV4nkL0QywxP29sODQsSGeDpr/oI49Qq9tRtAsb/LbYbDzFlOydVEqHmmZWFtXJEAX9ew==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "commondir": "^1.0.1", + "estree-walker": "^2.0.1", + "glob": "^7.1.6", + "is-reference": "^1.2.1", + "magic-string": "^0.25.7", + "resolve": "^1.17.0" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^2.30.0" + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "11.2.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-11.2.1.tgz", + "integrity": "sha512-yc2n43jcqVyGE2sqV5/YCmocy9ArjVAP/BeXyTtADTBBX6V0e5UMqwO8CdQ0kzjb6zu5P1qMzsScCMRvE9OlVg==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "@types/resolve": "1.17.1", + "builtin-modules": "^3.1.0", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">= 10.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/plugin-replace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-3.0.0.tgz", + "integrity": "sha512-3c7JCbMuYXM4PbPWT4+m/4Y6U60SgsnDT/cCyAyUKwFHg7pTSfsSQzIpETha3a3ig6OdOKzZz87D9ZXIK3qsDg==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "magic-string": "^0.25.7" + }, + "peerDependencies": { + "rollup": "^1.20.0 || ^2.0.0" + } + }, + "node_modules/@rollup/plugin-typescript": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-8.3.0.tgz", + "integrity": "sha512-I5FpSvLbtAdwJ+naznv+B4sjXZUcIvLLceYpITAn7wAP8W0wqc5noLdGIp9HGVntNhRWXctwPYrSSFQxtl0FPA==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "resolve": "^1.17.0" + }, + "engines": { + "node": ">=8.0.0" + }, + "peerDependencies": { + "rollup": "^2.14.0", + "tslib": "*", + "typescript": ">=3.7.0" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", + "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "dev": true, + "dependencies": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", + "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", + "dev": true + }, + "node_modules/@tsconfig/svelte": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-2.0.1.tgz", + "integrity": "sha512-aqkICXbM1oX5FfgZd2qSSAGdyo/NRxjWCamxoyi3T8iVQnzGge19HhDYzZ6NrVOW7bhcWNSq9XexWFtMzbB24A==", + "dev": true + }, + "node_modules/@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "node_modules/@types/gtag.js": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/@types/gtag.js/-/gtag.js-0.0.7.tgz", + "integrity": "sha512-Kl5beBoB0OXw7WeFgHHpLEchvC7HyIu3v1AksNNTemAF6jmEmQGqhZQSHcG6BOU/Lq0xsByQNqLzicLPjVkxYQ==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", + "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", + "dev": true + }, + "node_modules/@types/minimist": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.2.tgz", + "integrity": "sha512-jhuKLIRrhvCPLqwPcx6INqmKeiA5EWrsCOPhrlFSrbrmU4ZMPjj5Ul/oLCMDO98XRUIwVm78xICz4EPCektzeQ==", + "dev": true + }, + "node_modules/@types/node": { + "version": "16.11.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.6.tgz", + "integrity": "sha512-ua7PgUoeQFjmWPcoo9khiPum3Pd60k4/2ZGXt18sm2Slk0W0xZTqt5Y0Ny1NyBiN1EVQ/+FaF9NcY4Qe6rwk5w==", + "dev": true + }, + "node_modules/@types/normalize-package-data": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz", + "integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==", + "dev": true + }, + "node_modules/@types/pug": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/pug/-/pug-2.0.5.tgz", + "integrity": "sha512-LOnASQoeNZMkzexRuyqcBBDZ6rS+rQxUMkmj5A0PkhhiSZivLIuz6Hxyr1mkGoEZEkk66faROmpMi4fFkrKsBA==", + "dev": true + }, + "node_modules/@types/resolve": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", + "integrity": "sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/sass": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/@types/sass/-/sass-1.16.1.tgz", + "integrity": "sha512-iZUcRrGuz/Tbg3loODpW7vrQJkUtpY2fFSf4ELqqkApcS2TkZ1msk7ie8iZPB86lDOP8QOTTmuvWjc5S0R9OjQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.33.0.tgz", + "integrity": "sha512-aINiAxGVdOl1eJyVjaWn/YcVAq4Gi/Yo35qHGCnqbWVz61g39D0h23veY/MA0rFFGfxK7TySg2uwDeNv+JgVpg==", + "dev": true, + "dependencies": { + "@typescript-eslint/experimental-utils": "4.33.0", + "@typescript-eslint/scope-manager": "4.33.0", + "debug": "^4.3.1", + "functional-red-black-tree": "^1.0.1", + "ignore": "^5.1.8", + "regexpp": "^3.1.0", + "semver": "^7.3.5", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^4.0.0", + "eslint": "^5.0.0 || ^6.0.0 || ^7.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/experimental-utils": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.33.0.tgz", + "integrity": "sha512-zeQjOoES5JFjTnAhI5QY7ZviczMzDptls15GFsI6jyUOq0kOf9+WonkhtlIhh0RgHRnqj5gdNxW5j1EvAyYg6Q==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.7", + "@typescript-eslint/scope-manager": "4.33.0", + "@typescript-eslint/types": "4.33.0", + "@typescript-eslint/typescript-estree": "4.33.0", + "eslint-scope": "^5.1.1", + "eslint-utils": "^3.0.0" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "*" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.33.0.tgz", + "integrity": "sha512-ZohdsbXadjGBSK0/r+d87X0SBmKzOq4/S5nzK6SBgJspFo9/CUDJ7hjayuze+JK7CZQLDMroqytp7pOcFKTxZA==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "4.33.0", + "@typescript-eslint/types": "4.33.0", + "@typescript-eslint/typescript-estree": "4.33.0", + "debug": "^4.3.1" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^5.0.0 || ^6.0.0 || ^7.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.33.0.tgz", + "integrity": "sha512-5IfJHpgTsTZuONKbODctL4kKuQje/bzBRkwHE8UOZ4f89Zeddg+EGZs8PD8NcN4LdM3ygHWYB3ukPAYjvl/qbQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "4.33.0", + "@typescript-eslint/visitor-keys": "4.33.0" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.33.0.tgz", + "integrity": "sha512-zKp7CjQzLQImXEpLt2BUw1tvOMPfNoTAfb8l51evhYbOEEzdWyQNmHWWGPR6hwKJDAi+1VXSBmnhL9kyVTTOuQ==", + "dev": true, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.33.0.tgz", + "integrity": "sha512-rkWRY1MPFzjwnEVHsxGemDzqqddw2QbTJlICPD9p9I9LfsO8fdmfQPOX3uKfUaGRDFJbfrtm/sXhVXN4E+bzCA==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "4.33.0", + "@typescript-eslint/visitor-keys": "4.33.0", + "debug": "^4.3.1", + "globby": "^11.0.3", + "is-glob": "^4.0.1", + "semver": "^7.3.5", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "4.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.33.0.tgz", + "integrity": "sha512-uqi/2aSz9g2ftcHWf8uLPJA70rUv6yuMW5Bohw+bwcuzaxQIHaKFZCKGoGXIrc9vkTJ3+0txM73K0Hq3d5wgIg==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "4.33.0", + "eslint-visitor-keys": "^2.0.0" + }, + "engines": { + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "node_modules/abstract-leveldown": { + "version": "0.12.4", + "resolved": "https://registry.npmjs.org/abstract-leveldown/-/abstract-leveldown-0.12.4.tgz", + "integrity": "sha1-KeGOYy5g5OIh1YECR4UqY9ey5BA=", + "dev": true, + "dependencies": { + "xtend": "~3.0.0" + } + }, + "node_modules/abstract-leveldown/node_modules/xtend": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz", + "integrity": "sha1-XM50B7r2Qsunvs2laBEcST9ZZlo=", + "dev": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/amdefine": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true, + "engines": { + "node": ">=0.4.2" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "node_modules/are-we-there-yet": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.7.tgz", + "integrity": "sha512-nxwy40TuMiUGqMyRHgCSWZ9FM4VAoRP4xUYSTv5ImRog+h9yISPbVH7H8fASCIzYn9wlEv4zvFL7uKDMCFQm3g==", + "dev": true, + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "dev": true, + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/asn1.js/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/async-foreach": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz", + "integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "node_modules/aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/aws4": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", + "dev": true + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/bcrypt-pbkdf/node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/bl": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/bl/-/bl-0.8.2.tgz", + "integrity": "sha1-yba8oI0bwuoA/Ir7Txpf0eHGbk4=", + "dev": true, + "dependencies": { + "readable-stream": "~1.0.26" + } + }, + "node_modules/bl/node_modules/isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/bl/node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "node_modules/blakejs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/blakejs/-/blakejs-1.1.1.tgz", + "integrity": "sha512-bLG6PHOCZJKNshTjGRBvET0vTciwQE6zFKOKKXPDJfwFBd4Ac0yBfPZqcGvGJap50l7ktvlpFqc2jGVaUgbJgg==", + "dev": true + }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true + }, + "node_modules/bn.js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", + "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", + "dev": true + }, + "node_modules/browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "dev": true, + "dependencies": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "dev": true, + "dependencies": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "node_modules/browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "dev": true, + "dependencies": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/browserify-fs": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/browserify-fs/-/browserify-fs-1.0.0.tgz", + "integrity": "sha1-8HWqinKdTRcW0GZiDjhvzBMRqW8=", + "dev": true, + "dependencies": { + "level-filesystem": "^1.0.1", + "level-js": "^2.1.3", + "levelup": "^0.18.2" + } + }, + "node_modules/browserify-rsa": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", + "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", + "dev": true, + "dependencies": { + "bn.js": "^5.0.0", + "randombytes": "^2.0.1" + } + }, + "node_modules/browserify-sign": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", + "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", + "dev": true, + "dependencies": { + "bn.js": "^5.1.1", + "browserify-rsa": "^4.0.1", + "create-hash": "^1.2.0", + "create-hmac": "^1.1.7", + "elliptic": "^6.5.3", + "inherits": "^2.0.4", + "parse-asn1": "^5.1.5", + "readable-stream": "^3.6.0", + "safe-buffer": "^5.2.0" + } + }, + "node_modules/browserify-sign/node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/browserify-sign/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/buffer-es6": { + "version": "4.9.3", + "resolved": "https://registry.npmjs.org/buffer-es6/-/buffer-es6-4.9.3.tgz", + "integrity": "sha1-8mNHuC33b9N+GLy1KIxJcM/VxAQ=", + "dev": true + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "dev": true + }, + "node_modules/builtin-modules": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.2.0.tgz", + "integrity": "sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase-keys": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-6.2.2.tgz", + "integrity": "sha512-YrwaA0vEKazPBkn0ipTiMpSajYDSe+KjQfrjhcBMxJt/znbvlHd8Pw/Vamaz5EB4Wfhs3SUR3Z9mwRu/P3s3Yg==", + "dev": true, + "dependencies": { + "camelcase": "^5.3.1", + "map-obj": "^4.0.0", + "quick-lru": "^4.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chokidar": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz", + "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==", + "dev": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "dependencies": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/clone": { + "version": "0.1.19", + "resolved": "https://registry.npmjs.org/clone/-/clone-0.1.19.tgz", + "integrity": "sha1-YT+2hjmyaklKxTJT4Vsaa9iK2oU=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "engines": [ + "node >= 0.8" + ], + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/console-clear": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/console-clear/-/console-clear-1.1.1.tgz", + "integrity": "sha512-pMD+MVR538ipqkG5JXeOEbKWS5um1H4LUUccUQG68qpeqBYbzYy79Gh55jkd2TtPdRfUaLWdv6LPP//5Zt0aPQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, + "node_modules/create-ecdh": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", + "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", + "dev": true, + "dependencies": { + "bn.js": "^4.1.0", + "elliptic": "^6.5.3" + } + }, + "node_modules/create-ecdh/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/create-error": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/create-error/-/create-error-0.3.1.tgz", + "integrity": "sha1-aYECRaYp5lRDK/BDdzYAA6U1GiM=", + "dev": true + }, + "node_modules/create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dev": true, + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dev": true, + "dependencies": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "dev": true, + "dependencies": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + }, + "engines": { + "node": "*" + } + }, + "node_modules/dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decamelize-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", + "integrity": "sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk=", + "dev": true, + "dependencies": { + "decamelize": "^1.1.0", + "map-obj": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decamelize-keys/node_modules/map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==" + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deferred-leveldown": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/deferred-leveldown/-/deferred-leveldown-0.2.0.tgz", + "integrity": "sha1-LO8fER4cV4cNi7uK8mUOWHzS9bQ=", + "dev": true, + "dependencies": { + "abstract-leveldown": "~0.12.1" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "node_modules/des.js": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", + "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/detect-indent": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", + "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "dev": true, + "dependencies": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "node_modules/diffie-hellman/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/elliptic": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", + "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", + "dev": true, + "dependencies": { + "bn.js": "^4.11.9", + "brorand": "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + "inherits": "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/elliptic/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "node_modules/enquirer": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", + "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", + "dependencies": { + "ansi-colors": "^4.1.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/errno": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "dev": true, + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es6-promise": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", + "dev": true + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "7.32.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", + "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", + "dependencies": { + "@babel/code-frame": "7.12.11", + "@eslint/eslintrc": "^0.4.3", + "@humanwhocodes/config-array": "^0.5.0", + "ajv": "^6.10.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "enquirer": "^2.3.5", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^5.1.1", + "eslint-utils": "^2.1.0", + "eslint-visitor-keys": "^2.0.0", + "espree": "^7.3.1", + "esquery": "^1.4.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "functional-red-black-tree": "^1.0.1", + "glob-parent": "^5.1.2", + "globals": "^13.6.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.0.4", + "natural-compare": "^1.4.0", + "optionator": "^0.9.1", + "progress": "^2.0.0", + "regexpp": "^3.1.0", + "semver": "^7.2.1", + "strip-ansi": "^6.0.0", + "strip-json-comments": "^3.1.0", + "table": "^6.0.9", + "text-table": "^0.2.0", + "v8-compile-cache": "^2.0.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-plugin-security": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-security/-/eslint-plugin-security-1.4.0.tgz", + "integrity": "sha512-xlS7P2PLMXeqfhyf3NpqbvbnW04kN8M9NtmhpR3XGyOvt/vNKS7XPXT5EDbwKW9vCjWH4PpfQvgD/+JgN0VJKA==", + "dev": true, + "dependencies": { + "safe-regex": "^1.1.0" + } + }, + "node_modules/eslint-plugin-svelte3": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-svelte3/-/eslint-plugin-svelte3-3.2.1.tgz", + "integrity": "sha512-YoBR9mLoKCjGghJ/gvpnFZKaMEu/VRcuxpSRS8KuozuEo7CdBH7bmBHa6FmMm0i4kJnOyx+PVsaptz96K6H/4Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "eslint": ">=6.0.0", + "svelte": "^3.2.0" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/eslint-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", + "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^2.0.0" + }, + "engines": { + "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": ">=5" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", + "engines": { + "node": ">=10" + } + }, + "node_modules/eslint/node_modules/eslint-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", + "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", + "dependencies": { + "eslint-visitor-keys": "^1.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + } + }, + "node_modules/eslint/node_modules/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint/node_modules/ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "engines": { + "node": ">= 4" + } + }, + "node_modules/esm": { + "version": "3.2.25", + "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", + "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", + "dev": true, + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/espree": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", + "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", + "dependencies": { + "acorn": "^7.4.0", + "acorn-jsx": "^5.3.1", + "eslint-visitor-keys": "^1.3.0" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "engines": { + "node": ">=4" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esquery": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", + "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esquery/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "dev": true, + "dependencies": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true, + "engines": [ + "node >=0.6.0" + ] + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-glob": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.7.tgz", + "integrity": "sha512-rYGMRwip6lUMvYD3BTScMwT1HtAs2d71SMv66Vrxs0IekGZEjhM0pcMfjQPnknBt2zeCwQMEupiN02ZP4DiT1Q==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" + }, + "node_modules/fastq": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", + "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "dev": true, + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/flat-cache": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", + "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", + "dependencies": { + "flatted": "^3.1.0", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flatted": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.2.tgz", + "integrity": "sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA==" + }, + "node_modules/foreach": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", + "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=", + "dev": true + }, + "node_modules/forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" + }, + "node_modules/fwd-stream": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/fwd-stream/-/fwd-stream-1.0.4.tgz", + "integrity": "sha1-7Sgcq+1G/uz5Ie4y3ExQs3KsfPo=", + "dev": true, + "dependencies": { + "readable-stream": "~1.0.26-4" + } + }, + "node_modules/fwd-stream/node_modules/isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "node_modules/fwd-stream/node_modules/readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/fwd-stream/node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "node_modules/gauge": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", + "dev": true, + "dependencies": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "node_modules/gauge/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gauge/node_modules/strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gaze": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.3.tgz", + "integrity": "sha512-BRdNm8hbWzFzWHERTrejLqwHDfS4GibPoq5wjTPIoJHoBtKGPg3xAFfxmM+9ztbXelxcf2hwQcaz1PtmFeue8g==", + "dev": true, + "dependencies": { + "globule": "^1.0.0" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-port": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/get-port/-/get-port-3.2.0.tgz", + "integrity": "sha1-3Xzn3hh8Bsi/NTeWrHHgmfCYDrw=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/get-stdin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "dependencies": { + "assert-plus": "^1.0.0" + } + }, + "node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globals": { + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", + "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globby": { + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.4.tgz", + "integrity": "sha512-9O4MVG9ioZJ08ffbcyVYyLOJLk5JQ688pJ4eMGLpdWLHq/Wr1D9BlriLQyL0E+jbkuePVZXYFj47QM/v093wHg==", + "dev": true, + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.1.1", + "ignore": "^5.1.4", + "merge2": "^1.3.0", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globule": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/globule/-/globule-1.3.3.tgz", + "integrity": "sha512-mb1aYtDbIjTu4ShMB85m3UzjX9BVKe9WCzsnfMSZk+K5GpIbBOexgg4PPCt5eHDEG5/ZQAUX2Kct02zfiPLsKg==", + "dev": true, + "dependencies": { + "glob": "~7.1.1", + "lodash": "~4.17.10", + "minimatch": "~3.0.2" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/globule/node_modules/glob": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", + "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", + "dev": true + }, + "node_modules/har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "deprecated": "this library is no longer supported", + "dev": true, + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/hard-rejection": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", + "integrity": "sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-ansi/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "node_modules/hash-base": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", + "integrity": "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "safe-buffer": "^5.2.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/hash-base/node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/hash-base/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "node_modules/hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "dev": true, + "dependencies": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/hosted-git-info": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.0.2.tgz", + "integrity": "sha512-c9OGXbZ3guC/xOlCg1Ci/VgWlwsqDv1yMQL1CWqXDL0hDjXuNcq0zuR4xqPSuasI3kqFDhqSyTjREz5gzq0fXg==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" + } + }, + "node_modules/idb-wrapper": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/idb-wrapper/-/idb-wrapper-1.7.2.tgz", + "integrity": "sha512-zfNREywMuf0NzDo9mVsL0yegjsirJxHpKHvWcyRozIqQy89g0a3U+oBPOCN4cc0oCiOuYgZHimzaW/R46G1Mpg==", + "dev": true + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", + "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/indexof": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", + "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=", + "dev": true + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/is/-/is-0.2.7.tgz", + "integrity": "sha1-OzSixI81mXLzUEKEkZOucmS2NWI=", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.0.tgz", + "integrity": "sha512-vd15qHsaqrRL7dtH6QNuy0ndJmRDrS9HAM1CAiSifNUFv4x1a0CCVsj18hJ1mShxIG6T2i1sO78MkP56r0nYRw==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "dependencies": { + "number-is-nan": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "dev": true + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-object": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/is-object/-/is-object-0.1.2.tgz", + "integrity": "sha1-AO+8CIFsM8/ErIJR0TLhDcZQmNc=", + "dev": true + }, + "node_modules/is-observable": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-2.1.0.tgz", + "integrity": "sha512-DailKdLb0WU+xX8K5w7VsJhapwHLZ9jjmazqCJq4X12CTgqq73TKnbRcnSLuXYPOoLQgV5IrD7ePiX/h1vnkBw==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "node_modules/isbuffer": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/isbuffer/-/isbuffer-0.0.0.tgz", + "integrity": "sha1-OMFG2d9Si4v5sHAcPUPPEt8/w5s=", + "dev": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "node_modules/jest-worker": { + "version": "26.6.2", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", + "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", + "dev": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/js-base64": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.6.4.tgz", + "integrity": "sha512-pZe//GGmwJndub7ZghVHz7vjb2LgC1m8B07Au3eYqeqv9emhESByMXxaEgkUkEqJe87oBbSniGYoQNIBklc7IQ==", + "dev": true + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true + }, + "node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "dev": true, + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-blobs": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/level-blobs/-/level-blobs-0.1.7.tgz", + "integrity": "sha1-mrm5e7mfHtv594o0M+Ie1WOGva8=", + "dev": true, + "dependencies": { + "level-peek": "1.0.6", + "once": "^1.3.0", + "readable-stream": "^1.0.26-4" + } + }, + "node_modules/level-blobs/node_modules/isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "node_modules/level-blobs/node_modules/readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/level-blobs/node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "node_modules/level-filesystem": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/level-filesystem/-/level-filesystem-1.2.0.tgz", + "integrity": "sha1-oArKmRnEpN+v3KaoEI0iWq3/Y7M=", + "dev": true, + "dependencies": { + "concat-stream": "^1.4.4", + "errno": "^0.1.1", + "fwd-stream": "^1.0.4", + "level-blobs": "^0.1.7", + "level-peek": "^1.0.6", + "level-sublevel": "^5.2.0", + "octal": "^1.0.0", + "once": "^1.3.0", + "xtend": "^2.2.0" + } + }, + "node_modules/level-fix-range": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/level-fix-range/-/level-fix-range-1.0.2.tgz", + "integrity": "sha1-vxW5Fa422EcMgh6IPd95zRZCCCg=", + "dev": true + }, + "node_modules/level-hooks": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/level-hooks/-/level-hooks-4.5.0.tgz", + "integrity": "sha1-G5rmGSKTDzMF0aYfxNg8gQLA3ZM=", + "dev": true, + "dependencies": { + "string-range": "~1.2" + } + }, + "node_modules/level-js": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/level-js/-/level-js-2.2.4.tgz", + "integrity": "sha1-vAVfQYBjXUSJtWHJSG+jcOjBFpc=", + "dev": true, + "dependencies": { + "abstract-leveldown": "~0.12.0", + "idb-wrapper": "^1.5.0", + "isbuffer": "~0.0.0", + "ltgt": "^2.1.2", + "typedarray-to-buffer": "~1.0.0", + "xtend": "~2.1.2" + } + }, + "node_modules/level-js/node_modules/xtend": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz", + "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=", + "dev": true, + "dependencies": { + "object-keys": "~0.4.0" + }, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/level-peek": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/level-peek/-/level-peek-1.0.6.tgz", + "integrity": "sha1-vsUccqgu5GTTNkNMfIdsP8vM538=", + "dev": true, + "dependencies": { + "level-fix-range": "~1.0.2" + } + }, + "node_modules/level-sublevel": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/level-sublevel/-/level-sublevel-5.2.3.tgz", + "integrity": "sha1-dEwSxy0ucr543eO5tc2E1iGRQTo=", + "dev": true, + "dependencies": { + "level-fix-range": "2.0", + "level-hooks": ">=4.4.0 <5", + "string-range": "~1.2.1", + "xtend": "~2.0.4" + } + }, + "node_modules/level-sublevel/node_modules/level-fix-range": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/level-fix-range/-/level-fix-range-2.0.0.tgz", + "integrity": "sha1-xBfWIVlEIVGhnZojZ4aPFyTC1Ug=", + "dev": true, + "dependencies": { + "clone": "~0.1.9" + } + }, + "node_modules/level-sublevel/node_modules/object-keys": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.2.0.tgz", + "integrity": "sha1-zd7AKZiwkb5CvxA1rjLknxy26mc=", + "deprecated": "Please update to the latest object-keys", + "dev": true, + "dependencies": { + "foreach": "~2.0.1", + "indexof": "~0.0.1", + "is": "~0.2.6" + } + }, + "node_modules/level-sublevel/node_modules/xtend": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.0.6.tgz", + "integrity": "sha1-XqZXptukRwacLlnFihE4ywxebO4=", + "dev": true, + "dependencies": { + "is-object": "~0.1.2", + "object-keys": "~0.2.0" + }, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/levelup": { + "version": "0.18.6", + "resolved": "https://registry.npmjs.org/levelup/-/levelup-0.18.6.tgz", + "integrity": "sha1-5qAcsIlhbI7MApHCqb0/DETj5es=", + "dev": true, + "dependencies": { + "bl": "~0.8.1", + "deferred-leveldown": "~0.2.0", + "errno": "~0.1.1", + "prr": "~0.0.0", + "readable-stream": "~1.0.26", + "semver": "~2.3.1", + "xtend": "~3.0.0" + } + }, + "node_modules/levelup/node_modules/isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "node_modules/levelup/node_modules/prr": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/prr/-/prr-0.0.0.tgz", + "integrity": "sha1-GoS4WQgyVQFBGFPQCB7j+obikmo=", + "dev": true + }, + "node_modules/levelup/node_modules/readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/levelup/node_modules/semver": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-2.3.2.tgz", + "integrity": "sha1-uYSPJdbPNjMwc+ye+IVtQvEjPlI=", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/levelup/node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "node_modules/levelup/node_modules/xtend": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz", + "integrity": "sha1-XM50B7r2Qsunvs2laBEcST9ZZlo=", + "dev": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lines-and-columns": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", + "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", + "dev": true + }, + "node_modules/livereload": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/livereload/-/livereload-0.9.3.tgz", + "integrity": "sha512-q7Z71n3i4X0R9xthAryBdNGVGAO2R5X+/xXpmKeuPMrteg+W2U8VusTKV3YiJbXZwKsOlFlHe+go6uSNjfxrZw==", + "dev": true, + "dependencies": { + "chokidar": "^3.5.0", + "livereload-js": "^3.3.1", + "opts": ">= 1.2.0", + "ws": "^7.4.3" + }, + "bin": { + "livereload": "bin/livereload.js" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/livereload-js": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/livereload-js/-/livereload-js-3.3.2.tgz", + "integrity": "sha512-w677WnINxFkuixAoUEXOStewzLYGI76XVag+0JWMMEyjJQKs0ibWZMxkTlB96Lm3EjZ7IeOxVziBEbtxVQqQZA==", + "dev": true + }, + "node_modules/local-access": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/local-access/-/local-access-1.1.0.tgz", + "integrity": "sha512-XfegD5pyTAfb+GY6chk283Ox5z8WexG56OvM06RWLpAc/UHozO8X6xAxEkIitZOtsSMM1Yr3DkHgW5W+onLhCw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" + }, + "node_modules/lodash.truncate": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", + "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=" + }, + "node_modules/lottie-web": { + "version": "5.7.14", + "resolved": "https://registry.npmjs.org/lottie-web/-/lottie-web-5.7.14.tgz", + "integrity": "sha512-J+QEPse7Rws0XvTqRJNtcE8cszb5FWYFHubEK6bgDJtw64/AQJ40aazbWXsWGBM4sm/PgLBLgmmhDU4QpLiieg==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ltgt": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ltgt/-/ltgt-2.2.1.tgz", + "integrity": "sha1-81ypHEk/e3PaDgdJUwTxezH4fuU=", + "dev": true + }, + "node_modules/magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.4" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/map-obj": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", + "integrity": "sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dev": true, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/meow": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-9.0.0.tgz", + "integrity": "sha512-+obSblOQmRhcyBt62furQqRAQpNyWXo8BuQ5bN7dG8wmwQ+vwHKp/rCFD4CrTP8CsDQD1sjoZ94K417XEUk8IQ==", + "dev": true, + "dependencies": { + "@types/minimist": "^1.2.0", + "camelcase-keys": "^6.2.2", + "decamelize": "^1.2.0", + "decamelize-keys": "^1.1.0", + "hard-rejection": "^2.1.0", + "minimist-options": "4.1.0", + "normalize-package-data": "^3.0.0", + "read-pkg-up": "^7.0.1", + "redent": "^3.0.0", + "trim-newlines": "^3.0.0", + "type-fest": "^0.18.0", + "yargs-parser": "^20.2.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/meow/node_modules/type-fest": { + "version": "0.18.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.18.1.tgz", + "integrity": "sha512-OIAYXk8+ISY+qTOwkHtKqzAuxchoMiD9Udx+FSGQDuiRR+PJKJHc2NJAXlbhkGwTt/4/nKZxELY1w3ReWOL8mw==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", + "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", + "dev": true, + "dependencies": { + "braces": "^3.0.1", + "picomatch": "^2.2.3" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "dependencies": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + }, + "bin": { + "miller-rabin": "bin/miller-rabin" + } + }, + "node_modules/miller-rabin/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/mime": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.50.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.50.0.tgz", + "integrity": "sha512-9tMZCDlYHqeERXEHO9f/hKfNXhre5dK2eE/krIvUjZbS2KPcqGDfNShIWS1uW9XOTKQKqK6qbeOci18rbfW77A==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.33", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.33.tgz", + "integrity": "sha512-plLElXp7pRDd0bNZHw+nMd52vRYjLwQjygaNg7ddJ2uJtTlmnTCjWuPKxVu6//AdaRuME84SvLW91sIkBqGT0g==", + "dev": true, + "dependencies": { + "mime-db": "1.50.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "node_modules/minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "dev": true + }, + "node_modules/minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "dev": true + }, + "node_modules/minimist-options": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-4.1.0.tgz", + "integrity": "sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==", + "dev": true, + "dependencies": { + "arrify": "^1.0.1", + "is-plain-obj": "^1.1.0", + "kind-of": "^6.0.3" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/minipass": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.5.tgz", + "integrity": "sha512-+8NzxD82XQoNKNrl1d/FSi+X8wAEWR+sbYAfIvub4Nz0d22plFG72CEVVaufV8PNf4qSslFTD8VMOxNVhHCjTw==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/nan": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz", + "integrity": "sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ==", + "dev": true + }, + "node_modules/nanoevents": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/nanoevents/-/nanoevents-6.0.2.tgz", + "integrity": "sha512-FRS2otuFcPPYDPYViNWQ42+1iZqbXydinkRHTHFxrF4a1CpBfmydR9zkI44WSXAXCyPrkcGtPk5CnpW6Y3lFKQ==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" + }, + "node_modules/node-gyp": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-7.1.2.tgz", + "integrity": "sha512-CbpcIo7C3eMu3dL1c3d0xw449fHIGALIJsRP4DDPHpyiW8vcriNY7ubh9TE4zEKfSxscY7PjeFnshE7h75ynjQ==", + "dev": true, + "dependencies": { + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.3", + "nopt": "^5.0.0", + "npmlog": "^4.1.2", + "request": "^2.88.2", + "rimraf": "^3.0.2", + "semver": "^7.3.2", + "tar": "^6.0.2", + "which": "^2.0.2" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": ">= 10.12.0" + } + }, + "node_modules/node-sass": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/node-sass/-/node-sass-6.0.1.tgz", + "integrity": "sha512-f+Rbqt92Ful9gX0cGtdYwjTrWAaGURgaK5rZCWOgCNyGWusFYHhbqCCBoFBeat+HKETOU02AyTxNhJV0YZf2jQ==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "async-foreach": "^0.1.3", + "chalk": "^1.1.1", + "cross-spawn": "^7.0.3", + "gaze": "^1.0.0", + "get-stdin": "^4.0.1", + "glob": "^7.0.3", + "lodash": "^4.17.15", + "meow": "^9.0.0", + "nan": "^2.13.2", + "node-gyp": "^7.1.0", + "npmlog": "^4.0.0", + "request": "^2.88.0", + "sass-graph": "2.2.5", + "stdout-stream": "^1.4.0", + "true-case-path": "^1.0.2" + }, + "bin": { + "node-sass": "bin/node-sass" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/node-sass/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/node-sass/node_modules/ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/node-sass/node_modules/chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "dependencies": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/node-sass/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/node-sass/node_modules/strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/node-sass/node_modules/supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dev": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-package-data": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-3.0.3.tgz", + "integrity": "sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA==", + "dev": true, + "dependencies": { + "hosted-git-info": "^4.0.1", + "is-core-module": "^2.5.0", + "semver": "^7.3.4", + "validate-npm-package-license": "^3.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npmlog": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", + "dev": true, + "dependencies": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "node_modules/number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-keys": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz", + "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=", + "dev": true + }, + "node_modules/observable-fns": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/observable-fns/-/observable-fns-0.6.1.tgz", + "integrity": "sha512-9gRK4+sRWzeN6AOewNBTLXir7Zl/i3GB6Yl26gK4flxz8BXVpD3kt8amREmWNb0mxYOGDotvE5a4N+PtGGKdkg==", + "dev": true + }, + "node_modules/octal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/octal/-/octal-1.0.0.tgz", + "integrity": "sha1-Y+cWKmjvvrniE1iNWOmJ0eXEUws=", + "dev": true + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optionator": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", + "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.3" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/opts": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/opts/-/opts-2.0.2.tgz", + "integrity": "sha512-k41FwbcLnlgnFh69f4qdUfvDQ+5vaSDnVPFI/y5XuhKRq97EnVVneO9F1ESVCdiVu4fCS2L8usX3mU331hB7pg==", + "dev": true + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-asn1": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", + "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", + "dev": true, + "dependencies": { + "asn1.js": "^5.2.0", + "browserify-aes": "^1.0.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3", + "safe-buffer": "^5.1.1" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/pbkdf2": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", + "integrity": "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==", + "dev": true, + "dependencies": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.4.1.tgz", + "integrity": "sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/process-es6": { + "version": "0.11.6", + "resolved": "https://registry.npmjs.org/process-es6/-/process-es6-0.11.6.tgz", + "integrity": "sha1-xrs4n5qVH4K9TrFpYAEFvS/5x3g=", + "dev": true + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "node_modules/psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "dev": true + }, + "node_modules/public-encrypt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", + "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", + "dev": true, + "dependencies": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/public-encrypt/node_modules/bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/quick-lru": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-4.0.1.tgz", + "integrity": "sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/random-number-csprng": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/random-number-csprng/-/random-number-csprng-1.0.2.tgz", + "integrity": "sha1-/NEg5i3/wsB2dMfD/gHhayX3OiY=", + "dev": true, + "dependencies": { + "bluebird": "^3.3.3", + "create-error": "^0.3.1" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "dev": true, + "dependencies": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "node_modules/read-pkg": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", + "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", + "dev": true, + "dependencies": { + "@types/normalize-package-data": "^2.4.0", + "normalize-package-data": "^2.5.0", + "parse-json": "^5.0.0", + "type-fest": "^0.6.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/read-pkg-up": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", + "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", + "dev": true, + "dependencies": { + "find-up": "^4.1.0", + "read-pkg": "^5.2.0", + "type-fest": "^0.8.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/read-pkg-up/node_modules/type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/read-pkg/node_modules/hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true + }, + "node_modules/read-pkg/node_modules/normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "dependencies": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "node_modules/read-pkg/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/read-pkg/node_modules/type-fest": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", + "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/regexpp": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + } + }, + "node_modules/request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dev": true, + "dependencies": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/request/node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "dev": true, + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "node_modules/require-relative": { + "version": "0.8.7", + "resolved": "https://registry.npmjs.org/require-relative/-/require-relative-0.8.7.tgz", + "integrity": "sha1-eZlTn8ngR6N5KPoZb44VY9q9Nt4=", + "dev": true + }, + "node_modules/resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "engines": { + "node": ">=4" + } + }, + "node_modules/ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "dev": true, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "node_modules/rollup": { + "version": "2.58.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.58.3.tgz", + "integrity": "sha512-ei27MSw1KhRur4p87Q0/Va2NAYqMXOX++FNEumMBcdreIRLURKy+cE2wcDJKBn0nfmhP2ZGrJkP1XPO+G8FJQw==", + "dev": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/rollup-plugin-css-only": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-css-only/-/rollup-plugin-css-only-3.1.0.tgz", + "integrity": "sha512-TYMOE5uoD76vpj+RTkQLzC9cQtbnJNktHPB507FzRWBVaofg7KhIqq1kGbcVOadARSozWF883Ho9KpSPKH8gqA==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "4" + }, + "engines": { + "node": ">=10.12.0" + }, + "peerDependencies": { + "rollup": "1 || 2" + } + }, + "node_modules/rollup-plugin-css-only/node_modules/@rollup/pluginutils": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.1.1.tgz", + "integrity": "sha512-clDjivHqWGXi7u+0d2r2sBi4Ie6VLEAzWMIkvJLnDmxoOhBYOTfzGbOQBA32THHm11/LiJbd01tJUpJsbshSWQ==", + "dev": true, + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/rollup-plugin-livereload": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/rollup-plugin-livereload/-/rollup-plugin-livereload-2.0.5.tgz", + "integrity": "sha512-vqQZ/UQowTW7VoiKEM5ouNW90wE5/GZLfdWuR0ELxyKOJUIaj+uismPZZaICU4DnWPVjnpCDDxEqwU7pcKY/PA==", + "dev": true, + "dependencies": { + "livereload": "^0.9.1" + }, + "engines": { + "node": ">=8.3" + } + }, + "node_modules/rollup-plugin-node-builtins": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-builtins/-/rollup-plugin-node-builtins-2.1.2.tgz", + "integrity": "sha1-JKH+1KQyV7a2Q3HYq8bOGrFFl+k=", + "dev": true, + "dependencies": { + "browserify-fs": "^1.0.0", + "buffer-es6": "^4.9.2", + "crypto-browserify": "^3.11.0", + "process-es6": "^0.11.2" + } + }, + "node_modules/rollup-plugin-node-globals": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-globals/-/rollup-plugin-node-globals-1.4.0.tgz", + "integrity": "sha512-xRkB+W/m1KLIzPUmG0ofvR+CPNcvuCuNdjVBVS7ALKSxr3EDhnzNceGkGi1m8MToSli13AzKFYH4ie9w3I5L3g==", + "dev": true, + "dependencies": { + "acorn": "^5.7.3", + "buffer-es6": "^4.9.3", + "estree-walker": "^0.5.2", + "magic-string": "^0.22.5", + "process-es6": "^0.11.6", + "rollup-pluginutils": "^2.3.1" + } + }, + "node_modules/rollup-plugin-node-globals/node_modules/acorn": { + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", + "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/rollup-plugin-node-globals/node_modules/estree-walker": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.5.2.tgz", + "integrity": "sha512-XpCnW/AE10ws/kDAs37cngSkvgIR8aN3G0MS85m7dUpuK2EREo9VJ00uvw6Dg/hXEpfsE1I1TvJOJr+Z+TL+ig==", + "dev": true + }, + "node_modules/rollup-plugin-node-globals/node_modules/magic-string": { + "version": "0.22.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.22.5.tgz", + "integrity": "sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w==", + "dev": true, + "dependencies": { + "vlq": "^0.2.2" + } + }, + "node_modules/rollup-plugin-svelte": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-svelte/-/rollup-plugin-svelte-7.1.0.tgz", + "integrity": "sha512-vopCUq3G+25sKjwF5VilIbiY6KCuMNHP1PFvx2Vr3REBNMDllKHFZN2B9jwwC+MqNc3UPKkjXnceLPEjTjXGXg==", + "dev": true, + "dependencies": { + "require-relative": "^0.8.7", + "rollup-pluginutils": "^2.8.2" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "rollup": ">=2.0.0", + "svelte": ">=3.5.0" + } + }, + "node_modules/rollup-plugin-terser": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz", + "integrity": "sha512-w3iIaU4OxcF52UUXiZNsNeuXIMDvFrr+ZXK6bFZ0Q60qyVfq4uLptoS4bbq3paG3x216eQllFZX7zt6TIImguQ==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "jest-worker": "^26.2.1", + "serialize-javascript": "^4.0.0", + "terser": "^5.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0" + } + }, + "node_modules/rollup-plugin-typescript2": { + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.30.0.tgz", + "integrity": "sha512-NUFszIQyhgDdhRS9ya/VEmsnpTe+GERDMmFo0Y+kf8ds51Xy57nPNGglJY+W6x1vcouA7Au7nsTgsLFj2I0PxQ==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^4.1.0", + "find-cache-dir": "^3.3.1", + "fs-extra": "8.1.0", + "resolve": "1.20.0", + "tslib": "2.1.0" + }, + "peerDependencies": { + "rollup": ">=1.26.3", + "typescript": ">=2.4.0" + } + }, + "node_modules/rollup-plugin-typescript2/node_modules/@rollup/pluginutils": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.1.1.tgz", + "integrity": "sha512-clDjivHqWGXi7u+0d2r2sBi4Ie6VLEAzWMIkvJLnDmxoOhBYOTfzGbOQBA32THHm11/LiJbd01tJUpJsbshSWQ==", + "dev": true, + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/rollup-plugin-typescript2/node_modules/tslib": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.1.0.tgz", + "integrity": "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==", + "dev": true + }, + "node_modules/rollup-plugin-web-worker-loader": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-web-worker-loader/-/rollup-plugin-web-worker-loader-1.6.1.tgz", + "integrity": "sha512-4QywQSz1NXFHKdyiou16mH3ijpcfLtLGOrAqvAqu1Gx+P8+zj+3gwC2BSL/VW1d+LW4nIHC8F7d7OXhs9UdR2A==", + "dev": true, + "peerDependencies": { + "rollup": "^1.9.2 || ^2.0.0" + } + }, + "node_modules/rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1" + } + }, + "node_modules/rollup-pluginutils/node_modules/estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/sade": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.7.4.tgz", + "integrity": "sha512-y5yauMD93rX840MwUJr7C1ysLFBgMspsdTo4UVrDg3fXDvtwOyIqykhVAAm6fk/3au77773itJStObgK+LKaiA==", + "dev": true, + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "dependencies": { + "ret": "~0.1.10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "node_modules/sander": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/sander/-/sander-0.5.1.tgz", + "integrity": "sha1-dB4kXiMfB8r7b98PEzrfohalAq0=", + "dev": true, + "dependencies": { + "es6-promise": "^3.1.2", + "graceful-fs": "^4.1.3", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.2" + } + }, + "node_modules/sander/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/sass-graph": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/sass-graph/-/sass-graph-2.2.5.tgz", + "integrity": "sha512-VFWDAHOe6mRuT4mZRd4eKE+d8Uedrk6Xnh7Sh9b4NGufQLQjOrvf/MQoOdx+0s92L89FeyUUNfU597j/3uNpag==", + "dev": true, + "dependencies": { + "glob": "^7.0.0", + "lodash": "^4.0.0", + "scss-tokenizer": "^0.2.3", + "yargs": "^13.3.2" + }, + "bin": { + "sassgraph": "bin/sassgraph" + } + }, + "node_modules/scss-tokenizer": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz", + "integrity": "sha1-jrBtualyMzOCTT9VMGQRSYR85dE=", + "dev": true, + "dependencies": { + "js-base64": "^2.1.8", + "source-map": "^0.4.2" + } + }, + "node_modules/semiver": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", + "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-javascript": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", + "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "node_modules/sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.5.tgz", + "integrity": "sha512-KWcOiKeQj6ZyXx7zq4YxSMgHRlod4czeBQZrPb8OKcohcqAXShm7E20kEMle9WBt26hFcAf0qLOcp5zmY7kOqQ==", + "dev": true + }, + "node_modules/sirv": { + "version": "1.0.18", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.18.tgz", + "integrity": "sha512-f2AOPogZmXgJ9Ma2M22ZEhc1dNtRIzcEkiflMFeVTRq+OViOZMvH1IPMVOwrKaxpSaHioBJiDR0SluRqGa7atA==", + "dev": true, + "dependencies": { + "@polka/url": "^1.0.0-next.20", + "mime": "^2.3.1", + "totalist": "^1.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/sirv-cli": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/sirv-cli/-/sirv-cli-1.0.14.tgz", + "integrity": "sha512-yyUTNr984ANKDloqepkYbBSqvx3buwYg2sQKPWjSU+IBia5loaoka2If8N9CMwt8AfP179cdEl7kYJ//iWJHjQ==", + "dev": true, + "dependencies": { + "console-clear": "^1.1.0", + "get-port": "^3.2.0", + "kleur": "^3.0.0", + "local-access": "^1.0.1", + "sade": "^1.6.0", + "semiver": "^1.0.0", + "sirv": "^1.0.13", + "tinydate": "^1.0.0" + }, + "bin": { + "sirv": "bin.js" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/sorcery": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/sorcery/-/sorcery-0.10.0.tgz", + "integrity": "sha1-iukK19fLBfxZ8asMY3hF1cFaUrc=", + "dev": true, + "dependencies": { + "buffer-crc32": "^0.2.5", + "minimist": "^1.2.0", + "sander": "^0.5.0", + "sourcemap-codec": "^1.3.0" + }, + "bin": { + "sorcery": "bin/index.js" + } + }, + "node_modules/source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "dev": true, + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.20", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.20.tgz", + "integrity": "sha512-n1lZZ8Ve4ksRqizaBQgxXDgKwttHDhyfQjA6YZZn8+AroHbsIz+JjwxQDxbp+7y5OYCI8t1Yk7etjD9CRd2hIw==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, + "node_modules/spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "dev": true, + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", + "dev": true + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.10.tgz", + "integrity": "sha512-oie3/+gKf7QtpitB0LYLETe+k8SifzsX4KixvpOsbI6S0kRiRQ5MKOio8eMSAKQ17N06+wdEOXRiId+zOxo0hA==", + "dev": true + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "node_modules/sshpk": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sshpk/node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "node_modules/stdout-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.1.tgz", + "integrity": "sha512-j4emi03KXqJWcIeF8eIXkjMFN1Cmb8gUlDYGeBALLPo5qdyTfA9bOtl8m33lRoC+vFMkP3gl0WsDr6+gzxbbTA==", + "dev": true, + "dependencies": { + "readable-stream": "^2.0.1" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string-range": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/string-range/-/string-range-1.2.2.tgz", + "integrity": "sha1-qJPtNH5yKZvIO++78qaSqNI51d0=", + "dev": true + }, + "node_modules/string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "dependencies": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "dependencies": { + "ansi-regex": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/svelte": { + "version": "3.44.0", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-3.44.0.tgz", + "integrity": "sha512-zWACSJBSncGiDvFfYOMFGNV5zDLOlyhftmO5yOZ0lEtQMptpElaRtl39MWz1+lYCpwUq4F3Q2lTzI9TrTL+eMA==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/svelte-check": { + "version": "2.2.7", + "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-2.2.7.tgz", + "integrity": "sha512-lH8ArmwVC+D314cToZkXBBfj7NlpvgQGP7nXCAMnNHo6hTEcbKcf/cAZgzbnAOTftjIJrmLHp+EDW887VJFSOQ==", + "dev": true, + "dependencies": { + "chalk": "^4.0.0", + "chokidar": "^3.4.1", + "fast-glob": "^3.2.7", + "import-fresh": "^3.2.1", + "minimist": "^1.2.5", + "sade": "^1.7.4", + "source-map": "^0.7.3", + "svelte-preprocess": "^4.0.0", + "typescript": "*" + }, + "bin": { + "svelte-check": "bin/svelte-check" + }, + "peerDependencies": { + "svelte": "^3.24.0" + } + }, + "node_modules/svelte-check/node_modules/source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/svelte-preprocess": { + "version": "4.9.8", + "resolved": "https://registry.npmjs.org/svelte-preprocess/-/svelte-preprocess-4.9.8.tgz", + "integrity": "sha512-EQS/oRZzMtYdAprppZxY3HcysKh11w54MgA63ybtL+TAZ4hVqYOnhw41JVJjWN9dhPnNjjLzvbZ2tMhTsla1Og==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "@types/pug": "^2.0.4", + "@types/sass": "^1.16.0", + "detect-indent": "^6.0.0", + "magic-string": "^0.25.7", + "sorcery": "^0.10.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">= 9.11.2" + }, + "peerDependencies": { + "@babel/core": "^7.10.2", + "coffeescript": "^2.5.1", + "less": "^3.11.3", + "postcss": "^7 || ^8", + "postcss-load-config": "^2.1.0 || ^3.0.0", + "pug": "^3.0.0", + "sass": "^1.26.8", + "stylus": "^0.54.7", + "sugarss": "^2.0.0", + "svelte": "^3.23.0", + "typescript": "^3.9.5 || ^4.0.0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "coffeescript": { + "optional": true + }, + "less": { + "optional": true + }, + "node-sass": { + "optional": true + }, + "postcss": { + "optional": true + }, + "postcss-load-config": { + "optional": true + }, + "pug": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/svelte-router-spa": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/svelte-router-spa/-/svelte-router-spa-6.0.3.tgz", + "integrity": "sha512-aHgyUVVI/WjipQNmKcXpX0hFZtkW5Y6hwH5aXLr2P/aRQ/qlX8ZbKQJUwKjOD59p7tt/c+wqokiIt68N7aNuKQ==", + "dependencies": { + "url-params-parser": "^1.0.3" + }, + "peerDependencies": { + "svelte": "^3.36.0" + } + }, + "node_modules/table": { + "version": "6.7.2", + "resolved": "https://registry.npmjs.org/table/-/table-6.7.2.tgz", + "integrity": "sha512-UFZK67uvyNivLeQbVtkiUs8Uuuxv24aSL4/Vil2PJVtMgU8Lx0CYkP12uCGa3kjyQzOSgV1+z9Wkb82fCGsO0g==", + "dependencies": { + "ajv": "^8.0.1", + "lodash.clonedeep": "^4.5.0", + "lodash.truncate": "^4.4.2", + "slice-ansi": "^4.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/table/node_modules/ajv": { + "version": "8.6.3", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.3.tgz", + "integrity": "sha512-SMJOdDP6LqTkD0Uq8qLi+gMwSt0imXLSV080qFVwJCpH9U6Mb+SUGHAXM0KNbcBPguytWyvFxcHgMLe2D2XSpw==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/table/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/table/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/table/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, + "node_modules/table/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tar": { + "version": "6.1.11", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz", + "integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==", + "dev": true, + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/tar/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser": { + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.9.0.tgz", + "integrity": "sha512-h5hxa23sCdpzcye/7b8YqbE5OwKca/ni0RQz1uRX3tGh8haaGHqcuSqbGRybuAKNdntZ0mDgFNXPJ48xQ2RXKQ==", + "dev": true, + "dependencies": { + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" + }, + "node_modules/threads": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/threads/-/threads-1.7.0.tgz", + "integrity": "sha512-Mx5NBSHX3sQYR6iI9VYbgHKBLisyB+xROCBGjjWm1O9wb9vfLxdaGtmT/KCjUqMsSNW6nERzCW3T6H43LqjDZQ==", + "dev": true, + "dependencies": { + "callsites": "^3.1.0", + "debug": "^4.2.0", + "is-observable": "^2.1.0", + "observable-fns": "^0.6.1" + }, + "funding": { + "url": "https://github.com/andywer/threads.js?sponsor=1" + }, + "optionalDependencies": { + "tiny-worker": ">= 2" + } + }, + "node_modules/tiny-worker": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tiny-worker/-/tiny-worker-2.3.0.tgz", + "integrity": "sha512-pJ70wq5EAqTAEl9IkGzA+fN0836rycEuz2Cn6yeZ6FRzlVS5IDOkFHpIoEsksPRQV34GDqXm65+OlnZqUSyK2g==", + "dev": true, + "optional": true, + "dependencies": { + "esm": "^3.2.25" + } + }, + "node_modules/tinydate": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tinydate/-/tinydate-1.3.0.tgz", + "integrity": "sha512-7cR8rLy2QhYHpsBDBVYnnWXm8uRTr38RoZakFSW7Bs7PzfMPNZthuMLkwqZv7MTu8lhQ91cOFYS5a7iFj2oR3w==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/totalist": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz", + "integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "dependencies": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/trim-newlines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-3.0.1.tgz", + "integrity": "sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/true-case-path": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.3.tgz", + "integrity": "sha512-m6s2OdQe5wgpFMC+pAJ+q9djG82O2jcHPOI6RNg1yy9rCYR+WD6Nbpl32fDpfC56nirdRy+opFa/Vk7HYhqaew==", + "dev": true, + "dependencies": { + "glob": "^7.1.2" + } + }, + "node_modules/tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + }, + "node_modules/tsutils": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", + "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", + "dev": true, + "dependencies": { + "tslib": "^1.8.1" + }, + "engines": { + "node": ">= 6" + }, + "peerDependencies": { + "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" + } + }, + "node_modules/tsutils/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "dev": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "node_modules/typedarray-to-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-1.0.4.tgz", + "integrity": "sha1-m7i6DoQfs/TPH+fCRenz+opf6Zw=", + "dev": true + }, + "node_modules/typescript": { + "version": "4.4.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.4.4.tgz", + "integrity": "sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/url-params-parser": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/url-params-parser/-/url-params-parser-1.0.4.tgz", + "integrity": "sha512-0m6BqGpY2OetTZ3UPTLKkbTfUHigsX2YhrzORT9iYiyUJ/SP2WJ3cggg2YWtvMs36GPwK9Q44ffddyarniu2Tg==" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-compile-cache": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", + "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==" + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "engines": [ + "node >=0.6.0" + ], + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "node_modules/verror/node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "node_modules/vlq": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/vlq/-/vlq-0.2.3.tgz", + "integrity": "sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow==", + "dev": true + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dev": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/word-wrap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/ws": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.5.tgz", + "integrity": "sha512-BAkMFcAzl8as1G/hArkxOxq3G7pjUqQ3gzYbLL0/5zNkph70e+lCoxBGnm6AW1+/aiNeV4fnKqZ8m4GZewmH2w==", + "dev": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.2.0.tgz", + "integrity": "sha1-7vax8ZjByN6vrYsXZaBNrUoBxak=", + "dev": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/yargs": { + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", + "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "dev": true, + "dependencies": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.2" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/yargs/node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/yargs-parser": { + "version": "13.1.2", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", + "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", + "dev": true, + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + }, "dependencies": { "@babel/code-frame": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", - "dev": true, "requires": { "@babel/highlight": "^7.10.4" } @@ -33,14 +5802,12 @@ "@babel/helper-validator-identifier": { "version": "7.15.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", - "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", - "dev": true + "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==" }, "@babel/highlight": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", - "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.14.5", "chalk": "^2.0.0", @@ -51,7 +5818,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "requires": { "color-convert": "^1.9.0" } @@ -60,7 +5826,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -71,7 +5836,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "requires": { "color-name": "1.1.3" } @@ -79,26 +5843,22 @@ "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "requires": { "has-flag": "^3.0.0" } @@ -109,7 +5869,6 @@ "version": "0.4.3", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", - "dev": true, "requires": { "ajv": "^6.12.4", "debug": "^4.1.1", @@ -125,8 +5884,7 @@ "ignore": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==" } } }, @@ -134,7 +5892,6 @@ "version": "0.5.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", - "dev": true, "requires": { "@humanwhocodes/object-schema": "^1.2.0", "debug": "^4.1.1", @@ -144,8 +5901,7 @@ "@humanwhocodes/object-schema": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", - "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", - "dev": true + "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==" }, "@nodelib/fs.scandir": { "version": "2.1.5", @@ -422,20 +6178,18 @@ "acorn": { "version": "7.4.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==" }, "acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true + "requires": {} }, "ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -452,20 +6206,17 @@ "ansi-colors": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==" }, "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" }, "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "requires": { "color-convert": "^2.0.1" } @@ -500,7 +6251,6 @@ "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, "requires": { "sprintf-js": "~1.0.2" } @@ -555,8 +6305,7 @@ "astral-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==" }, "async-foreach": { "version": "0.1.3", @@ -585,8 +6334,7 @@ "balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, "base64-js": { "version": "1.5.1", @@ -674,7 +6422,6 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -822,8 +6569,7 @@ "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" }, "camelcase": { "version": "5.3.1", @@ -852,7 +6598,6 @@ "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, "requires": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -951,7 +6696,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "requires": { "color-name": "~1.1.4" } @@ -959,8 +6703,7 @@ "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, "combined-stream": { "version": "1.0.8", @@ -986,8 +6729,7 @@ "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "concat-stream": { "version": "1.6.2", @@ -1074,7 +6816,6 @@ "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, "requires": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -1113,7 +6854,6 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", - "dev": true, "requires": { "ms": "2.1.2" } @@ -1145,8 +6885,7 @@ "deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==" }, "deepmerge": { "version": "4.2.2", @@ -1223,7 +6962,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, "requires": { "esutils": "^2.0.2" } @@ -1271,7 +7009,6 @@ "version": "2.3.6", "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dev": true, "requires": { "ansi-colors": "^4.1.1" } @@ -1309,14 +7046,12 @@ "escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==" }, "eslint": { "version": "7.32.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", - "dev": true, "requires": { "@babel/code-frame": "7.12.11", "@eslint/eslintrc": "^0.4.3", @@ -1364,7 +7099,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", - "dev": true, "requires": { "eslint-visitor-keys": "^1.1.0" }, @@ -1372,16 +7106,14 @@ "eslint-visitor-keys": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==" } } }, "ignore": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==" } } }, @@ -1398,7 +7130,8 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/eslint-plugin-svelte3/-/eslint-plugin-svelte3-3.2.1.tgz", "integrity": "sha512-YoBR9mLoKCjGghJ/gvpnFZKaMEu/VRcuxpSRS8KuozuEo7CdBH7bmBHa6FmMm0i4kJnOyx+PVsaptz96K6H/4Q==", - "dev": true + "dev": true, + "requires": {} }, "eslint-scope": { "version": "5.1.1", @@ -1434,7 +7167,6 @@ "version": "7.3.1", "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", - "dev": true, "requires": { "acorn": "^7.4.0", "acorn-jsx": "^5.3.1", @@ -1444,22 +7176,19 @@ "eslint-visitor-keys": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==" } } }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, "esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", - "dev": true, "requires": { "estraverse": "^5.1.0" }, @@ -1467,8 +7196,7 @@ "estraverse": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==" } } }, @@ -1501,8 +7229,7 @@ "esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "evp_bytestokey": { "version": "1.0.3", @@ -1529,8 +7256,7 @@ "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "fast-glob": { "version": "3.2.7", @@ -1548,14 +7274,12 @@ "fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fastq": { "version": "1.13.0", @@ -1570,7 +7294,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, "requires": { "flat-cache": "^3.0.4" } @@ -1609,7 +7332,6 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", - "dev": true, "requires": { "flatted": "^3.1.0", "rimraf": "^3.0.2" @@ -1618,8 +7340,7 @@ "flatted": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.2.tgz", - "integrity": "sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA==", - "dev": true + "integrity": "sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA==" }, "foreach": { "version": "2.0.5", @@ -1667,8 +7388,7 @@ "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { "version": "2.3.2", @@ -1686,8 +7406,7 @@ "functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" }, "fwd-stream": { "version": "1.0.4", @@ -1797,7 +7516,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", - "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -1811,7 +7529,6 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, "requires": { "is-glob": "^4.0.1" } @@ -1820,7 +7537,6 @@ "version": "13.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", - "dev": true, "requires": { "type-fest": "^0.20.2" } @@ -1923,8 +7639,7 @@ "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" }, "has-unicode": { "version": "2.0.1", @@ -2025,7 +7740,6 @@ "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, "requires": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -2034,8 +7748,7 @@ "imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" }, "indent-string": { "version": "4.0.0", @@ -2053,7 +7766,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "requires": { "once": "^1.3.0", "wrappy": "1" @@ -2062,8 +7774,7 @@ "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "is": { "version": "0.2.7", @@ -2098,8 +7809,7 @@ "is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" }, "is-fullwidth-code-point": { "version": "1.0.0", @@ -2114,7 +7824,6 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, "requires": { "is-extglob": "^2.1.1" } @@ -2179,8 +7888,7 @@ "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "isstream": { "version": "0.1.2", @@ -2208,14 +7916,12 @@ "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "js-yaml": { "version": "3.14.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -2234,22 +7940,20 @@ "dev": true }, "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", "dev": true }, "json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" }, "json-stringify-safe": { "version": "5.0.1", @@ -2267,14 +7971,14 @@ } }, "jsprim": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", "dev": true, "requires": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", - "json-schema": "0.2.3", + "json-schema": "0.4.0", "verror": "1.10.0" } }, @@ -2500,7 +8204,6 @@ "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, "requires": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" @@ -2554,20 +8257,17 @@ "lodash.clonedeep": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", - "dev": true + "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=" }, "lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" }, "lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", - "dev": true + "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=" }, "lottie-web": { "version": "5.7.14", @@ -2578,7 +8278,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "requires": { "yallist": "^4.0.0" } @@ -2743,7 +8442,6 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, "requires": { "brace-expansion": "^1.1.7" } @@ -2802,8 +8500,7 @@ "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "nan": { "version": "2.15.0", @@ -2820,8 +8517,7 @@ "natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" }, "node-gyp": { "version": "7.1.2", @@ -2991,7 +8687,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, "requires": { "wrappy": "1" } @@ -3000,7 +8695,6 @@ "version": "0.9.1", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", - "dev": true, "requires": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", @@ -3044,7 +8738,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, "requires": { "callsites": "^3.0.0" } @@ -3083,14 +8776,12 @@ "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" }, "path-parse": { "version": "1.0.7", @@ -3141,8 +8832,7 @@ "prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==" }, "prettier": { "version": "2.4.1", @@ -3165,8 +8855,7 @@ "progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", - "dev": true + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==" }, "prr": { "version": "1.0.1", @@ -3205,8 +8894,7 @@ "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, "qs": { "version": "6.5.2", @@ -3355,8 +9043,7 @@ "regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==" }, "request": { "version": "2.88.2", @@ -3403,8 +9090,7 @@ "require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==" }, "require-main-filename": { "version": "2.0.0", @@ -3431,8 +9117,7 @@ "resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==" }, "ret": { "version": "0.1.15", @@ -3450,7 +9135,6 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, "requires": { "glob": "^7.1.3" } @@ -3610,7 +9294,8 @@ "version": "1.6.1", "resolved": "https://registry.npmjs.org/rollup-plugin-web-worker-loader/-/rollup-plugin-web-worker-loader-1.6.1.tgz", "integrity": "sha512-4QywQSz1NXFHKdyiou16mH3ijpcfLtLGOrAqvAqu1Gx+P8+zj+3gwC2BSL/VW1d+LW4nIHC8F7d7OXhs9UdR2A==", - "dev": true + "dev": true, + "requires": {} }, "rollup-pluginutils": { "version": "2.8.2", @@ -3723,7 +9408,6 @@ "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, "requires": { "lru-cache": "^6.0.0" } @@ -3757,7 +9441,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "requires": { "shebang-regex": "^3.0.0" } @@ -3765,8 +9448,7 @@ "shebang-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" }, "signal-exit": { "version": "3.0.5", @@ -3811,7 +9493,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, "requires": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", @@ -3821,8 +9502,7 @@ "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" } } }, @@ -3906,8 +9586,7 @@ "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" }, "sshpk": { "version": "1.16.1", @@ -3943,6 +9622,15 @@ "readable-stream": "^2.0.1" } }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, "string-range": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/string-range/-/string-range-1.2.2.tgz", @@ -3977,20 +9665,10 @@ } } }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "requires": { - "safe-buffer": "~5.1.0" - } - }, "strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "requires": { "ansi-regex": "^5.0.1" } @@ -4007,14 +9685,12 @@ "strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==" }, "supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "requires": { "has-flag": "^4.0.0" } @@ -4022,8 +9698,7 @@ "svelte": { "version": "3.44.0", "resolved": "https://registry.npmjs.org/svelte/-/svelte-3.44.0.tgz", - "integrity": "sha512-zWACSJBSncGiDvFfYOMFGNV5zDLOlyhftmO5yOZ0lEtQMptpElaRtl39MWz1+lYCpwUq4F3Q2lTzI9TrTL+eMA==", - "dev": true + "integrity": "sha512-zWACSJBSncGiDvFfYOMFGNV5zDLOlyhftmO5yOZ0lEtQMptpElaRtl39MWz1+lYCpwUq4F3Q2lTzI9TrTL+eMA==" }, "svelte-check": { "version": "2.2.7", @@ -4076,7 +9751,6 @@ "version": "6.7.2", "resolved": "https://registry.npmjs.org/table/-/table-6.7.2.tgz", "integrity": "sha512-UFZK67uvyNivLeQbVtkiUs8Uuuxv24aSL4/Vil2PJVtMgU8Lx0CYkP12uCGa3kjyQzOSgV1+z9Wkb82fCGsO0g==", - "dev": true, "requires": { "ajv": "^8.0.1", "lodash.clonedeep": "^4.5.0", @@ -4090,7 +9764,6 @@ "version": "8.6.3", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.3.tgz", "integrity": "sha512-SMJOdDP6LqTkD0Uq8qLi+gMwSt0imXLSV080qFVwJCpH9U6Mb+SUGHAXM0KNbcBPguytWyvFxcHgMLe2D2XSpw==", - "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -4101,26 +9774,22 @@ "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" }, "json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" }, "string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -4173,8 +9842,7 @@ "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", - "dev": true + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" }, "threads": { "version": "1.7.0", @@ -4245,6 +9913,11 @@ "glob": "^7.1.2" } }, + "tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + }, "tsutils": { "version": "3.21.0", "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", @@ -4281,7 +9954,6 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, "requires": { "prelude-ls": "^1.2.1" } @@ -4289,8 +9961,7 @@ "type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==" }, "typedarray": { "version": "0.0.6", @@ -4320,7 +9991,6 @@ "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, "requires": { "punycode": "^2.1.0" } @@ -4345,8 +10015,7 @@ "v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true + "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==" }, "validate-npm-package-license": { "version": "3.0.4", @@ -4387,7 +10056,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "requires": { "isexe": "^2.0.0" } @@ -4410,8 +10078,7 @@ "word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==" }, "wrap-ansi": { "version": "5.1.0", @@ -4485,14 +10152,14 @@ "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "ws": { "version": "7.5.5", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.5.tgz", "integrity": "sha512-BAkMFcAzl8as1G/hArkxOxq3G7pjUqQ3gzYbLL0/5zNkph70e+lCoxBGnm6AW1+/aiNeV4fnKqZ8m4GZewmH2w==", - "dev": true + "dev": true, + "requires": {} }, "xtend": { "version": "2.2.0", @@ -4509,8 +10176,7 @@ "yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "yargs": { "version": "13.3.2", diff --git a/contracts/wasm/fairroulette/frontend/package.json b/contracts/wasm/fairroulette/frontend/package.json index 3ea890b88c..60f9d89948 100644 --- a/contracts/wasm/fairroulette/frontend/package.json +++ b/contracts/wasm/fairroulette/frontend/package.json @@ -49,6 +49,7 @@ "dependencies": { "@babel/eslint-parser": "^7.15.8", "lottie-web": "^5.7.13", - "svelte-router-spa": "^6.0.2" + "svelte-router-spa": "^6.0.2", + "tslib": "^2.3.1" } } diff --git a/contracts/wasm/fairroulette/frontend/waypoint.hcl b/contracts/wasm/fairroulette/frontend/waypoint.hcl index d0b5e41d96..3aebf200dd 100644 --- a/contracts/wasm/fairroulette/frontend/waypoint.hcl +++ b/contracts/wasm/fairroulette/frontend/waypoint.hcl @@ -18,7 +18,6 @@ variable "goshimmer_url" { variable "chainid" { type = string - default = "be1j1GwB971eEAVfDmNFUtUfQ7rHEEF43Mz7yTP2bdkH" } variable "adminWhitelist" { @@ -36,7 +35,7 @@ variable "ghcr" { # An application to deploy. app "fairroulette" { # Build specifies how an application should be deployed. In this case, - # we'll build using a Dockerfile and keeping it in a local registry. + # we'll build using a Dockerfile and keeping it in a github registry. build { use "docker" { disable_entrypoint = true diff --git a/contracts/wasm/fairroulette/go/fairroulette/consts.go b/contracts/wasm/fairroulette/go/fairroulette/consts.go index 69bdc218e0..6ef1d12317 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/consts.go +++ b/contracts/wasm/fairroulette/go/fairroulette/consts.go @@ -7,12 +7,12 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "fairroulette" ScDescription = "" - HScName = wasmlib.ScHname(0xdf79d138) + HScName = wasmtypes.ScHname(0xdf79d138) ) const ( @@ -49,13 +49,13 @@ const ( ) const ( - HFuncForcePayout = wasmlib.ScHname(0x555a4c4f) - HFuncForceReset = wasmlib.ScHname(0xa331951e) - HFuncPayWinners = wasmlib.ScHname(0xfb2b0144) - HFuncPlaceBet = wasmlib.ScHname(0xdfba7d1b) - HFuncPlayPeriod = wasmlib.ScHname(0xcb94b293) - HViewLastWinningNumber = wasmlib.ScHname(0x2f5f09fe) - HViewRoundNumber = wasmlib.ScHname(0x0dcfe520) - HViewRoundStartedAt = wasmlib.ScHname(0x725de8b4) - HViewRoundStatus = wasmlib.ScHname(0x145053b5) + HFuncForcePayout = wasmtypes.ScHname(0x555a4c4f) + HFuncForceReset = wasmtypes.ScHname(0xa331951e) + HFuncPayWinners = wasmtypes.ScHname(0xfb2b0144) + HFuncPlaceBet = wasmtypes.ScHname(0xdfba7d1b) + HFuncPlayPeriod = wasmtypes.ScHname(0xcb94b293) + HViewLastWinningNumber = wasmtypes.ScHname(0x2f5f09fe) + HViewRoundNumber = wasmtypes.ScHname(0x0dcfe520) + HViewRoundStartedAt = wasmtypes.ScHname(0x725de8b4) + HViewRoundStatus = wasmtypes.ScHname(0x145053b5) ) diff --git a/contracts/wasm/fairroulette/go/fairroulette/contract.go b/contracts/wasm/fairroulette/go/fairroulette/contract.go index 6f324490b1..6cd760fd22 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/contract.go +++ b/contracts/wasm/fairroulette/go/fairroulette/contract.go @@ -7,7 +7,7 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type ForcePayoutCall struct { Func *wasmlib.ScFunc @@ -69,36 +69,36 @@ func (sc Funcs) PayWinners(ctx wasmlib.ScFuncCallContext) *PayWinnersCall { func (sc Funcs) PlaceBet(ctx wasmlib.ScFuncCallContext) *PlaceBetCall { f := &PlaceBetCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncPlaceBet)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) PlayPeriod(ctx wasmlib.ScFuncCallContext) *PlayPeriodCall { f := &PlayPeriodCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncPlayPeriod)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) LastWinningNumber(ctx wasmlib.ScViewCallContext) *LastWinningNumberCall { f := &LastWinningNumberCall{Func: wasmlib.NewScView(ctx, HScName, HViewLastWinningNumber)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) RoundNumber(ctx wasmlib.ScViewCallContext) *RoundNumberCall { f := &RoundNumberCall{Func: wasmlib.NewScView(ctx, HScName, HViewRoundNumber)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) RoundStartedAt(ctx wasmlib.ScViewCallContext) *RoundStartedAtCall { f := &RoundStartedAtCall{Func: wasmlib.NewScView(ctx, HScName, HViewRoundStartedAt)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) RoundStatus(ctx wasmlib.ScViewCallContext) *RoundStatusCall { f := &RoundStatusCall{Func: wasmlib.NewScView(ctx, HScName, HViewRoundStatus)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/fairroulette/go/fairroulette/events.go b/contracts/wasm/fairroulette/go/fairroulette/events.go index 353c75c871..905109b708 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/events.go +++ b/contracts/wasm/fairroulette/go/fairroulette/events.go @@ -5,46 +5,48 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -//nolint:gocritic package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) type FairRouletteEvents struct{} -func (e FairRouletteEvents) Bet(address wasmlib.ScAddress, amount int64, number int64) { - wasmlib.NewEventEncoder("fairroulette.bet"). - Address(address). - Int64(amount). - Int64(number). - Emit() +func (e FairRouletteEvents) Bet(address wasmtypes.ScAddress, amount uint64, number uint16) { + evt := wasmlib.NewEventEncoder("fairroulette.bet") + evt.Encode(wasmtypes.AddressToString(address)) + evt.Encode(wasmtypes.Uint64ToString(amount)) + evt.Encode(wasmtypes.Uint16ToString(number)) + evt.Emit() } -func (e FairRouletteEvents) Payout(address wasmlib.ScAddress, amount int64) { - wasmlib.NewEventEncoder("fairroulette.payout"). - Address(address). - Int64(amount). - Emit() +func (e FairRouletteEvents) Payout(address wasmtypes.ScAddress, amount uint64) { + evt := wasmlib.NewEventEncoder("fairroulette.payout") + evt.Encode(wasmtypes.AddressToString(address)) + evt.Encode(wasmtypes.Uint64ToString(amount)) + evt.Emit() } -func (e FairRouletteEvents) Round(number int64) { - wasmlib.NewEventEncoder("fairroulette.round"). - Int64(number). - Emit() +func (e FairRouletteEvents) Round(number uint32) { + evt := wasmlib.NewEventEncoder("fairroulette.round") + evt.Encode(wasmtypes.Uint32ToString(number)) + evt.Emit() } func (e FairRouletteEvents) Start() { - wasmlib.NewEventEncoder("fairroulette.start"). - Emit() + evt := wasmlib.NewEventEncoder("fairroulette.start") + evt.Emit() } func (e FairRouletteEvents) Stop() { - wasmlib.NewEventEncoder("fairroulette.stop"). - Emit() + evt := wasmlib.NewEventEncoder("fairroulette.stop") + evt.Emit() } -func (e FairRouletteEvents) Winner(number int64) { - wasmlib.NewEventEncoder("fairroulette.winner"). - Int64(number). - Emit() +func (e FairRouletteEvents) Winner(number uint16) { + evt := wasmlib.NewEventEncoder("fairroulette.winner") + evt.Encode(wasmtypes.Uint16ToString(number)) + evt.Emit() } diff --git a/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go b/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go index 729953c23c..cfc5bb5f21 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go +++ b/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go @@ -10,7 +10,8 @@ package fairroulette import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) // Define some default configuration parameters. @@ -39,7 +40,8 @@ func funcPlaceBet(ctx wasmlib.ScFuncContext, f *PlaceBetContext) { // Get the array of current bets from state storage. bets := f.State.Bets() - for i := int32(0); i < bets.Length(); i++ { + nrOfBets := bets.Length() + for i := uint32(0); i < nrOfBets; i++ { bet := bets.GetBet(i).Value() if bet.Better.Address() == ctx.Caller().Address() { @@ -60,7 +62,7 @@ func funcPlaceBet(ctx wasmlib.ScFuncContext, f *PlaceBetContext) { incoming := ctx.Incoming() // Retrieve the amount of plain iota tokens that are part of the incoming balance. - amount := incoming.Balance(wasmlib.IOTA) + amount := incoming.Balance(wasmtypes.IOTA) // Require that there are actually some plain iotas there ctx.Require(amount > 0, "empty bet") @@ -74,17 +76,14 @@ func funcPlaceBet(ctx wasmlib.ScFuncContext, f *PlaceBetContext) { Number: number, } - // Determine what the next bet number is by retrieving the length of the bets array. - betNr := bets.Length() - // Append the bet data to the bets array. The bet array will automatically take care // of serializing the bet struct into a bytes representation. - bets.GetBet(betNr).SetValue(bet) + bets.AppendBet().SetValue(bet) f.Events.Bet(bet.Better.Address(), bet.Amount, bet.Number) // Was this the first bet of this round? - if betNr == 0 { + if nrOfBets == 0 { // Yes it was, query the state for the length of the playing period in seconds by // retrieving the playPeriod value from state storage playPeriod := f.State.PlayPeriod().Value() @@ -100,7 +99,7 @@ func funcPlaceBet(ctx wasmlib.ScFuncContext, f *PlaceBetContext) { f.State.RoundStatus().SetValue(1) // timestamp is nanotime, divide by NanoTimeDivider to get seconds => common unix timestamp - timestamp := int32(ctx.Timestamp() / NanoTimeDivider) + timestamp := uint32(ctx.Timestamp() / NanoTimeDivider) f.State.RoundStartedAt().SetValue(timestamp) f.Events.Start() @@ -115,7 +114,7 @@ func funcPlaceBet(ctx wasmlib.ScFuncContext, f *PlaceBetContext) { // amount of seconds. This will lock in the playing period, during which more bets can // be placed. Once the 'payWinners' function gets triggered by the ISCP it will gather // all bets up to that moment as the ones to consider for determining the winner. - ScFuncs.PayWinners(ctx).Func.Delay(playPeriod).TransferIotas(1).Post() + ScFuncs.PayWinners(ctx).Func.Delay(playPeriod).Post() } } } @@ -130,7 +129,7 @@ func funcPayWinners(ctx wasmlib.ScFuncContext, f *PayWinnersContext) { // generator will use the next 8 bytes from the hash as its random Int64 number and once // it runs out of data it simply hashes the previous hash for a next pseudo-random sequence. // Here we determine the winning number for this round in the range of 1 thru MaxNumber. - winningNumber := ctx.Random(MaxNumber-1) + 1 + winningNumber := uint16(ctx.Random(MaxNumber-1) + 1) // Save the last winning number in state storage under 'lastWinningNumber' so that there // is (limited) time for people to call the 'getLastWinningNumber' View to verify the last @@ -143,18 +142,18 @@ func funcPayWinners(ctx wasmlib.ScFuncContext, f *PayWinnersContext) { // Keep track of the total bet amount, the total win amount, and all the winners. // Note how we decided to keep the winners in a local vector instead of creating // yet another array in state storage or having to go through lockedBets again. - totalBetAmount := int64(0) - totalWinAmount := int64(0) + totalBetAmount := uint64(0) + totalWinAmount := uint64(0) winners := make([]*Bet, 0) // Get the 'bets' array in state storage. bets := f.State.Bets() // Determine the amount of bets in the 'bets' array. - nrBets := bets.Length() + nrOfBets := bets.Length() // Loop through all indexes of the 'bets' array. - for i := int32(0); i < nrBets; i++ { + for i := uint32(0); i < nrOfBets; i++ { // Retrieve the bet stored at the next index bet := bets.GetBet(i).Value() @@ -186,7 +185,7 @@ func funcPayWinners(ctx wasmlib.ScFuncContext, f *PayWinnersContext) { // a small percentage that would go to the owner of the smart contract as hosting payment. // Keep track of the total payout so we can calculate the remainder after truncation. - totalPayout := int64(0) + totalPayout := uint64(0) // Loop through all winners. size := len(winners) @@ -213,7 +212,7 @@ func funcPayWinners(ctx wasmlib.ScFuncContext, f *PayWinnersContext) { // of the winner. The transfer_to_address() method receives the address value and // the proxy to the new transfers map on the host, and will call the corresponding // host sandbox function with these values. - ctx.TransferToAddress(bet.Better.Address(), transfers) + ctx.Send(bet.Better.Address(), transfers) } // Announce who got sent what as event. @@ -228,7 +227,7 @@ func funcPayWinners(ctx wasmlib.ScFuncContext, f *PayWinnersContext) { transfers := wasmlib.NewScTransferIotas(remainder) // Send the remainder to the contract creator. - ctx.TransferToAddress(ctx.ContractCreator().Address(), transfers) + ctx.Send(ctx.ContractCreator().Address(), transfers) } // Set round status to 0, send out event to notify that the round has ended diff --git a/contracts/wasm/fairroulette/go/fairroulette/keys.go b/contracts/wasm/fairroulette/go/fairroulette/keys.go deleted file mode 100644 index 3f95a7a418..0000000000 --- a/contracts/wasm/fairroulette/go/fairroulette/keys.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package fairroulette - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamNumber = 0 - IdxParamPlayPeriod = 1 - - IdxResultLastWinningNumber = 2 - IdxResultRoundNumber = 3 - IdxResultRoundStartedAt = 4 - IdxResultRoundStatus = 5 - - IdxStateBets = 6 - IdxStateLastWinningNumber = 7 - IdxStatePlayPeriod = 8 - IdxStateRoundNumber = 9 - IdxStateRoundStartedAt = 10 - IdxStateRoundStatus = 11 -) - -const keyMapLen = 12 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamNumber, - ParamPlayPeriod, - ResultLastWinningNumber, - ResultRoundNumber, - ResultRoundStartedAt, - ResultRoundStatus, - StateBets, - StateLastWinningNumber, - StatePlayPeriod, - StateRoundNumber, - StateRoundStartedAt, - StateRoundStatus, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/fairroulette/go/fairroulette/lib.go b/contracts/wasm/fairroulette/go/fairroulette/lib.go index 5ca3bb14f4..1d9faef4d7 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/lib.go +++ b/contracts/wasm/fairroulette/go/fairroulette/lib.go @@ -7,23 +7,42 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncForcePayout, funcForcePayoutThunk) - exports.AddFunc(FuncForceReset, funcForceResetThunk) - exports.AddFunc(FuncPayWinners, funcPayWinnersThunk) - exports.AddFunc(FuncPlaceBet, funcPlaceBetThunk) - exports.AddFunc(FuncPlayPeriod, funcPlayPeriodThunk) - exports.AddView(ViewLastWinningNumber, viewLastWinningNumberThunk) - exports.AddView(ViewRoundNumber, viewRoundNumberThunk) - exports.AddView(ViewRoundStartedAt, viewRoundStartedAtThunk) - exports.AddView(ViewRoundStatus, viewRoundStatusThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncForcePayout, + FuncForceReset, + FuncPayWinners, + FuncPlaceBet, + FuncPlayPeriod, + ViewLastWinningNumber, + ViewRoundNumber, + ViewRoundStartedAt, + ViewRoundStatus, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcForcePayoutThunk, + funcForceResetThunk, + funcPayWinnersThunk, + funcPlaceBetThunk, + funcPlayPeriodThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewLastWinningNumberThunk, + viewRoundNumberThunk, + viewRoundStartedAtThunk, + viewRoundStatusThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type ForcePayoutContext struct { @@ -33,15 +52,15 @@ type ForcePayoutContext struct { func funcForcePayoutThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairroulette.funcForcePayout") - - // only SC creator can restart the round forcefully - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &ForcePayoutContext{ State: MutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC creator can restart the round forcefully + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + funcForcePayout(ctx, f) ctx.Log("fairroulette.funcForcePayout ok") } @@ -53,15 +72,15 @@ type ForceResetContext struct { func funcForceResetThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairroulette.funcForceReset") - - // only SC creator can restart the round forcefully - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &ForceResetContext{ State: MutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC creator can restart the round forcefully + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + funcForceReset(ctx, f) ctx.Log("fairroulette.funcForceReset ok") } @@ -73,15 +92,15 @@ type PayWinnersContext struct { func funcPayWinnersThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairroulette.funcPayWinners") - - // only SC itself can invoke this function - ctx.Require(ctx.Caller() == ctx.AccountID(), "no permission") - f := &PayWinnersContext{ State: MutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC itself can invoke this function + ctx.Require(ctx.Caller() == ctx.AccountID(), "no permission") + funcPayWinners(ctx, f) ctx.Log("fairroulette.funcPayWinners ok") } @@ -96,10 +115,10 @@ func funcPlaceBetThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairroulette.funcPlaceBet") f := &PlaceBetContext{ Params: ImmutablePlaceBetParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Number().Exists(), "missing mandatory number") @@ -115,18 +134,18 @@ type PlayPeriodContext struct { func funcPlayPeriodThunk(ctx wasmlib.ScFuncContext) { ctx.Log("fairroulette.funcPlayPeriod") - - // only SC creator can update the play period - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &PlayPeriodContext{ Params: ImmutablePlayPeriodParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // only SC creator can update the play period + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + ctx.Require(f.Params.PlayPeriod().Exists(), "missing mandatory playPeriod") funcPlayPeriod(ctx, f) ctx.Log("fairroulette.funcPlayPeriod ok") @@ -139,15 +158,17 @@ type LastWinningNumberContext struct { func viewLastWinningNumberThunk(ctx wasmlib.ScViewContext) { ctx.Log("fairroulette.viewLastWinningNumber") + results := wasmlib.NewScDict() f := &LastWinningNumberContext{ Results: MutableLastWinningNumberResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewLastWinningNumber(ctx, f) + ctx.Results(results) ctx.Log("fairroulette.viewLastWinningNumber ok") } @@ -158,15 +179,17 @@ type RoundNumberContext struct { func viewRoundNumberThunk(ctx wasmlib.ScViewContext) { ctx.Log("fairroulette.viewRoundNumber") + results := wasmlib.NewScDict() f := &RoundNumberContext{ Results: MutableRoundNumberResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewRoundNumber(ctx, f) + ctx.Results(results) ctx.Log("fairroulette.viewRoundNumber ok") } @@ -177,15 +200,17 @@ type RoundStartedAtContext struct { func viewRoundStartedAtThunk(ctx wasmlib.ScViewContext) { ctx.Log("fairroulette.viewRoundStartedAt") + results := wasmlib.NewScDict() f := &RoundStartedAtContext{ Results: MutableRoundStartedAtResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewRoundStartedAt(ctx, f) + ctx.Results(results) ctx.Log("fairroulette.viewRoundStartedAt ok") } @@ -196,14 +221,16 @@ type RoundStatusContext struct { func viewRoundStatusThunk(ctx wasmlib.ScViewContext) { ctx.Log("fairroulette.viewRoundStatus") + results := wasmlib.NewScDict() f := &RoundStatusContext{ Results: MutableRoundStatusResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableFairRouletteState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewRoundStatus(ctx, f) + ctx.Results(results) ctx.Log("fairroulette.viewRoundStatus ok") } diff --git a/contracts/wasm/fairroulette/go/fairroulette/params.go b/contracts/wasm/fairroulette/go/fairroulette/params.go index 7a02cc2470..37eb25c28f 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/params.go +++ b/contracts/wasm/fairroulette/go/fairroulette/params.go @@ -7,36 +7,36 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutablePlaceBetParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutablePlaceBetParams) Number() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamNumber)) +func (s ImmutablePlaceBetParams) Number() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(ParamNumber)) } type MutablePlaceBetParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutablePlaceBetParams) Number() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamNumber)) +func (s MutablePlaceBetParams) Number() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(ParamNumber)) } type ImmutablePlayPeriodParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutablePlayPeriodParams) PlayPeriod() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamPlayPeriod)) +func (s ImmutablePlayPeriodParams) PlayPeriod() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamPlayPeriod)) } type MutablePlayPeriodParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutablePlayPeriodParams) PlayPeriod() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamPlayPeriod)) +func (s MutablePlayPeriodParams) PlayPeriod() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamPlayPeriod)) } diff --git a/contracts/wasm/fairroulette/go/fairroulette/results.go b/contracts/wasm/fairroulette/go/fairroulette/results.go index 8f4946533c..988371e5a9 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/results.go +++ b/contracts/wasm/fairroulette/go/fairroulette/results.go @@ -7,68 +7,68 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableLastWinningNumberResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableLastWinningNumberResults) LastWinningNumber() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultLastWinningNumber)) +func (s ImmutableLastWinningNumberResults) LastWinningNumber() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(ResultLastWinningNumber)) } type MutableLastWinningNumberResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableLastWinningNumberResults) LastWinningNumber() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultLastWinningNumber)) +func (s MutableLastWinningNumberResults) LastWinningNumber() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(ResultLastWinningNumber)) } type ImmutableRoundNumberResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRoundNumberResults) RoundNumber() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultRoundNumber)) +func (s ImmutableRoundNumberResults) RoundNumber() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultRoundNumber)) } type MutableRoundNumberResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRoundNumberResults) RoundNumber() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultRoundNumber)) +func (s MutableRoundNumberResults) RoundNumber() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultRoundNumber)) } type ImmutableRoundStartedAtResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRoundStartedAtResults) RoundStartedAt() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultRoundStartedAt)) +func (s ImmutableRoundStartedAtResults) RoundStartedAt() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultRoundStartedAt)) } type MutableRoundStartedAtResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRoundStartedAtResults) RoundStartedAt() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultRoundStartedAt)) +func (s MutableRoundStartedAtResults) RoundStartedAt() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultRoundStartedAt)) } type ImmutableRoundStatusResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRoundStatusResults) RoundStatus() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ResultRoundStatus)) +func (s ImmutableRoundStatusResults) RoundStatus() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(ResultRoundStatus)) } type MutableRoundStatusResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRoundStatusResults) RoundStatus() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ResultRoundStatus)) +func (s MutableRoundStatusResults) RoundStatus() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(ResultRoundStatus)) } diff --git a/contracts/wasm/fairroulette/go/fairroulette/state.go b/contracts/wasm/fairroulette/go/fairroulette/state.go index e7ce804afe..b481a01364 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/state.go +++ b/contracts/wasm/fairroulette/go/fairroulette/state.go @@ -7,67 +7,70 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableBet struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableBet) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableBet) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableBet) GetBet(index int32) ImmutableBet { - return ImmutableBet{objID: a.objID, keyID: wasmlib.Key32(index)} +func (a ArrayOfImmutableBet) GetBet(index uint32) ImmutableBet { + return ImmutableBet{proxy: a.proxy.Index(index)} } type ImmutableFairRouletteState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableFairRouletteState) Bets() ArrayOfImmutableBet { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBets), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBet{objID: arrID} + return ArrayOfImmutableBet{proxy: s.proxy.Root(StateBets)} } -func (s ImmutableFairRouletteState) LastWinningNumber() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateLastWinningNumber)) +func (s ImmutableFairRouletteState) LastWinningNumber() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(StateLastWinningNumber)) } -func (s ImmutableFairRouletteState) PlayPeriod() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(StatePlayPeriod)) +func (s ImmutableFairRouletteState) PlayPeriod() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(StatePlayPeriod)) } -func (s ImmutableFairRouletteState) RoundNumber() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateRoundNumber)) +func (s ImmutableFairRouletteState) RoundNumber() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(StateRoundNumber)) } -func (s ImmutableFairRouletteState) RoundStartedAt() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(StateRoundStartedAt)) +func (s ImmutableFairRouletteState) RoundStartedAt() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(StateRoundStartedAt)) } -func (s ImmutableFairRouletteState) RoundStatus() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(StateRoundStatus)) +func (s ImmutableFairRouletteState) RoundStatus() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(StateRoundStatus)) } type ArrayOfMutableBet struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableBet) AppendBet() MutableBet { + return MutableBet{proxy: a.proxy.Append()} } func (a ArrayOfMutableBet) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableBet) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableBet) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableBet) GetBet(index int32) MutableBet { - return MutableBet{objID: a.objID, keyID: wasmlib.Key32(index)} +func (a ArrayOfMutableBet) GetBet(index uint32) MutableBet { + return MutableBet{proxy: a.proxy.Index(index)} } type MutableFairRouletteState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableFairRouletteState) AsImmutable() ImmutableFairRouletteState { @@ -75,26 +78,25 @@ func (s MutableFairRouletteState) AsImmutable() ImmutableFairRouletteState { } func (s MutableFairRouletteState) Bets() ArrayOfMutableBet { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateBets), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES) - return ArrayOfMutableBet{objID: arrID} + return ArrayOfMutableBet{proxy: s.proxy.Root(StateBets)} } -func (s MutableFairRouletteState) LastWinningNumber() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateLastWinningNumber)) +func (s MutableFairRouletteState) LastWinningNumber() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(StateLastWinningNumber)) } -func (s MutableFairRouletteState) PlayPeriod() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(StatePlayPeriod)) +func (s MutableFairRouletteState) PlayPeriod() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(StatePlayPeriod)) } -func (s MutableFairRouletteState) RoundNumber() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateRoundNumber)) +func (s MutableFairRouletteState) RoundNumber() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(StateRoundNumber)) } -func (s MutableFairRouletteState) RoundStartedAt() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(StateRoundStartedAt)) +func (s MutableFairRouletteState) RoundStartedAt() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(StateRoundStartedAt)) } -func (s MutableFairRouletteState) RoundStatus() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(StateRoundStatus)) +func (s MutableFairRouletteState) RoundStatus() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(StateRoundStatus)) } diff --git a/contracts/wasm/fairroulette/go/fairroulette/structs.go b/contracts/wasm/fairroulette/go/fairroulette/structs.go index 944ed41420..2f3e20f0d2 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/structs.go +++ b/contracts/wasm/fairroulette/go/fairroulette/structs.go @@ -7,62 +7,60 @@ package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type Bet struct { - Amount int64 - Better wasmlib.ScAgentID - Number int64 + Amount uint64 + Better wasmtypes.ScAgentID + Number uint16 } -func NewBetFromBytes(bytes []byte) *Bet { - decode := wasmlib.NewBytesDecoder(bytes) +func NewBetFromBytes(buf []byte) *Bet { + dec := wasmtypes.NewWasmDecoder(buf) data := &Bet{} - data.Amount = decode.Int64() - data.Better = decode.AgentID() - data.Number = decode.Int64() - decode.Close() + data.Amount = wasmtypes.Uint64Decode(dec) + data.Better = wasmtypes.AgentIDDecode(dec) + data.Number = wasmtypes.Uint16Decode(dec) + dec.Close() return data } func (o *Bet) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Int64(o.Amount). - AgentID(o.Better). - Int64(o.Number). - Data() + enc := wasmtypes.NewWasmEncoder() + wasmtypes.Uint64Encode(enc, o.Amount) + wasmtypes.AgentIDEncode(enc, o.Better) + wasmtypes.Uint16Encode(enc, o.Number) + return enc.Buf() } type ImmutableBet struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o ImmutableBet) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o ImmutableBet) Value() *Bet { - return NewBetFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewBetFromBytes(o.proxy.Get()) } type MutableBet struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o MutableBet) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } func (o MutableBet) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o MutableBet) SetValue(value *Bet) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } func (o MutableBet) Value() *Bet { - return NewBetFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewBetFromBytes(o.proxy.Get()) } diff --git a/contracts/wasm/fairroulette/go/main.go b/contracts/wasm/fairroulette/go/main.go index c4f5e312dc..88f71a564a 100644 --- a/contracts/wasm/fairroulette/go/main.go +++ b/contracts/wasm/fairroulette/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/fairroulette/go/fairroulette" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + fairroulette.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - fairroulette.OnLoad() + fairroulette.OnLoad(-1) } diff --git a/contracts/wasm/fairroulette/schema.yaml b/contracts/wasm/fairroulette/schema.yaml index d895358ffe..571eec7685 100644 --- a/contracts/wasm/fairroulette/schema.yaml +++ b/contracts/wasm/fairroulette/schema.yaml @@ -3,36 +3,36 @@ description: "" events: bet: address: Address // address of better - amount: Int64 // amount of iotas to bet - number: Int64 // number to bet on + amount: Uint64 // amount of iotas to bet + number: Uint16 // number to bet on payout: address: Address // address of winner - amount: Int64 // amount of iotas won + amount: Uint64 // amount of iotas won round: - number: Int64 // current betting round number + number: Uint32 // current betting round number start: stop: winner: - number: Int64 // the winning number + number: Uint16 // the winning number structs: Bet: - amount: Int64 + amount: Uint64 better: AgentID - number: Int64 + number: Uint16 typedefs: {} state: bets: Bet[] - lastWinningNumber: Int64 - playPeriod: Int32 - roundNumber: Int64 - roundStartedAt: Int32 - roundStatus: Int16 + lastWinningNumber: Uint16 + playPeriod: Uint32 + roundNumber: Uint32 + roundStartedAt: Uint32 + roundStatus: Uint16 funcs: payWinners: access: self // only SC itself can invoke this function placeBet: params: - number: Int64 // the number a better bets on + number: Uint16 // the number a better bets on forceReset: access: creator // only SC creator can restart the round forcefully forcePayout: @@ -40,17 +40,17 @@ funcs: playPeriod: access: creator // only SC creator can update the play period params: - playPeriod: Int32 // number of minutes in one playing round + playPeriod: Uint32 // number of minutes in one playing round views: lastWinningNumber: results: - lastWinningNumber: Int64 + lastWinningNumber: Uint16 roundNumber: results: - roundNumber: Int64 + roundNumber: Uint32 roundStartedAt: results: - roundStartedAt: Int32 + roundStartedAt: Uint32 roundStatus: results: - roundStatus: Int16 + roundStatus: Uint16 diff --git a/contracts/wasm/fairroulette/src/contract.rs b/contracts/wasm/fairroulette/src/contract.rs index cfdd6239e9..c674bb5c12 100644 --- a/contracts/wasm/fairroulette/src/contract.rs +++ b/contracts/wasm/fairroulette/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct ForcePayoutCall { pub func: ScFunc, @@ -61,75 +56,75 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn force_payout(_ctx: & dyn ScFuncCallContext) -> ForcePayoutCall { + pub fn force_payout(_ctx: &dyn ScFuncCallContext) -> ForcePayoutCall { ForcePayoutCall { func: ScFunc::new(HSC_NAME, HFUNC_FORCE_PAYOUT), } } - pub fn force_reset(_ctx: & dyn ScFuncCallContext) -> ForceResetCall { + pub fn force_reset(_ctx: &dyn ScFuncCallContext) -> ForceResetCall { ForceResetCall { func: ScFunc::new(HSC_NAME, HFUNC_FORCE_RESET), } } - pub fn pay_winners(_ctx: & dyn ScFuncCallContext) -> PayWinnersCall { + pub fn pay_winners(_ctx: &dyn ScFuncCallContext) -> PayWinnersCall { PayWinnersCall { func: ScFunc::new(HSC_NAME, HFUNC_PAY_WINNERS), } } - pub fn place_bet(_ctx: & dyn ScFuncCallContext) -> PlaceBetCall { + pub fn place_bet(_ctx: &dyn ScFuncCallContext) -> PlaceBetCall { let mut f = PlaceBetCall { func: ScFunc::new(HSC_NAME, HFUNC_PLACE_BET), - params: MutablePlaceBetParams { id: 0 }, + params: MutablePlaceBetParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn play_period(_ctx: & dyn ScFuncCallContext) -> PlayPeriodCall { + pub fn play_period(_ctx: &dyn ScFuncCallContext) -> PlayPeriodCall { let mut f = PlayPeriodCall { func: ScFunc::new(HSC_NAME, HFUNC_PLAY_PERIOD), - params: MutablePlayPeriodParams { id: 0 }, + params: MutablePlayPeriodParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn last_winning_number(_ctx: & dyn ScViewCallContext) -> LastWinningNumberCall { + pub fn last_winning_number(_ctx: &dyn ScViewCallContext) -> LastWinningNumberCall { let mut f = LastWinningNumberCall { func: ScView::new(HSC_NAME, HVIEW_LAST_WINNING_NUMBER), - results: ImmutableLastWinningNumberResults { id: 0 }, + results: ImmutableLastWinningNumberResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn round_number(_ctx: & dyn ScViewCallContext) -> RoundNumberCall { + pub fn round_number(_ctx: &dyn ScViewCallContext) -> RoundNumberCall { let mut f = RoundNumberCall { func: ScView::new(HSC_NAME, HVIEW_ROUND_NUMBER), - results: ImmutableRoundNumberResults { id: 0 }, + results: ImmutableRoundNumberResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn round_started_at(_ctx: & dyn ScViewCallContext) -> RoundStartedAtCall { + pub fn round_started_at(_ctx: &dyn ScViewCallContext) -> RoundStartedAtCall { let mut f = RoundStartedAtCall { func: ScView::new(HSC_NAME, HVIEW_ROUND_STARTED_AT), - results: ImmutableRoundStartedAtResults { id: 0 }, + results: ImmutableRoundStartedAtResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn round_status(_ctx: & dyn ScViewCallContext) -> RoundStatusCall { + pub fn round_status(_ctx: &dyn ScViewCallContext) -> RoundStatusCall { let mut f = RoundStatusCall { func: ScView::new(HSC_NAME, HVIEW_ROUND_STATUS), - results: ImmutableRoundStatusResults { id: 0 }, + results: ImmutableRoundStatusResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/fairroulette/src/events.rs b/contracts/wasm/fairroulette/src/events.rs index be639f0726..5c27ee9975 100644 --- a/contracts/wasm/fairroulette/src/events.rs +++ b/contracts/wasm/fairroulette/src/events.rs @@ -6,6 +6,7 @@ // Change the json schema instead #![allow(dead_code)] +#![allow(unused_mut)] use wasmlib::*; @@ -14,38 +15,40 @@ pub struct FairRouletteEvents { impl FairRouletteEvents { - pub fn bet(&self, address: &ScAddress, amount: i64, number: i64) { - let mut encoder = EventEncoder::new("fairroulette.bet"); - encoder.address(&address); - encoder.int64(amount); - encoder.int64(number); - encoder.emit(); + pub fn bet(&self, address: &ScAddress, amount: u64, number: u16) { + let mut evt = EventEncoder::new("fairroulette.bet"); + evt.encode(&address_to_string(&address)); + evt.encode(&uint64_to_string(amount)); + evt.encode(&uint16_to_string(number)); + evt.emit(); } - pub fn payout(&self, address: &ScAddress, amount: i64) { - let mut encoder = EventEncoder::new("fairroulette.payout"); - encoder.address(&address); - encoder.int64(amount); - encoder.emit(); + pub fn payout(&self, address: &ScAddress, amount: u64) { + let mut evt = EventEncoder::new("fairroulette.payout"); + evt.encode(&address_to_string(&address)); + evt.encode(&uint64_to_string(amount)); + evt.emit(); } - pub fn round(&self, number: i64) { - let mut encoder = EventEncoder::new("fairroulette.round"); - encoder.int64(number); - encoder.emit(); + pub fn round(&self, number: u32) { + let mut evt = EventEncoder::new("fairroulette.round"); + evt.encode(&uint32_to_string(number)); + evt.emit(); } pub fn start(&self) { - EventEncoder::new("fairroulette.start").emit(); + let mut evt = EventEncoder::new("fairroulette.start"); + evt.emit(); } pub fn stop(&self) { - EventEncoder::new("fairroulette.stop").emit(); + let mut evt = EventEncoder::new("fairroulette.stop"); + evt.emit(); } - pub fn winner(&self, number: i64) { - let mut encoder = EventEncoder::new("fairroulette.winner"); - encoder.int64(number); - encoder.emit(); + pub fn winner(&self, number: u16) { + let mut evt = EventEncoder::new("fairroulette.winner"); + evt.encode(&uint16_to_string(number)); + evt.emit(); } } diff --git a/contracts/wasm/fairroulette/src/fairroulette.rs b/contracts/wasm/fairroulette/src/fairroulette.rs index 7b2bc95955..00424e9070 100644 --- a/contracts/wasm/fairroulette/src/fairroulette.rs +++ b/contracts/wasm/fairroulette/src/fairroulette.rs @@ -16,16 +16,16 @@ use crate::structs::*; // Define some default configuration parameters. // The maximum number one can bet on. The range of numbers starts at 1. -const MAX_NUMBER: i64 = 8; +const MAX_NUMBER: u16 = 8; // The default playing period of one betting round in seconds. -const DEFAULT_PLAY_PERIOD: i32 = 60; +const DEFAULT_PLAY_PERIOD: u32 = 60; // Enable this if you deploy the contract to an actual node. It will pay out the prize after a certain timeout. const ENABLE_SELF_POST: bool = true; // The number to divide nano seconds to seconds. -const NANO_TIME_DIVIDER: i64 = 1_000_000_000; +const NANO_TIME_DIVIDER: u64 = 1_000_000_000; // 'placeBet' is used by betters to place a bet on a number from 1 to MAX_NUMBER. The first // incoming bet triggers a betting round of configurable duration. After the playing period @@ -39,7 +39,8 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { // Get the array of current bets from state storage. let bets: ArrayOfMutableBet = f.state.bets(); - for i in 0..bets.length() { + let nr_of_bets = bets.length(); + for i in 0..nr_of_bets { let bet: Bet = bets.get_bet(i).value(); if bet.better.address() == ctx.caller().address() { @@ -48,8 +49,8 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { } // Since we are sure that the 'number' parameter actually exists we can - // retrieve its actual value into an i64. - let number: i64 = f.params.number().value(); + // retrieve its actual value into an u16. + let number: u16 = f.params.number().value(); // Require that the number is a valid number to bet on, otherwise panic out. ctx.require(number >= 1 && number <= MAX_NUMBER, "invalid number"); @@ -60,7 +61,7 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { let incoming: ScBalances = ctx.incoming(); // Retrieve the amount of plain iota tokens that are part of the incoming balance. - let amount: i64 = incoming.balance(&ScColor::IOTA); + let amount: u64 = incoming.balance(&ScColor::IOTA); // Require that there are actually some plain iotas there ctx.require(amount > 0, "empty bet"); @@ -74,20 +75,17 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { number: number, }; - // Determine what the next bet number is by retrieving the length of the bets array. - let bet_nr: i32 = bets.length(); - // Append the bet data to the bets array. The bet array will automatically take care // of serializing the bet struct into a bytes representation. - bets.get_bet(bet_nr).set_value(&bet); + bets.append_bet().set_value(&bet); f.events.bet(&bet.better.address(), bet.amount, bet.number); // Was this the first bet of this round? - if bet_nr == 0 { + if nr_of_bets == 0 { // Yes it was, query the state for the length of the playing period in seconds by // retrieving the playPeriod value from state storage - let mut play_period: i32 = f.state.play_period().value(); + let mut play_period: u32 = f.state.play_period().value(); // if the play period is less than 10 seconds we override it with the default duration. // Note that this will also happen when the play period was not set yet because in that @@ -101,7 +99,7 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { f.state.round_status().set_value(1); // timestamp is nanotime, divide by NANO_TIME_DIVIDER to get seconds => common unix timestamp - let timestamp = (ctx.timestamp() / NANO_TIME_DIVIDER) as i32; + let timestamp = (ctx.timestamp() / NANO_TIME_DIVIDER) as u32; f.state.round_started_at().set_value(timestamp); f.events.start(); @@ -116,10 +114,7 @@ pub fn func_place_bet(ctx: &ScFuncContext, f: &PlaceBetContext) { // amount of seconds. This will lock in the playing period, during which more bets can // be placed. Once the 'payWinners' function gets triggered by the ISCP it will gather all // bets up to that moment as the ones to consider for determining the winner. - ScFuncs::pay_winners(ctx).func - .delay(play_period) - .transfer_iotas(1) - .post(); + ScFuncs::pay_winners(ctx).func.delay(play_period).post(); } } } @@ -133,7 +128,7 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { // generator will use the next 8 bytes from the hash as its random Int64 number and once // it runs out of data it simply hashes the previous hash for a next pseudo-random sequence. // Here we determine the winning number for this round in the range of 1 thru MAX_NUMBER. - let winning_number: i64 = ctx.random(MAX_NUMBER - 1) + 1; + let winning_number: u16 = (ctx.random(MAX_NUMBER as u64 - 1) + 1) as u16; // Save the last winning number in state storage under 'lastWinningNumber' so that there // is (limited) time for people to call the 'getLastWinningNumber' View to verify the last @@ -146,18 +141,18 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { // Keep track of the total bet amount, the total win amount, and all the winners. // Note how we decided to keep the winners in a local vector instead of creating // yet another array in state storage or having to go through lockedBets again. - let mut total_bet_amount: i64 = 0_i64; - let mut total_win_amount: i64 = 0_i64; + let mut total_bet_amount: u64 = 0_u64; + let mut total_win_amount: u64 = 0_u64; let mut winners: Vec = Vec::new(); // Get the 'bets' array in state storage. let bets: ArrayOfMutableBet = f.state.bets(); // Determine the amount of bets in the 'bets' array. - let nr_bets: i32 = bets.length(); + let nr_of_bets: u32 = bets.length(); // Loop through all indexes of the 'bets' array. - for i in 0..nr_bets { + for i in 0..nr_of_bets { // Retrieve the bet stored at the next index let bet: Bet = bets.get_bet(i).value(); @@ -190,7 +185,7 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { // a small percentage that would go to the owner of the smart contract as hosting payment. // Keep track of the total payout so we can calculate the remainder after truncation. - let mut total_payout: i64 = 0_i64; + let mut total_payout: u64 = 0_u64; // Loop through all winners. let size: usize = winners.len(); @@ -199,7 +194,7 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { let bet: &Bet = &winners[i]; // Determine the proportional win amount (we could take our percentage here) - let payout: i64 = total_bet_amount * bet.amount / total_win_amount; + let payout: u64 = total_bet_amount * bet.amount / total_win_amount; // Anything to pay to the winner? if payout != 0 { @@ -217,7 +212,7 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { // of the winner. The transfer_to_address() method receives the address value and // the proxy to the new transfers map on the host, and will call the corresponding // host sandbox function with these values. - ctx.transfer_to_address(&bet.better.address(), transfers); + ctx.send(&bet.better.address(), &transfers); } // Announce who got sent what as event. @@ -226,13 +221,13 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { // This is where we transfer the remainder after payout to the creator of the smart contract. // The bank always wins :-P - let remainder: i64 = total_bet_amount - total_payout; + let remainder: u64 = total_bet_amount - total_payout; if remainder != 0 { // We have a remainder. First create a transfer for the remainder. let transfers: ScTransfers = ScTransfers::iotas(remainder); // Send the remainder to the contract creator. - ctx.transfer_to_address(&ctx.contract_creator().address(), transfers); + ctx.send(&ctx.contract_creator().address(), &transfers); } // Set round status to 0, send out event to notify that the round has ended @@ -258,7 +253,7 @@ pub fn func_force_reset(_ctx: &ScFuncContext, f: &ForceResetContext) { pub fn func_play_period(ctx: &ScFuncContext, f: &PlayPeriodContext) { // Since we are sure that the 'playPeriod' parameter actually exists we can // retrieve its actual value into an i32 value. - let play_period: i32 = f.params.play_period().value(); + let play_period: u32 = f.params.play_period().value(); // Require that the play period (in seconds) is not ridiculously low. // Otherwise, panic out with an error message. diff --git a/contracts/wasm/fairroulette/src/keys.rs b/contracts/wasm/fairroulette/src/keys.rs deleted file mode 100644 index e487249b10..0000000000 --- a/contracts/wasm/fairroulette/src/keys.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_NUMBER : usize = 0; -pub(crate) const IDX_PARAM_PLAY_PERIOD : usize = 1; - -pub(crate) const IDX_RESULT_LAST_WINNING_NUMBER : usize = 2; -pub(crate) const IDX_RESULT_ROUND_NUMBER : usize = 3; -pub(crate) const IDX_RESULT_ROUND_STARTED_AT : usize = 4; -pub(crate) const IDX_RESULT_ROUND_STATUS : usize = 5; - -pub(crate) const IDX_STATE_BETS : usize = 6; -pub(crate) const IDX_STATE_LAST_WINNING_NUMBER : usize = 7; -pub(crate) const IDX_STATE_PLAY_PERIOD : usize = 8; -pub(crate) const IDX_STATE_ROUND_NUMBER : usize = 9; -pub(crate) const IDX_STATE_ROUND_STARTED_AT : usize = 10; -pub(crate) const IDX_STATE_ROUND_STATUS : usize = 11; - -pub const KEY_MAP_LEN: usize = 12; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_NUMBER, - PARAM_PLAY_PERIOD, - RESULT_LAST_WINNING_NUMBER, - RESULT_ROUND_NUMBER, - RESULT_ROUND_STARTED_AT, - RESULT_ROUND_STATUS, - STATE_BETS, - STATE_LAST_WINNING_NUMBER, - STATE_PLAY_PERIOD, - STATE_ROUND_NUMBER, - STATE_ROUND_STARTED_AT, - STATE_ROUND_STATUS, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/fairroulette/src/lib.rs b/contracts/wasm/fairroulette/src/lib.rs index 753003c506..aa5788543a 100644 --- a/contracts/wasm/fairroulette/src/lib.rs +++ b/contracts/wasm/fairroulette/src/lib.rs @@ -10,43 +10,59 @@ use fairroulette::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; use crate::events::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::structs::*; mod consts; mod contract; mod events; -mod keys; mod params; mod results; mod state; mod structs; + mod fairroulette; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_FORCE_PAYOUT, + FUNC_FORCE_RESET, + FUNC_PAY_WINNERS, + FUNC_PLACE_BET, + FUNC_PLAY_PERIOD, + VIEW_LAST_WINNING_NUMBER, + VIEW_ROUND_NUMBER, + VIEW_ROUND_STARTED_AT, + VIEW_ROUND_STATUS, + ], + funcs: &[ + func_force_payout_thunk, + func_force_reset_thunk, + func_pay_winners_thunk, + func_place_bet_thunk, + func_play_period_thunk, + ], + views: &[ + view_last_winning_number_thunk, + view_round_number_thunk, + view_round_started_at_thunk, + view_round_status_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_FORCE_PAYOUT, func_force_payout_thunk); - exports.add_func(FUNC_FORCE_RESET, func_force_reset_thunk); - exports.add_func(FUNC_PAY_WINNERS, func_pay_winners_thunk); - exports.add_func(FUNC_PLACE_BET, func_place_bet_thunk); - exports.add_func(FUNC_PLAY_PERIOD, func_play_period_thunk); - exports.add_view(VIEW_LAST_WINNING_NUMBER, view_last_winning_number_thunk); - exports.add_view(VIEW_ROUND_NUMBER, view_round_number_thunk); - exports.add_view(VIEW_ROUND_STARTED_AT, view_round_started_at_thunk); - exports.add_view(VIEW_ROUND_STATUS, view_round_status_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct ForcePayoutContext { @@ -56,16 +72,14 @@ pub struct ForcePayoutContext { fn func_force_payout_thunk(ctx: &ScFuncContext) { ctx.log("fairroulette.funcForcePayout"); + let f = ForcePayoutContext { + events: FairRouletteEvents {}, + state: MutableFairRouletteState { proxy: state_proxy() }, + }; // only SC creator can restart the round forcefully ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = ForcePayoutContext { - events: FairRouletteEvents {}, - state: MutableFairRouletteState { - id: OBJ_ID_STATE, - }, - }; func_force_payout(ctx, &f); ctx.log("fairroulette.funcForcePayout ok"); } @@ -77,16 +91,14 @@ pub struct ForceResetContext { fn func_force_reset_thunk(ctx: &ScFuncContext) { ctx.log("fairroulette.funcForceReset"); + let f = ForceResetContext { + events: FairRouletteEvents {}, + state: MutableFairRouletteState { proxy: state_proxy() }, + }; // only SC creator can restart the round forcefully ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = ForceResetContext { - events: FairRouletteEvents {}, - state: MutableFairRouletteState { - id: OBJ_ID_STATE, - }, - }; func_force_reset(ctx, &f); ctx.log("fairroulette.funcForceReset ok"); } @@ -98,16 +110,14 @@ pub struct PayWinnersContext { fn func_pay_winners_thunk(ctx: &ScFuncContext) { ctx.log("fairroulette.funcPayWinners"); + let f = PayWinnersContext { + events: FairRouletteEvents {}, + state: MutableFairRouletteState { proxy: state_proxy() }, + }; // only SC itself can invoke this function ctx.require(ctx.caller() == ctx.account_id(), "no permission"); - let f = PayWinnersContext { - events: FairRouletteEvents {}, - state: MutableFairRouletteState { - id: OBJ_ID_STATE, - }, - }; func_pay_winners(ctx, &f); ctx.log("fairroulette.funcPayWinners ok"); } @@ -122,12 +132,8 @@ fn func_place_bet_thunk(ctx: &ScFuncContext) { ctx.log("fairroulette.funcPlaceBet"); let f = PlaceBetContext { events: FairRouletteEvents {}, - params: ImmutablePlaceBetParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairRouletteState { - id: OBJ_ID_STATE, - }, + params: ImmutablePlaceBetParams { proxy: params_proxy() }, + state: MutableFairRouletteState { proxy: state_proxy() }, }; ctx.require(f.params.number().exists(), "missing mandatory number"); func_place_bet(ctx, &f); @@ -142,19 +148,15 @@ pub struct PlayPeriodContext { fn func_play_period_thunk(ctx: &ScFuncContext) { ctx.log("fairroulette.funcPlayPeriod"); + let f = PlayPeriodContext { + events: FairRouletteEvents {}, + params: ImmutablePlayPeriodParams { proxy: params_proxy() }, + state: MutableFairRouletteState { proxy: state_proxy() }, + }; // only SC creator can update the play period ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = PlayPeriodContext { - events: FairRouletteEvents {}, - params: ImmutablePlayPeriodParams { - id: OBJ_ID_PARAMS, - }, - state: MutableFairRouletteState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.play_period().exists(), "missing mandatory playPeriod"); func_play_period(ctx, &f); ctx.log("fairroulette.funcPlayPeriod ok"); @@ -168,14 +170,11 @@ pub struct LastWinningNumberContext { fn view_last_winning_number_thunk(ctx: &ScViewContext) { ctx.log("fairroulette.viewLastWinningNumber"); let f = LastWinningNumberContext { - results: MutableLastWinningNumberResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableFairRouletteState { - id: OBJ_ID_STATE, - }, + results: MutableLastWinningNumberResults { proxy: results_proxy() }, + state: ImmutableFairRouletteState { proxy: state_proxy() }, }; view_last_winning_number(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("fairroulette.viewLastWinningNumber ok"); } @@ -187,14 +186,11 @@ pub struct RoundNumberContext { fn view_round_number_thunk(ctx: &ScViewContext) { ctx.log("fairroulette.viewRoundNumber"); let f = RoundNumberContext { - results: MutableRoundNumberResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableFairRouletteState { - id: OBJ_ID_STATE, - }, + results: MutableRoundNumberResults { proxy: results_proxy() }, + state: ImmutableFairRouletteState { proxy: state_proxy() }, }; view_round_number(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("fairroulette.viewRoundNumber ok"); } @@ -206,14 +202,11 @@ pub struct RoundStartedAtContext { fn view_round_started_at_thunk(ctx: &ScViewContext) { ctx.log("fairroulette.viewRoundStartedAt"); let f = RoundStartedAtContext { - results: MutableRoundStartedAtResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableFairRouletteState { - id: OBJ_ID_STATE, - }, + results: MutableRoundStartedAtResults { proxy: results_proxy() }, + state: ImmutableFairRouletteState { proxy: state_proxy() }, }; view_round_started_at(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("fairroulette.viewRoundStartedAt ok"); } @@ -225,13 +218,10 @@ pub struct RoundStatusContext { fn view_round_status_thunk(ctx: &ScViewContext) { ctx.log("fairroulette.viewRoundStatus"); let f = RoundStatusContext { - results: MutableRoundStatusResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableFairRouletteState { - id: OBJ_ID_STATE, - }, + results: MutableRoundStatusResults { proxy: results_proxy() }, + state: ImmutableFairRouletteState { proxy: state_proxy() }, }; view_round_status(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("fairroulette.viewRoundStatus ok"); } diff --git a/contracts/wasm/fairroulette/src/params.rs b/contracts/wasm/fairroulette/src/params.rs index cfb876a057..2bbddfd291 100644 --- a/contracts/wasm/fairroulette/src/params.rs +++ b/contracts/wasm/fairroulette/src/params.rs @@ -9,52 +9,48 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutablePlaceBetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutablePlaceBetParams { - pub fn number(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_NUMBER.get_key_id()) + pub fn number(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(PARAM_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutablePlaceBetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutablePlaceBetParams { - pub fn number(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_NUMBER.get_key_id()) + pub fn number(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(PARAM_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutablePlayPeriodParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutablePlayPeriodParams { - pub fn play_period(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_PLAY_PERIOD.get_key_id()) + pub fn play_period(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_PLAY_PERIOD)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutablePlayPeriodParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutablePlayPeriodParams { - pub fn play_period(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_PLAY_PERIOD.get_key_id()) + pub fn play_period(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_PLAY_PERIOD)) } } diff --git a/contracts/wasm/fairroulette/src/results.rs b/contracts/wasm/fairroulette/src/results.rs index 3786d0f879..116797efb3 100644 --- a/contracts/wasm/fairroulette/src/results.rs +++ b/contracts/wasm/fairroulette/src/results.rs @@ -9,96 +9,92 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableLastWinningNumberResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableLastWinningNumberResults { - pub fn last_winning_number(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_LAST_WINNING_NUMBER.get_key_id()) + pub fn last_winning_number(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(RESULT_LAST_WINNING_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableLastWinningNumberResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableLastWinningNumberResults { - pub fn last_winning_number(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_LAST_WINNING_NUMBER.get_key_id()) + pub fn last_winning_number(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(RESULT_LAST_WINNING_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRoundNumberResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRoundNumberResults { - pub fn round_number(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_ROUND_NUMBER.get_key_id()) + pub fn round_number(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_ROUND_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRoundNumberResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRoundNumberResults { - pub fn round_number(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_ROUND_NUMBER.get_key_id()) + pub fn round_number(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_ROUND_NUMBER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRoundStartedAtResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRoundStartedAtResults { - pub fn round_started_at(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_ROUND_STARTED_AT.get_key_id()) + pub fn round_started_at(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_ROUND_STARTED_AT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRoundStartedAtResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRoundStartedAtResults { - pub fn round_started_at(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_ROUND_STARTED_AT.get_key_id()) + pub fn round_started_at(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_ROUND_STARTED_AT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRoundStatusResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRoundStatusResults { - pub fn round_status(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, RESULT_ROUND_STATUS.get_key_id()) + pub fn round_status(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(RESULT_ROUND_STATUS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRoundStatusResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRoundStatusResults { - pub fn round_status(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, RESULT_ROUND_STATUS.get_key_id()) + pub fn round_status(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(RESULT_ROUND_STATUS)) } } diff --git a/contracts/wasm/fairroulette/src/state.rs b/contracts/wasm/fairroulette/src/state.rs index 1eab6abc50..011c023ab1 100644 --- a/contracts/wasm/fairroulette/src/state.rs +++ b/contracts/wasm/fairroulette/src/state.rs @@ -9,110 +9,111 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableBet { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableBet { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_bet(&self, index: i32) -> ImmutableBet { - ImmutableBet { obj_id: self.obj_id, key_id: Key32(index) } + + pub fn get_bet(&self, index: u32) -> ImmutableBet { + ImmutableBet { proxy: self.proxy.index(index) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFairRouletteState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFairRouletteState { pub fn bets(&self) -> ArrayOfImmutableBet { - let arr_id = get_object_id(self.id, STATE_BETS.get_key_id(), TYPE_ARRAY | TYPE_BYTES); - ArrayOfImmutableBet { obj_id: arr_id } + ArrayOfImmutableBet { proxy: self.proxy.root(STATE_BETS) } } - pub fn last_winning_number(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_LAST_WINNING_NUMBER.get_key_id()) + pub fn last_winning_number(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(STATE_LAST_WINNING_NUMBER)) } - pub fn play_period(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, STATE_PLAY_PERIOD.get_key_id()) + pub fn play_period(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(STATE_PLAY_PERIOD)) } - pub fn round_number(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_ROUND_NUMBER.get_key_id()) + pub fn round_number(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(STATE_ROUND_NUMBER)) } - pub fn round_started_at(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, STATE_ROUND_STARTED_AT.get_key_id()) + pub fn round_started_at(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(STATE_ROUND_STARTED_AT)) } - pub fn round_status(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, STATE_ROUND_STATUS.get_key_id()) + pub fn round_status(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(STATE_ROUND_STATUS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableBet { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableBet { - pub fn clear(&self) { - clear(self.obj_id); + + pub fn append_bet(&self) -> MutableBet { + MutableBet { proxy: self.proxy.append() } + } + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_bet(&self, index: i32) -> MutableBet { - MutableBet { obj_id: self.obj_id, key_id: Key32(index) } + + pub fn get_bet(&self, index: u32) -> MutableBet { + MutableBet { proxy: self.proxy.index(index) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFairRouletteState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFairRouletteState { pub fn as_immutable(&self) -> ImmutableFairRouletteState { - ImmutableFairRouletteState { id: self.id } + ImmutableFairRouletteState { proxy: self.proxy.root("") } } pub fn bets(&self) -> ArrayOfMutableBet { - let arr_id = get_object_id(self.id, STATE_BETS.get_key_id(), TYPE_ARRAY | TYPE_BYTES); - ArrayOfMutableBet { obj_id: arr_id } + ArrayOfMutableBet { proxy: self.proxy.root(STATE_BETS) } } - pub fn last_winning_number(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_LAST_WINNING_NUMBER.get_key_id()) + pub fn last_winning_number(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(STATE_LAST_WINNING_NUMBER)) } - pub fn play_period(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, STATE_PLAY_PERIOD.get_key_id()) + pub fn play_period(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(STATE_PLAY_PERIOD)) } - pub fn round_number(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_ROUND_NUMBER.get_key_id()) + pub fn round_number(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(STATE_ROUND_NUMBER)) } - pub fn round_started_at(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, STATE_ROUND_STARTED_AT.get_key_id()) + pub fn round_started_at(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(STATE_ROUND_STARTED_AT)) } - pub fn round_status(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, STATE_ROUND_STATUS.get_key_id()) + pub fn round_status(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(STATE_ROUND_STATUS)) } } diff --git a/contracts/wasm/fairroulette/src/structs.rs b/contracts/wasm/fairroulette/src/structs.rs index 4bd7f082bc..1d6aa76ba5 100644 --- a/contracts/wasm/fairroulette/src/structs.rs +++ b/contracts/wasm/fairroulette/src/structs.rs @@ -9,70 +9,67 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; #[derive(Clone)] pub struct Bet { - pub amount : i64, + pub amount : u64, pub better : ScAgentID, - pub number : i64, + pub number : u16, } impl Bet { pub fn from_bytes(bytes: &[u8]) -> Bet { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); Bet { - amount : decode.int64(), - better : decode.agent_id(), - number : decode.int64(), + amount : uint64_decode(&mut dec), + better : agent_id_decode(&mut dec), + number : uint16_decode(&mut dec), } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.int64(self.amount); - encode.agent_id(&self.better); - encode.int64(self.number); - return encode.data(); + let mut enc = WasmEncoder::new(); + uint64_encode(&mut enc, self.amount); + agent_id_encode(&mut enc, &self.better); + uint16_encode(&mut enc, self.number); + enc.buf() } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBet { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl ImmutableBet { pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn value(&self) -> Bet { - Bet::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Bet::from_bytes(&self.proxy.get()) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBet { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl MutableBet { pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn set_value(&self, value: &Bet) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } pub fn value(&self) -> Bet { - Bet::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Bet::from_bytes(&self.proxy.get()) } } diff --git a/contracts/wasm/fairroulette/test/fairroulette_bg.wasm b/contracts/wasm/fairroulette/test/fairroulette_bg.wasm index d7ee598864..5eab9c7510 100644 Binary files a/contracts/wasm/fairroulette/test/fairroulette_bg.wasm and b/contracts/wasm/fairroulette/test/fairroulette_bg.wasm differ diff --git a/contracts/wasm/fairroulette/test/fairroulette_test.go b/contracts/wasm/fairroulette/test/fairroulette_test.go index 09b45e53d5..4d10887e26 100644 --- a/contracts/wasm/fairroulette/test/fairroulette_test.go +++ b/contracts/wasm/fairroulette/test/fairroulette_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/iotaledger/wasp/contracts/wasm/fairroulette/go/fairroulette" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -28,9 +28,16 @@ func TestBets(t *testing.T) { better[i] = ctx.NewSoloAgent() placeBet := fairroulette.ScFuncs.PlaceBet(ctx.Sign(better[i])) placeBet.Params.Number().SetValue(3) - placeBet.Func.TransferIotas(25).Post() + placeBet.Func.TransferIotas(1234).Post() require.NoError(t, ctx.Err) } + // TODO this should be a simple 1 request to wait for, but sometimes + // the payout will have already been triggered (bug), so instead of + // waiting for that single payout request we will (erroneously) wait + // for the inbuf and outbuf counts to equalize + info := ctx.Chain.MempoolInfo() + + // wait for finalize_auction ctx.AdvanceClockBy(1201 * time.Second) - require.True(t, ctx.WaitForPendingRequests(1)) + require.True(t, ctx.WaitForPendingRequests(-info.InBufCounter)) } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/consts.ts b/contracts/wasm/fairroulette/ts/fairroulette/consts.ts index d930b586af..6ec19d299e 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/consts.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "fairroulette"; export const ScDescription = ""; -export const HScName = new wasmlib.ScHname(0xdf79d138); +export const HScName = new wasmtypes.ScHname(0xdf79d138); export const ParamNumber = "number"; export const ParamPlayPeriod = "playPeriod"; @@ -36,12 +36,12 @@ export const ViewRoundNumber = "roundNumber"; export const ViewRoundStartedAt = "roundStartedAt"; export const ViewRoundStatus = "roundStatus"; -export const HFuncForcePayout = new wasmlib.ScHname(0x555a4c4f); -export const HFuncForceReset = new wasmlib.ScHname(0xa331951e); -export const HFuncPayWinners = new wasmlib.ScHname(0xfb2b0144); -export const HFuncPlaceBet = new wasmlib.ScHname(0xdfba7d1b); -export const HFuncPlayPeriod = new wasmlib.ScHname(0xcb94b293); -export const HViewLastWinningNumber = new wasmlib.ScHname(0x2f5f09fe); -export const HViewRoundNumber = new wasmlib.ScHname(0x0dcfe520); -export const HViewRoundStartedAt = new wasmlib.ScHname(0x725de8b4); -export const HViewRoundStatus = new wasmlib.ScHname(0x145053b5); +export const HFuncForcePayout = new wasmtypes.ScHname(0x555a4c4f); +export const HFuncForceReset = new wasmtypes.ScHname(0xa331951e); +export const HFuncPayWinners = new wasmtypes.ScHname(0xfb2b0144); +export const HFuncPlaceBet = new wasmtypes.ScHname(0xdfba7d1b); +export const HFuncPlayPeriod = new wasmtypes.ScHname(0xcb94b293); +export const HViewLastWinningNumber = new wasmtypes.ScHname(0x2f5f09fe); +export const HViewRoundNumber = new wasmtypes.ScHname(0x0dcfe520); +export const HViewRoundStartedAt = new wasmtypes.ScHname(0x725de8b4); +export const HViewRoundStatus = new wasmtypes.ScHname(0x145053b5); diff --git a/contracts/wasm/fairroulette/ts/fairroulette/contract.ts b/contracts/wasm/fairroulette/ts/fairroulette/contract.ts index 7b9b6e4bc2..0688799437 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/contract.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/contract.ts @@ -14,7 +14,7 @@ export class ForcePayoutCall { export class ForcePayoutContext { events: sc.FairRouletteEvents = new sc.FairRouletteEvents(); - state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(); + state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(wasmlib.ScState.proxy()); } export class ForceResetCall { @@ -23,7 +23,7 @@ export class ForceResetCall { export class ForceResetContext { events: sc.FairRouletteEvents = new sc.FairRouletteEvents(); - state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(); + state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(wasmlib.ScState.proxy()); } export class PayWinnersCall { @@ -32,117 +32,117 @@ export class PayWinnersCall { export class PayWinnersContext { events: sc.FairRouletteEvents = new sc.FairRouletteEvents(); - state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(); + state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(wasmlib.ScState.proxy()); } export class PlaceBetCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncPlaceBet); - params: sc.MutablePlaceBetParams = new sc.MutablePlaceBetParams(); + params: sc.MutablePlaceBetParams = new sc.MutablePlaceBetParams(wasmlib.ScView.nilProxy); } export class PlaceBetContext { events: sc.FairRouletteEvents = new sc.FairRouletteEvents(); - params: sc.ImmutablePlaceBetParams = new sc.ImmutablePlaceBetParams(); - state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(); + params: sc.ImmutablePlaceBetParams = new sc.ImmutablePlaceBetParams(wasmlib.paramsProxy()); + state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(wasmlib.ScState.proxy()); } export class PlayPeriodCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncPlayPeriod); - params: sc.MutablePlayPeriodParams = new sc.MutablePlayPeriodParams(); + params: sc.MutablePlayPeriodParams = new sc.MutablePlayPeriodParams(wasmlib.ScView.nilProxy); } export class PlayPeriodContext { events: sc.FairRouletteEvents = new sc.FairRouletteEvents(); - params: sc.ImmutablePlayPeriodParams = new sc.ImmutablePlayPeriodParams(); - state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(); + params: sc.ImmutablePlayPeriodParams = new sc.ImmutablePlayPeriodParams(wasmlib.paramsProxy()); + state: sc.MutableFairRouletteState = new sc.MutableFairRouletteState(wasmlib.ScState.proxy()); } export class LastWinningNumberCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewLastWinningNumber); - results: sc.ImmutableLastWinningNumberResults = new sc.ImmutableLastWinningNumberResults(); + results: sc.ImmutableLastWinningNumberResults = new sc.ImmutableLastWinningNumberResults(wasmlib.ScView.nilProxy); } export class LastWinningNumberContext { - results: sc.MutableLastWinningNumberResults = new sc.MutableLastWinningNumberResults(); - state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(); + results: sc.MutableLastWinningNumberResults = new sc.MutableLastWinningNumberResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(wasmlib.ScState.proxy()); } export class RoundNumberCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewRoundNumber); - results: sc.ImmutableRoundNumberResults = new sc.ImmutableRoundNumberResults(); + results: sc.ImmutableRoundNumberResults = new sc.ImmutableRoundNumberResults(wasmlib.ScView.nilProxy); } export class RoundNumberContext { - results: sc.MutableRoundNumberResults = new sc.MutableRoundNumberResults(); - state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(); + results: sc.MutableRoundNumberResults = new sc.MutableRoundNumberResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(wasmlib.ScState.proxy()); } export class RoundStartedAtCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewRoundStartedAt); - results: sc.ImmutableRoundStartedAtResults = new sc.ImmutableRoundStartedAtResults(); + results: sc.ImmutableRoundStartedAtResults = new sc.ImmutableRoundStartedAtResults(wasmlib.ScView.nilProxy); } export class RoundStartedAtContext { - results: sc.MutableRoundStartedAtResults = new sc.MutableRoundStartedAtResults(); - state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(); + results: sc.MutableRoundStartedAtResults = new sc.MutableRoundStartedAtResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(wasmlib.ScState.proxy()); } export class RoundStatusCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewRoundStatus); - results: sc.ImmutableRoundStatusResults = new sc.ImmutableRoundStatusResults(); + results: sc.ImmutableRoundStatusResults = new sc.ImmutableRoundStatusResults(wasmlib.ScView.nilProxy); } export class RoundStatusContext { - results: sc.MutableRoundStatusResults = new sc.MutableRoundStatusResults(); - state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(); + results: sc.MutableRoundStatusResults = new sc.MutableRoundStatusResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableFairRouletteState = new sc.ImmutableFairRouletteState(wasmlib.ScState.proxy()); } export class ScFuncs { - static forcePayout(ctx: wasmlib.ScFuncCallContext): ForcePayoutCall { - return new ForcePayoutCall(); - } - - static forceReset(ctx: wasmlib.ScFuncCallContext): ForceResetCall { - return new ForceResetCall(); - } - - static payWinners(ctx: wasmlib.ScFuncCallContext): PayWinnersCall { - return new PayWinnersCall(); - } - - static placeBet(ctx: wasmlib.ScFuncCallContext): PlaceBetCall { - let f = new PlaceBetCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static playPeriod(ctx: wasmlib.ScFuncCallContext): PlayPeriodCall { - let f = new PlayPeriodCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static lastWinningNumber(ctx: wasmlib.ScViewCallContext): LastWinningNumberCall { - let f = new LastWinningNumberCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static roundNumber(ctx: wasmlib.ScViewCallContext): RoundNumberCall { - let f = new RoundNumberCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static roundStartedAt(ctx: wasmlib.ScViewCallContext): RoundStartedAtCall { - let f = new RoundStartedAtCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static roundStatus(ctx: wasmlib.ScViewCallContext): RoundStatusCall { - let f = new RoundStatusCall(); - f.func.setPtrs(null, f.results); - return f; - } + static forcePayout(_ctx: wasmlib.ScFuncCallContext): ForcePayoutCall { + return new ForcePayoutCall(); + } + + static forceReset(_ctx: wasmlib.ScFuncCallContext): ForceResetCall { + return new ForceResetCall(); + } + + static payWinners(_ctx: wasmlib.ScFuncCallContext): PayWinnersCall { + return new PayWinnersCall(); + } + + static placeBet(_ctx: wasmlib.ScFuncCallContext): PlaceBetCall { + const f = new PlaceBetCall(); + f.params = new sc.MutablePlaceBetParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static playPeriod(_ctx: wasmlib.ScFuncCallContext): PlayPeriodCall { + const f = new PlayPeriodCall(); + f.params = new sc.MutablePlayPeriodParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static lastWinningNumber(_ctx: wasmlib.ScViewCallContext): LastWinningNumberCall { + const f = new LastWinningNumberCall(); + f.results = new sc.ImmutableLastWinningNumberResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static roundNumber(_ctx: wasmlib.ScViewCallContext): RoundNumberCall { + const f = new RoundNumberCall(); + f.results = new sc.ImmutableRoundNumberResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static roundStartedAt(_ctx: wasmlib.ScViewCallContext): RoundStartedAtCall { + const f = new RoundStartedAtCall(); + f.results = new sc.ImmutableRoundStartedAtResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static roundStatus(_ctx: wasmlib.ScViewCallContext): RoundStatusCall { + const f = new RoundStatusCall(); + f.results = new sc.ImmutableRoundStatusResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/events.ts b/contracts/wasm/fairroulette/ts/fairroulette/events.ts index bef3fbce6f..64a405c213 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/events.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/events.ts @@ -6,43 +6,44 @@ // Change the json schema instead import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class FairRouletteEvents { - bet(address: wasmlib.ScAddress, amount: i64, number: i64): void { - new wasmlib.EventEncoder("fairroulette.bet"). - address(address). - int64(amount). - int64(number). - emit(); + bet(address: wasmtypes.ScAddress, amount: u64, number: u16): void { + const evt = new wasmlib.EventEncoder("fairroulette.bet"); + evt.encode(wasmtypes.addressToString(address)); + evt.encode(wasmtypes.uint64ToString(amount)); + evt.encode(wasmtypes.uint16ToString(number)); + evt.emit(); } - payout(address: wasmlib.ScAddress, amount: i64): void { - new wasmlib.EventEncoder("fairroulette.payout"). - address(address). - int64(amount). - emit(); + payout(address: wasmtypes.ScAddress, amount: u64): void { + const evt = new wasmlib.EventEncoder("fairroulette.payout"); + evt.encode(wasmtypes.addressToString(address)); + evt.encode(wasmtypes.uint64ToString(amount)); + evt.emit(); } - round(number: i64): void { - new wasmlib.EventEncoder("fairroulette.round"). - int64(number). - emit(); + round(number: u32): void { + const evt = new wasmlib.EventEncoder("fairroulette.round"); + evt.encode(wasmtypes.uint32ToString(number)); + evt.emit(); } start(): void { - new wasmlib.EventEncoder("fairroulette.start"). - emit(); + const evt = new wasmlib.EventEncoder("fairroulette.start"); + evt.emit(); } stop(): void { - new wasmlib.EventEncoder("fairroulette.stop"). - emit(); + const evt = new wasmlib.EventEncoder("fairroulette.stop"); + evt.emit(); } - winner(number: i64): void { - new wasmlib.EventEncoder("fairroulette.winner"). - int64(number). - emit(); + winner(number: u16): void { + const evt = new wasmlib.EventEncoder("fairroulette.winner"); + evt.encode(wasmtypes.uint16ToString(number)); + evt.emit(); } } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts b/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts index 6319c393de..a7161c4409 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts @@ -8,21 +8,22 @@ // through a minimal implementation and not to come up with a complete real-world solution. import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; // Define some default configuration parameters. // The maximum number one can bet on. The range of numbers starts at 1. -const MAX_NUMBER: i64 = 8; +const MAX_NUMBER: u16 = 8; // The default playing period of one betting round in seconds. -const DEFAULT_PLAY_PERIOD: i32 = 60; +const DEFAULT_PLAY_PERIOD: u32 = 60; // Enable this if you deploy the contract to an actual node. It will pay out the prize after a certain timeout. const ENABLE_SELF_POST: boolean = true; // The number to divide nano seconds to seconds. -const NANO_TIME_DIVIDER: i64 = 1000000000; +const NANO_TIME_DIVIDER: u64 = 1000000000; // 'placeBet' is used by betters to place a bet on a number from 1 to MAX_NUMBER. The first // incoming bet triggers a betting round of configurable duration. After the playing period @@ -36,7 +37,8 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): // Get the array of current bets from state storage. let bets: sc.ArrayOfMutableBet = f.state.bets(); - for (let i = 0; i < bets.length(); i++) { + const nrOfBets = bets.length(); + for (let i: u32 = 0; i < nrOfBets; i++) { let bet: sc.Bet = bets.getBet(i).value(); if (bet.better.address() == ctx.caller().address()) { @@ -46,7 +48,7 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): // Since we are sure that the 'number' parameter actually exists we can // retrieve its actual value into an i64. - let number: i64 = f.params.number().value(); + let number: u16 = f.params.number().value(); // Require that the number is a valid number to bet on, otherwise panic out. ctx.require(number >= 1 && number <= MAX_NUMBER, "invalid number"); @@ -57,7 +59,7 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): let incoming: wasmlib.ScBalances = ctx.incoming(); // Retrieve the amount of plain iota tokens that are part of the incoming balance. - let amount: i64 = incoming.balance(wasmlib.ScColor.IOTA); + let amount: u64 = incoming.balance(wasmtypes.IOTA); // Require that there are actually some plain iotas there ctx.require(amount > 0, "empty bet"); @@ -70,20 +72,17 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): bet.amount = amount; bet.number = number; - // Determine what the next bet number is by retrieving the length of the bets array. - let betNr: i32 = bets.length(); - // Append the bet data to the bets array. The bet array will automatically take care // of serializing the bet struct into a bytes representation. - bets.getBet(betNr).setValue(bet); + bets.appendBet().setValue(bet); f.events.bet(bet.better.address(), bet.amount, bet.number); // Was this the first bet of this round? - if (betNr == 0) { + if (nrOfBets == 0) { // Yes it was, query the state for the length of the playing period in seconds by // retrieving the playPeriod value from state storage - let playPeriod: i32 = f.state.playPeriod().value(); + let playPeriod: u32 = f.state.playPeriod().value(); // if the play period is less than 10 seconds we override it with the default duration. // Note that this will also happen when the play period was not set yet because in that @@ -97,7 +96,7 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): f.state.roundStatus().setValue(1); // timestamp is nanotime, divide by NANO_TIME_DIVIDER to get seconds => common unix timestamp - let timestamp = (ctx.timestamp() / NANO_TIME_DIVIDER) as i32; + let timestamp = (ctx.timestamp() / NANO_TIME_DIVIDER) as u32; f.state.roundStartedAt().setValue(timestamp); f.events.start(); @@ -112,10 +111,7 @@ export function funcPlaceBet(ctx: wasmlib.ScFuncContext, f: sc.PlaceBetContext): // amount of seconds. This will lock in the playing period, during which more bets can // be placed. Once the 'payWinners' function gets triggered by the ISCP it will gather all // bets up to that moment as the ones to consider for determining the winner. - sc.ScFuncs.payWinners(ctx).func - .delay(playPeriod) - .transferIotas(1) - .post(); + sc.ScFuncs.payWinners(ctx).func.delay(playPeriod).post(); } } } @@ -129,7 +125,7 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte // generator will use the next 8 bytes from the hash as its random Int64 number and once // it runs out of data it simply hashes the previous hash for a next pseudo-random sequence. // Here we determine the winning number for this round in the range of 1 thru MAX_NUMBER. - let winningNumber: i64 = ctx.random(MAX_NUMBER - 1) + 1; + let winningNumber: u16 = (ctx.random(MAX_NUMBER - 1) + 1) as u16; // Save the last winning number in state storage under 'lastWinningNumber' so that there // is (limited) time for people to call the 'getLastWinningNumber' View to verify the last @@ -142,18 +138,18 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte // Keep track of the total bet amount, the total win amount, and all the winners. // Note how we decided to keep the winners in a local vector instead of creating // yet another array in state storage or having to go through lockedBets again. - let totalBetAmount: i64 = 0; - let totalWinAmount: i64 = 0; + let totalBetAmount: u64 = 0; + let totalWinAmount: u64 = 0; let winners: sc.Bet[] = []; // Get the 'bets' array in state storage. let bets: sc.ArrayOfMutableBet = f.state.bets(); // Determine the amount of bets in the 'bets' array. - let nrBets: i32 = bets.length(); + let nrOfBets: u32 = bets.length(); // Loop through all indexes of the 'bets' array. - for (let i = 0; i < nrBets; i++) { + for (let i: u32 = 0; i < nrOfBets; i++) { // Retrieve the bet stored at the next index let bet: sc.Bet = bets.getBet(i).value(); @@ -186,7 +182,7 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte // a small percentage that would go to the owner of the smart contract as hosting payment. // Keep track of the total payout so we can calculate the remainder after truncation. - let totalPayout: i64 = 0; + let totalPayout: u64 = 0; // Loop through all winners. let size = winners.length; @@ -195,7 +191,7 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte let bet: sc.Bet = winners[i]; // Determine the proportional win amount (we could take our percentage here) - let payout: i64 = totalBetAmount * bet.amount / totalWinAmount; + let payout: u64 = totalBetAmount * bet.amount / totalWinAmount; // Anything to pay to the winner? if (payout != 0) { @@ -213,7 +209,7 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte // of the winner. The transferToAddress() method receives the address value and // the proxy to the new transfers map on the host, and will call the corresponding // host sandbox function with these values. - ctx.transferToAddress(bet.better.address(), transfers); + ctx.send(bet.better.address(), transfers); } // Announce who got sent what as event. @@ -222,13 +218,13 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte // This is where we transfer the remainder after payout to the creator of the smart contract. // The bank always wins :-P - let remainder: i64 = totalBetAmount - totalPayout; + let remainder: u64 = totalBetAmount - totalPayout; if (remainder != 0) { // We have a remainder. First create a transfer for the remainder. let transfers: wasmlib.ScTransfers = wasmlib.ScTransfers.iotas(remainder); // Send the remainder to the contract creator. - ctx.transferToAddress(ctx.contractCreator().address(), transfers); + ctx.send(ctx.contractCreator().address(), transfers); } // Set round status to 0, send out event to notify that the round has ended @@ -254,7 +250,7 @@ export function funcForceReset(ctx: wasmlib.ScFuncContext, f: sc.ForceResetConte export function funcPlayPeriod(ctx: wasmlib.ScFuncContext, f: sc.PlayPeriodContext): void { // Since we are sure that the 'playPeriod' parameter actually exists we can // retrieve its actual value into an i32 value. - let playPeriod: i32 = f.params.playPeriod().value(); + let playPeriod: u32 = f.params.playPeriod().value(); // Require that the play period (in seconds) is not ridiculously low. // Otherwise, panic out with an error message. @@ -275,7 +271,7 @@ export function viewLastWinningNumber(ctx: wasmlib.ScViewContext, f: sc.LastWinn } export function viewRoundNumber(ctx: wasmlib.ScViewContext, f: sc.RoundNumberContext): void { - // Get the 'roundNumber' int64 value from state storage. + // Get the 'roundNumber' uint32 value from state storage. let roundNumber = f.state.roundNumber().value(); // Set the 'roundNumber' in results to the value from state storage. @@ -283,7 +279,7 @@ export function viewRoundNumber(ctx: wasmlib.ScViewContext, f: sc.RoundNumberCon } export function viewRoundStatus(ctx: wasmlib.ScViewContext, f: sc.RoundStatusContext): void { - // Get the 'roundStatus' int16 value from state storage. + // Get the 'roundStatus' uint16 value from state storage. let roundStatus = f.state.roundStatus().value(); // Set the 'roundStatus' in results to the value from state storage. @@ -291,7 +287,7 @@ export function viewRoundStatus(ctx: wasmlib.ScViewContext, f: sc.RoundStatusCon } export function viewRoundStartedAt(ctx: wasmlib.ScViewContext, f: sc.RoundStartedAtContext): void { - // Get the 'roundStartedAt' int32 value from state storage. + // Get the 'roundStartedAt' uint32 value from state storage. let roundStartedAt = f.state.roundStartedAt().value(); // Set the 'roundStartedAt' in results to the value from state storage. diff --git a/contracts/wasm/fairroulette/ts/fairroulette/index.ts b/contracts/wasm/fairroulette/ts/fairroulette/index.ts index a14f6af431..31dc75a2bc 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/index.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/index.ts @@ -10,7 +10,6 @@ export * from "./fairroulette"; export * from "./consts"; export * from "./contract"; export * from "./events"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/fairroulette/ts/fairroulette/keys.ts b/contracts/wasm/fairroulette/ts/fairroulette/keys.ts deleted file mode 100644 index 46895b797f..0000000000 --- a/contracts/wasm/fairroulette/ts/fairroulette/keys.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamNumber = 0; -export const IdxParamPlayPeriod = 1; - -export const IdxResultLastWinningNumber = 2; -export const IdxResultRoundNumber = 3; -export const IdxResultRoundStartedAt = 4; -export const IdxResultRoundStatus = 5; - -export const IdxStateBets = 6; -export const IdxStateLastWinningNumber = 7; -export const IdxStatePlayPeriod = 8; -export const IdxStateRoundNumber = 9; -export const IdxStateRoundStartedAt = 10; -export const IdxStateRoundStatus = 11; - -export let keyMap: string[] = [ - sc.ParamNumber, - sc.ParamPlayPeriod, - sc.ResultLastWinningNumber, - sc.ResultRoundNumber, - sc.ResultRoundStartedAt, - sc.ResultRoundStatus, - sc.StateBets, - sc.StateLastWinningNumber, - sc.StatePlayPeriod, - sc.StateRoundNumber, - sc.StateRoundStartedAt, - sc.StateRoundStatus, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/fairroulette/ts/fairroulette/lib.ts b/contracts/wasm/fairroulette/ts/fairroulette/lib.ts index e19135eaba..8f485e94e5 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/lib.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/lib.ts @@ -8,59 +8,70 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncForcePayout, + sc.FuncForceReset, + sc.FuncPayWinners, + sc.FuncPlaceBet, + sc.FuncPlayPeriod, + sc.ViewLastWinningNumber, + sc.ViewRoundNumber, + sc.ViewRoundStartedAt, + sc.ViewRoundStatus, + ], + funcs: [ + funcForcePayoutThunk, + funcForceResetThunk, + funcPayWinnersThunk, + funcPlaceBetThunk, + funcPlayPeriodThunk, + ], + views: [ + viewLastWinningNumberThunk, + viewRoundNumberThunk, + viewRoundStartedAtThunk, + viewRoundStatusThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncForcePayout, funcForcePayoutThunk); - exports.addFunc(sc.FuncForceReset, funcForceResetThunk); - exports.addFunc(sc.FuncPayWinners, funcPayWinnersThunk); - exports.addFunc(sc.FuncPlaceBet, funcPlaceBetThunk); - exports.addFunc(sc.FuncPlayPeriod, funcPlayPeriodThunk); - exports.addView(sc.ViewLastWinningNumber, viewLastWinningNumberThunk); - exports.addView(sc.ViewRoundNumber, viewRoundNumberThunk); - exports.addView(sc.ViewRoundStartedAt, viewRoundStartedAtThunk); - exports.addView(sc.ViewRoundStatus, viewRoundStatusThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcForcePayoutThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairroulette.funcForcePayout"); + let f = new sc.ForcePayoutContext(); // only SC creator can restart the round forcefully ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.ForcePayoutContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcForcePayout(ctx, f); ctx.log("fairroulette.funcForcePayout ok"); } function funcForceResetThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairroulette.funcForceReset"); + let f = new sc.ForceResetContext(); // only SC creator can restart the round forcefully ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.ForceResetContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcForceReset(ctx, f); ctx.log("fairroulette.funcForceReset ok"); } function funcPayWinnersThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairroulette.funcPayWinners"); + let f = new sc.PayWinnersContext(); // only SC itself can invoke this function ctx.require(ctx.caller().equals(ctx.accountID()), "no permission"); - let f = new sc.PayWinnersContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcPayWinners(ctx, f); ctx.log("fairroulette.funcPayWinners ok"); } @@ -68,8 +79,6 @@ function funcPayWinnersThunk(ctx: wasmlib.ScFuncContext): void { function funcPlaceBetThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairroulette.funcPlaceBet"); let f = new sc.PlaceBetContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.number().exists(), "missing mandatory number"); sc.funcPlaceBet(ctx, f); ctx.log("fairroulette.funcPlaceBet ok"); @@ -77,13 +86,11 @@ function funcPlaceBetThunk(ctx: wasmlib.ScFuncContext): void { function funcPlayPeriodThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("fairroulette.funcPlayPeriod"); + let f = new sc.PlayPeriodContext(); // only SC creator can update the play period ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.PlayPeriodContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.playPeriod().exists(), "missing mandatory playPeriod"); sc.funcPlayPeriod(ctx, f); ctx.log("fairroulette.funcPlayPeriod ok"); @@ -92,35 +99,39 @@ function funcPlayPeriodThunk(ctx: wasmlib.ScFuncContext): void { function viewLastWinningNumberThunk(ctx: wasmlib.ScViewContext): void { ctx.log("fairroulette.viewLastWinningNumber"); let f = new sc.LastWinningNumberContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableLastWinningNumberResults(results.asProxy()); sc.viewLastWinningNumber(ctx, f); + ctx.results(results); ctx.log("fairroulette.viewLastWinningNumber ok"); } function viewRoundNumberThunk(ctx: wasmlib.ScViewContext): void { ctx.log("fairroulette.viewRoundNumber"); let f = new sc.RoundNumberContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableRoundNumberResults(results.asProxy()); sc.viewRoundNumber(ctx, f); + ctx.results(results); ctx.log("fairroulette.viewRoundNumber ok"); } function viewRoundStartedAtThunk(ctx: wasmlib.ScViewContext): void { ctx.log("fairroulette.viewRoundStartedAt"); let f = new sc.RoundStartedAtContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableRoundStartedAtResults(results.asProxy()); sc.viewRoundStartedAt(ctx, f); + ctx.results(results); ctx.log("fairroulette.viewRoundStartedAt ok"); } function viewRoundStatusThunk(ctx: wasmlib.ScViewContext): void { ctx.log("fairroulette.viewRoundStatus"); let f = new sc.RoundStatusContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableRoundStatusResults(results.asProxy()); sc.viewRoundStatus(ctx, f); + ctx.results(results); ctx.log("fairroulette.viewRoundStatus ok"); } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/params.ts b/contracts/wasm/fairroulette/ts/fairroulette/params.ts index ca1af44b4a..86a1735007 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/params.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/params.ts @@ -5,29 +5,29 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutablePlaceBetParams extends wasmlib.ScMapID { - number(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNumber)); +export class ImmutablePlaceBetParams extends wasmtypes.ScProxy { + number(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.ParamNumber)); } } -export class MutablePlaceBetParams extends wasmlib.ScMapID { - number(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNumber)); +export class MutablePlaceBetParams extends wasmtypes.ScProxy { + number(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.ParamNumber)); } } -export class ImmutablePlayPeriodParams extends wasmlib.ScMapID { - playPeriod(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamPlayPeriod)); +export class ImmutablePlayPeriodParams extends wasmtypes.ScProxy { + playPeriod(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamPlayPeriod)); } } -export class MutablePlayPeriodParams extends wasmlib.ScMapID { - playPeriod(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamPlayPeriod)); +export class MutablePlayPeriodParams extends wasmtypes.ScProxy { + playPeriod(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamPlayPeriod)); } } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/results.ts b/contracts/wasm/fairroulette/ts/fairroulette/results.ts index 719f1acc2c..90b2aa1f97 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/results.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/results.ts @@ -5,53 +5,53 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableLastWinningNumberResults extends wasmlib.ScMapID { - lastWinningNumber(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultLastWinningNumber)); +export class ImmutableLastWinningNumberResults extends wasmtypes.ScProxy { + lastWinningNumber(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.ResultLastWinningNumber)); } } -export class MutableLastWinningNumberResults extends wasmlib.ScMapID { - lastWinningNumber(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultLastWinningNumber)); +export class MutableLastWinningNumberResults extends wasmtypes.ScProxy { + lastWinningNumber(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.ResultLastWinningNumber)); } } -export class ImmutableRoundNumberResults extends wasmlib.ScMapID { - roundNumber(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundNumber)); +export class ImmutableRoundNumberResults extends wasmtypes.ScProxy { + roundNumber(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultRoundNumber)); } } -export class MutableRoundNumberResults extends wasmlib.ScMapID { - roundNumber(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundNumber)); +export class MutableRoundNumberResults extends wasmtypes.ScProxy { + roundNumber(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultRoundNumber)); } } -export class ImmutableRoundStartedAtResults extends wasmlib.ScMapID { - roundStartedAt(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundStartedAt)); +export class ImmutableRoundStartedAtResults extends wasmtypes.ScProxy { + roundStartedAt(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultRoundStartedAt)); } } -export class MutableRoundStartedAtResults extends wasmlib.ScMapID { - roundStartedAt(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundStartedAt)); +export class MutableRoundStartedAtResults extends wasmtypes.ScProxy { + roundStartedAt(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultRoundStartedAt)); } } -export class ImmutableRoundStatusResults extends wasmlib.ScMapID { - roundStatus(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundStatus)); +export class ImmutableRoundStatusResults extends wasmtypes.ScProxy { + roundStatus(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.ResultRoundStatus)); } } -export class MutableRoundStatusResults extends wasmlib.ScMapID { - roundStatus(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultRoundStatus)); +export class MutableRoundStatusResults extends wasmtypes.ScProxy { + roundStatus(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.ResultRoundStatus)); } } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/state.ts b/contracts/wasm/fairroulette/ts/fairroulette/state.ts index f3eb652c35..eb5bc54b01 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/state.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/state.ts @@ -5,101 +5,91 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableBet { - objID: i32; +export class ArrayOfImmutableBet extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getBet(index: i32): sc.ImmutableBet { - return new sc.ImmutableBet(this.objID, new wasmlib.Key32(index)); + getBet(index: u32): sc.ImmutableBet { + return new sc.ImmutableBet(this.proxy.index(index)); } } -export class ImmutableFairRouletteState extends wasmlib.ScMapID { - bets(): sc.ArrayOfImmutableBet { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBets), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBet(arrID); +export class ImmutableFairRouletteState extends wasmtypes.ScProxy { + bets(): sc.ArrayOfImmutableBet { + return new sc.ArrayOfImmutableBet(this.proxy.root(sc.StateBets)); } - lastWinningNumber(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateLastWinningNumber)); + lastWinningNumber(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.StateLastWinningNumber)); } - playPeriod(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.StatePlayPeriod)); + playPeriod(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.StatePlayPeriod)); } - roundNumber(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateRoundNumber)); + roundNumber(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.StateRoundNumber)); } - roundStartedAt(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.StateRoundStartedAt)); + roundStartedAt(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.StateRoundStartedAt)); } - roundStatus(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.StateRoundStatus)); + roundStatus(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.StateRoundStatus)); } } -export class ArrayOfMutableBet { - objID: i32; +export class ArrayOfMutableBet extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendBet(): sc.MutableBet { + return new sc.MutableBet(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getBet(index: i32): sc.MutableBet { - return new sc.MutableBet(this.objID, new wasmlib.Key32(index)); + getBet(index: u32): sc.MutableBet { + return new sc.MutableBet(this.proxy.index(index)); } } -export class MutableFairRouletteState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableFairRouletteState { - const imm = new sc.ImmutableFairRouletteState(); - imm.mapID = this.mapID; - return imm; +export class MutableFairRouletteState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableFairRouletteState { + return new sc.ImmutableFairRouletteState(this.proxy); } - bets(): sc.ArrayOfMutableBet { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateBets), wasmlib.TYPE_ARRAY|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBet(arrID); + bets(): sc.ArrayOfMutableBet { + return new sc.ArrayOfMutableBet(this.proxy.root(sc.StateBets)); } - lastWinningNumber(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateLastWinningNumber)); + lastWinningNumber(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.StateLastWinningNumber)); } - playPeriod(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.StatePlayPeriod)); + playPeriod(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.StatePlayPeriod)); } - roundNumber(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateRoundNumber)); + roundNumber(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.StateRoundNumber)); } - roundStartedAt(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.StateRoundStartedAt)); + roundStartedAt(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.StateRoundStartedAt)); } - roundStatus(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.StateRoundStatus)); + roundStatus(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.StateRoundStatus)); } } diff --git a/contracts/wasm/fairroulette/ts/fairroulette/structs.ts b/contracts/wasm/fairroulette/ts/fairroulette/structs.ts index a0c749f141..3f5fe8f796 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/structs.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/structs.ts @@ -5,72 +5,58 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Bet { - amount : i64 = 0; - better : wasmlib.ScAgentID = new wasmlib.ScAgentID(); - number : i64 = 0; - - static fromBytes(bytes: u8[]): Bet { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Bet(); - data.amount = decode.int64(); - data.better = decode.agentID(); - data.number = decode.int64(); - decode.close(); - return data; - } - - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - int64(this.amount). - agentID(this.better). - int64(this.number). - data(); - } + amount : u64 = 0; + better : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); + number : u16 = 0; + + static fromBytes(buf: u8[]): Bet { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new Bet(); + data.amount = wasmtypes.uint64Decode(dec); + data.better = wasmtypes.agentIDDecode(dec); + data.number = wasmtypes.uint16Decode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint64Encode(enc, this.amount); + wasmtypes.agentIDEncode(enc, this.better); + wasmtypes.uint16Encode(enc, this.number); + return enc.buf(); + } } -export class ImmutableBet { - objID: i32; - keyID: wasmlib.Key32; +export class ImmutableBet extends wasmtypes.ScProxy { - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } + exists(): bool { + return this.proxy.exists(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Bet { - return Bet.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Bet { + return Bet.fromBytes(this.proxy.get()); + } } -export class MutableBet { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class MutableBet extends wasmtypes.ScProxy { - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } - setValue(value: Bet): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: Bet): void { + this.proxy.set(value.bytes()); + } - value(): Bet { - return Bet.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Bet { + return Bet.fromBytes(this.proxy.get()); + } } diff --git a/contracts/wasm/helloworld/Cargo.toml b/contracts/wasm/helloworld/Cargo.toml index 5969d1d7b0..01a82d9fac 100644 --- a/contracts/wasm/helloworld/Cargo.toml +++ b/contracts/wasm/helloworld/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/helloworld/go/helloworld/consts.go b/contracts/wasm/helloworld/go/helloworld/consts.go index bb14625014..890a33e759 100644 --- a/contracts/wasm/helloworld/go/helloworld/consts.go +++ b/contracts/wasm/helloworld/go/helloworld/consts.go @@ -7,12 +7,12 @@ package helloworld -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "helloworld" ScDescription = "The ubiquitous hello world demo" - HScName = wasmlib.ScHname(0x0683223c) + HScName = wasmtypes.ScHname(0x0683223c) ) const ( @@ -25,6 +25,6 @@ const ( ) const ( - HFuncHelloWorld = wasmlib.ScHname(0x9d042e65) - HViewGetHelloWorld = wasmlib.ScHname(0x210439ce) + HFuncHelloWorld = wasmtypes.ScHname(0x9d042e65) + HViewGetHelloWorld = wasmtypes.ScHname(0x210439ce) ) diff --git a/contracts/wasm/helloworld/go/helloworld/contract.go b/contracts/wasm/helloworld/go/helloworld/contract.go index 3423976513..172d63cfbb 100644 --- a/contracts/wasm/helloworld/go/helloworld/contract.go +++ b/contracts/wasm/helloworld/go/helloworld/contract.go @@ -7,7 +7,7 @@ package helloworld -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type HelloWorldCall struct { Func *wasmlib.ScFunc @@ -28,6 +28,6 @@ func (sc Funcs) HelloWorld(ctx wasmlib.ScFuncCallContext) *HelloWorldCall { func (sc Funcs) GetHelloWorld(ctx wasmlib.ScViewCallContext) *GetHelloWorldCall { f := &GetHelloWorldCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetHelloWorld)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/helloworld/go/helloworld/helloworld.go b/contracts/wasm/helloworld/go/helloworld/helloworld.go index 8556be3915..33fba4ec98 100644 --- a/contracts/wasm/helloworld/go/helloworld/helloworld.go +++ b/contracts/wasm/helloworld/go/helloworld/helloworld.go @@ -4,7 +4,7 @@ package helloworld import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" ) //nolint:unparam diff --git a/contracts/wasm/helloworld/go/helloworld/keys.go b/contracts/wasm/helloworld/go/helloworld/keys.go deleted file mode 100644 index 149a75fad1..0000000000 --- a/contracts/wasm/helloworld/go/helloworld/keys.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package helloworld - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxResultHelloWorld = 0 -) - -const keyMapLen = 1 - -var keyMap = [keyMapLen]wasmlib.Key{ - ResultHelloWorld, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/helloworld/go/helloworld/lib.go b/contracts/wasm/helloworld/go/helloworld/lib.go index 9292b24c0a..15c47c513d 100644 --- a/contracts/wasm/helloworld/go/helloworld/lib.go +++ b/contracts/wasm/helloworld/go/helloworld/lib.go @@ -7,16 +7,28 @@ package helloworld -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncHelloWorld, funcHelloWorldThunk) - exports.AddView(ViewGetHelloWorld, viewGetHelloWorldThunk) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncHelloWorld, + ViewGetHelloWorld, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcHelloWorldThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetHelloWorldThunk, + }, +} - for i, key := range keyMap { - idxMap[i] = key.KeyID() +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type HelloWorldContext struct { @@ -27,7 +39,7 @@ func funcHelloWorldThunk(ctx wasmlib.ScFuncContext) { ctx.Log("helloworld.funcHelloWorld") f := &HelloWorldContext{ State: MutableHelloWorldState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcHelloWorld(ctx, f) @@ -41,14 +53,16 @@ type GetHelloWorldContext struct { func viewGetHelloWorldThunk(ctx wasmlib.ScViewContext) { ctx.Log("helloworld.viewGetHelloWorld") + results := wasmlib.NewScDict() f := &GetHelloWorldContext{ Results: MutableGetHelloWorldResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableHelloWorldState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetHelloWorld(ctx, f) + ctx.Results(results) ctx.Log("helloworld.viewGetHelloWorld ok") } diff --git a/contracts/wasm/helloworld/go/helloworld/results.go b/contracts/wasm/helloworld/go/helloworld/results.go index 94e77f318a..1477888daf 100644 --- a/contracts/wasm/helloworld/go/helloworld/results.go +++ b/contracts/wasm/helloworld/go/helloworld/results.go @@ -7,20 +7,20 @@ package helloworld -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableGetHelloWorldResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetHelloWorldResults) HelloWorld() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultHelloWorld)) +func (s ImmutableGetHelloWorldResults) HelloWorld() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultHelloWorld)) } type MutableGetHelloWorldResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetHelloWorldResults) HelloWorld() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultHelloWorld)) +func (s MutableGetHelloWorldResults) HelloWorld() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultHelloWorld)) } diff --git a/contracts/wasm/helloworld/go/helloworld/state.go b/contracts/wasm/helloworld/go/helloworld/state.go index 0b1fb82fcb..cf95ee8ef1 100644 --- a/contracts/wasm/helloworld/go/helloworld/state.go +++ b/contracts/wasm/helloworld/go/helloworld/state.go @@ -7,12 +7,14 @@ package helloworld +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + type ImmutableHelloWorldState struct { - id int32 + proxy wasmtypes.Proxy } type MutableHelloWorldState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableHelloWorldState) AsImmutable() ImmutableHelloWorldState { diff --git a/contracts/wasm/helloworld/go/main.go b/contracts/wasm/helloworld/go/main.go index 856ecebec4..9dbf82070b 100644 --- a/contracts/wasm/helloworld/go/main.go +++ b/contracts/wasm/helloworld/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/helloworld/go/helloworld" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + helloworld.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - helloworld.OnLoad() + helloworld.OnLoad(-1) } diff --git a/contracts/wasm/helloworld/src/contract.rs b/contracts/wasm/helloworld/src/contract.rs index ca5b365fd9..97c2b5c1f1 100644 --- a/contracts/wasm/helloworld/src/contract.rs +++ b/contracts/wasm/helloworld/src/contract.rs @@ -7,12 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::results::*; +use crate::*; pub struct HelloWorldCall { pub func: ScFunc, @@ -27,18 +23,18 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn hello_world(_ctx: & dyn ScFuncCallContext) -> HelloWorldCall { + pub fn hello_world(_ctx: &dyn ScFuncCallContext) -> HelloWorldCall { HelloWorldCall { func: ScFunc::new(HSC_NAME, HFUNC_HELLO_WORLD), } } - pub fn get_hello_world(_ctx: & dyn ScViewCallContext) -> GetHelloWorldCall { + pub fn get_hello_world(_ctx: &dyn ScViewCallContext) -> GetHelloWorldCall { let mut f = GetHelloWorldCall { func: ScView::new(HSC_NAME, HVIEW_GET_HELLO_WORLD), - results: ImmutableGetHelloWorldResults { id: 0 }, + results: ImmutableGetHelloWorldResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/helloworld/src/keys.rs b/contracts/wasm/helloworld/src/keys.rs deleted file mode 100644 index 468a469a19..0000000000 --- a/contracts/wasm/helloworld/src/keys.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - - -pub(crate) const IDX_RESULT_HELLO_WORLD : usize = 0; - - -pub const KEY_MAP_LEN: usize = 1; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - RESULT_HELLO_WORLD, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/helloworld/src/lib.rs b/contracts/wasm/helloworld/src/lib.rs index 80bb927a85..0de572d3d6 100644 --- a/contracts/wasm/helloworld/src/lib.rs +++ b/contracts/wasm/helloworld/src/lib.rs @@ -10,31 +10,39 @@ use helloworld::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::results::*; use crate::state::*; mod consts; mod contract; -mod keys; mod results; mod state; + mod helloworld; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_HELLO_WORLD, + VIEW_GET_HELLO_WORLD, + ], + funcs: &[ + func_hello_world_thunk, + ], + views: &[ + view_get_hello_world_thunk, + ], +}; + #[no_mangle] -fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_HELLO_WORLD, func_hello_world_thunk); - exports.add_view(VIEW_GET_HELLO_WORLD, view_get_hello_world_thunk); +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } +#[no_mangle] +fn on_load() { + ScExports::export(&EXPORT_MAP); } pub struct HelloWorldContext { @@ -44,9 +52,7 @@ pub struct HelloWorldContext { fn func_hello_world_thunk(ctx: &ScFuncContext) { ctx.log("helloworld.funcHelloWorld"); let f = HelloWorldContext { - state: MutableHelloWorldState { - id: OBJ_ID_STATE, - }, + state: MutableHelloWorldState { proxy: state_proxy() }, }; func_hello_world(ctx, &f); ctx.log("helloworld.funcHelloWorld ok"); @@ -60,13 +66,10 @@ pub struct GetHelloWorldContext { fn view_get_hello_world_thunk(ctx: &ScViewContext) { ctx.log("helloworld.viewGetHelloWorld"); let f = GetHelloWorldContext { - results: MutableGetHelloWorldResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableHelloWorldState { - id: OBJ_ID_STATE, - }, + results: MutableGetHelloWorldResults { proxy: results_proxy() }, + state: ImmutableHelloWorldState { proxy: state_proxy() }, }; view_get_hello_world(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("helloworld.viewGetHelloWorld ok"); } diff --git a/contracts/wasm/helloworld/src/results.rs b/contracts/wasm/helloworld/src/results.rs index 49fc1b6000..798cb05acd 100644 --- a/contracts/wasm/helloworld/src/results.rs +++ b/contracts/wasm/helloworld/src/results.rs @@ -9,29 +9,26 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetHelloWorldResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetHelloWorldResults { pub fn hello_world(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_HELLO_WORLD.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_HELLO_WORLD)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetHelloWorldResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetHelloWorldResults { pub fn hello_world(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_HELLO_WORLD.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_HELLO_WORLD)) } } diff --git a/contracts/wasm/helloworld/src/state.rs b/contracts/wasm/helloworld/src/state.rs index 435ad75b1c..bbde370a5e 100644 --- a/contracts/wasm/helloworld/src/state.rs +++ b/contracts/wasm/helloworld/src/state.rs @@ -9,17 +9,15 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableHelloWorldState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableHelloWorldState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } diff --git a/contracts/wasm/helloworld/test/helloworld_bg.wasm b/contracts/wasm/helloworld/test/helloworld_bg.wasm index 3a50d255a5..51039ae6ea 100644 Binary files a/contracts/wasm/helloworld/test/helloworld_bg.wasm and b/contracts/wasm/helloworld/test/helloworld_bg.wasm differ diff --git a/contracts/wasm/helloworld/test/helloworld_test.go b/contracts/wasm/helloworld/test/helloworld_test.go index c18c9ed42c..a027332cfb 100644 --- a/contracts/wasm/helloworld/test/helloworld_test.go +++ b/contracts/wasm/helloworld/test/helloworld_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/iotaledger/wasp/contracts/wasm/helloworld/go/helloworld" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -24,7 +24,7 @@ func TestFuncHelloWorld(t *testing.T) { ctx := setupTest(t) helloWorld := helloworld.ScFuncs.HelloWorld(ctx) - helloWorld.Func.TransferIotas(1).Post() + helloWorld.Func.Post() require.NoError(t, ctx.Err) } diff --git a/contracts/wasm/helloworld/ts/helloworld/consts.ts b/contracts/wasm/helloworld/ts/helloworld/consts.ts index d52c7a618a..802b2638fc 100644 --- a/contracts/wasm/helloworld/ts/helloworld/consts.ts +++ b/contracts/wasm/helloworld/ts/helloworld/consts.ts @@ -5,16 +5,16 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "helloworld"; export const ScDescription = "The ubiquitous hello world demo"; -export const HScName = new wasmlib.ScHname(0x0683223c); +export const HScName = new wasmtypes.ScHname(0x0683223c); export const ResultHelloWorld = "helloWorld"; export const FuncHelloWorld = "helloWorld"; export const ViewGetHelloWorld = "getHelloWorld"; -export const HFuncHelloWorld = new wasmlib.ScHname(0x9d042e65); -export const HViewGetHelloWorld = new wasmlib.ScHname(0x210439ce); +export const HFuncHelloWorld = new wasmtypes.ScHname(0x9d042e65); +export const HViewGetHelloWorld = new wasmtypes.ScHname(0x210439ce); diff --git a/contracts/wasm/helloworld/ts/helloworld/contract.ts b/contracts/wasm/helloworld/ts/helloworld/contract.ts index 3740f30ca3..a0961c65ef 100644 --- a/contracts/wasm/helloworld/ts/helloworld/contract.ts +++ b/contracts/wasm/helloworld/ts/helloworld/contract.ts @@ -13,27 +13,27 @@ export class HelloWorldCall { } export class HelloWorldContext { - state: sc.MutableHelloWorldState = new sc.MutableHelloWorldState(); + state: sc.MutableHelloWorldState = new sc.MutableHelloWorldState(wasmlib.ScState.proxy()); } export class GetHelloWorldCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetHelloWorld); - results: sc.ImmutableGetHelloWorldResults = new sc.ImmutableGetHelloWorldResults(); + results: sc.ImmutableGetHelloWorldResults = new sc.ImmutableGetHelloWorldResults(wasmlib.ScView.nilProxy); } export class GetHelloWorldContext { - results: sc.MutableGetHelloWorldResults = new sc.MutableGetHelloWorldResults(); - state: sc.ImmutableHelloWorldState = new sc.ImmutableHelloWorldState(); + results: sc.MutableGetHelloWorldResults = new sc.MutableGetHelloWorldResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableHelloWorldState = new sc.ImmutableHelloWorldState(wasmlib.ScState.proxy()); } export class ScFuncs { - static helloWorld(ctx: wasmlib.ScFuncCallContext): HelloWorldCall { - return new HelloWorldCall(); - } - - static getHelloWorld(ctx: wasmlib.ScViewCallContext): GetHelloWorldCall { - let f = new GetHelloWorldCall(); - f.func.setPtrs(null, f.results); - return f; - } + static helloWorld(_ctx: wasmlib.ScFuncCallContext): HelloWorldCall { + return new HelloWorldCall(); + } + + static getHelloWorld(_ctx: wasmlib.ScViewCallContext): GetHelloWorldCall { + const f = new GetHelloWorldCall(); + f.results = new sc.ImmutableGetHelloWorldResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/helloworld/ts/helloworld/index.ts b/contracts/wasm/helloworld/ts/helloworld/index.ts index d88f5510f4..95162fe0c6 100644 --- a/contracts/wasm/helloworld/ts/helloworld/index.ts +++ b/contracts/wasm/helloworld/ts/helloworld/index.ts @@ -9,7 +9,6 @@ export * from "./helloworld"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./results"; export * from "./state"; diff --git a/contracts/wasm/helloworld/ts/helloworld/lib.ts b/contracts/wasm/helloworld/ts/helloworld/lib.ts index c70f64e037..5a24c8eabe 100644 --- a/contracts/wasm/helloworld/ts/helloworld/lib.ts +++ b/contracts/wasm/helloworld/ts/helloworld/lib.ts @@ -8,24 +8,30 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncHelloWorld, + sc.ViewGetHelloWorld, + ], + funcs: [ + funcHelloWorldThunk, + ], + views: [ + viewGetHelloWorldThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncHelloWorld, funcHelloWorldThunk); - exports.addView(sc.ViewGetHelloWorld, viewGetHelloWorldThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcHelloWorldThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("helloworld.funcHelloWorld"); let f = new sc.HelloWorldContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcHelloWorld(ctx, f); ctx.log("helloworld.funcHelloWorld ok"); } @@ -33,8 +39,9 @@ function funcHelloWorldThunk(ctx: wasmlib.ScFuncContext): void { function viewGetHelloWorldThunk(ctx: wasmlib.ScViewContext): void { ctx.log("helloworld.viewGetHelloWorld"); let f = new sc.GetHelloWorldContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetHelloWorldResults(results.asProxy()); sc.viewGetHelloWorld(ctx, f); + ctx.results(results); ctx.log("helloworld.viewGetHelloWorld ok"); } diff --git a/contracts/wasm/helloworld/ts/helloworld/results.ts b/contracts/wasm/helloworld/ts/helloworld/results.ts index b9337efedf..2ba0103e29 100644 --- a/contracts/wasm/helloworld/ts/helloworld/results.ts +++ b/contracts/wasm/helloworld/ts/helloworld/results.ts @@ -5,17 +5,17 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableGetHelloWorldResults extends wasmlib.ScMapID { - helloWorld(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultHelloWorld)); +export class ImmutableGetHelloWorldResults extends wasmtypes.ScProxy { + helloWorld(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultHelloWorld)); } } -export class MutableGetHelloWorldResults extends wasmlib.ScMapID { - helloWorld(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultHelloWorld)); +export class MutableGetHelloWorldResults extends wasmtypes.ScProxy { + helloWorld(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultHelloWorld)); } } diff --git a/contracts/wasm/helloworld/ts/helloworld/state.ts b/contracts/wasm/helloworld/ts/helloworld/state.ts index b1476bca64..c84ab241f7 100644 --- a/contracts/wasm/helloworld/ts/helloworld/state.ts +++ b/contracts/wasm/helloworld/ts/helloworld/state.ts @@ -5,16 +5,14 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableHelloWorldState extends wasmlib.ScMapID { +export class ImmutableHelloWorldState extends wasmtypes.ScProxy { } -export class MutableHelloWorldState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableHelloWorldState { - const imm = new sc.ImmutableHelloWorldState(); - imm.mapID = this.mapID; - return imm; +export class MutableHelloWorldState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableHelloWorldState { + return new sc.ImmutableHelloWorldState(this.proxy); } } diff --git a/contracts/wasm/inccounter/Cargo.toml b/contracts/wasm/inccounter/Cargo.toml index 85cf6dbe20..b8a519e68e 100644 --- a/contracts/wasm/inccounter/Cargo.toml +++ b/contracts/wasm/inccounter/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/inccounter/go/inccounter/consts.go b/contracts/wasm/inccounter/go/inccounter/consts.go index 86b738973e..cfd2fabd96 100644 --- a/contracts/wasm/inccounter/go/inccounter/consts.go +++ b/contracts/wasm/inccounter/go/inccounter/consts.go @@ -7,23 +7,31 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "inccounter" ScDescription = "" - HScName = wasmlib.ScHname(0xaf2438e9) + HScName = wasmtypes.ScHname(0xaf2438e9) ) const ( ParamCounter = "counter" ParamDelay = "delay" ParamDummy = "dummy" + ParamNi64 = "ni64" + ParamNu64 = "nu64" ParamNumRepeats = "numRepeats" ) const ( + ResultBuf = "buf" ResultCounter = "counter" + ResultNi64 = "ni64" + ResultNu64 = "nu64" + ResultStr = "str" + ResultXi64 = "xi64" + ResultXu64 = "xu64" ) const ( @@ -43,24 +51,30 @@ const ( FuncLocalStateSandboxCall = "localStateSandboxCall" FuncPostIncrement = "postIncrement" FuncRepeatMany = "repeatMany" - FuncTestLeb128 = "testLeb128" + FuncTestVliCodec = "testVliCodec" + FuncTestVluCodec = "testVluCodec" FuncWhenMustIncrement = "whenMustIncrement" ViewGetCounter = "getCounter" + ViewGetVli = "getVli" + ViewGetVlu = "getVlu" ) const ( - HFuncCallIncrement = wasmlib.ScHname(0xeb5dcacd) - HFuncCallIncrementRecurse5x = wasmlib.ScHname(0x8749fbff) - HFuncEndlessLoop = wasmlib.ScHname(0x365f0929) - HFuncIncrement = wasmlib.ScHname(0xd351bd12) - HFuncIncrementWithDelay = wasmlib.ScHname(0xa235bba7) - HFuncInit = wasmlib.ScHname(0x1f44d644) - HFuncLocalStateInternalCall = wasmlib.ScHname(0xecfc5d33) - HFuncLocalStatePost = wasmlib.ScHname(0x3fd54d13) - HFuncLocalStateSandboxCall = wasmlib.ScHname(0x7bd22c53) - HFuncPostIncrement = wasmlib.ScHname(0x81c772f5) - HFuncRepeatMany = wasmlib.ScHname(0x4ff450d3) - HFuncTestLeb128 = wasmlib.ScHname(0xd8364cb9) - HFuncWhenMustIncrement = wasmlib.ScHname(0xb4c3e7a6) - HViewGetCounter = wasmlib.ScHname(0xb423e607) + HFuncCallIncrement = wasmtypes.ScHname(0xeb5dcacd) + HFuncCallIncrementRecurse5x = wasmtypes.ScHname(0x8749fbff) + HFuncEndlessLoop = wasmtypes.ScHname(0x365f0929) + HFuncIncrement = wasmtypes.ScHname(0xd351bd12) + HFuncIncrementWithDelay = wasmtypes.ScHname(0xa235bba7) + HFuncInit = wasmtypes.ScHname(0x1f44d644) + HFuncLocalStateInternalCall = wasmtypes.ScHname(0xecfc5d33) + HFuncLocalStatePost = wasmtypes.ScHname(0x3fd54d13) + HFuncLocalStateSandboxCall = wasmtypes.ScHname(0x7bd22c53) + HFuncPostIncrement = wasmtypes.ScHname(0x81c772f5) + HFuncRepeatMany = wasmtypes.ScHname(0x4ff450d3) + HFuncTestVliCodec = wasmtypes.ScHname(0xd5356012) + HFuncTestVluCodec = wasmtypes.ScHname(0x9f7f63e6) + HFuncWhenMustIncrement = wasmtypes.ScHname(0xb4c3e7a6) + HViewGetCounter = wasmtypes.ScHname(0xb423e607) + HViewGetVli = wasmtypes.ScHname(0x0ee16f89) + HViewGetVlu = wasmtypes.ScHname(0x54d624e6) ) diff --git a/contracts/wasm/inccounter/go/inccounter/contract.go b/contracts/wasm/inccounter/go/inccounter/contract.go index ce3aa3e852..91e558d74f 100644 --- a/contracts/wasm/inccounter/go/inccounter/contract.go +++ b/contracts/wasm/inccounter/go/inccounter/contract.go @@ -7,7 +7,7 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type CallIncrementCall struct { Func *wasmlib.ScFunc @@ -56,7 +56,11 @@ type RepeatManyCall struct { Params MutableRepeatManyParams } -type TestLeb128Call struct { +type TestVliCodecCall struct { + Func *wasmlib.ScFunc +} + +type TestVluCodecCall struct { Func *wasmlib.ScFunc } @@ -70,6 +74,18 @@ type GetCounterCall struct { Results ImmutableGetCounterResults } +type GetVliCall struct { + Func *wasmlib.ScView + Params MutableGetVliParams + Results ImmutableGetVliResults +} + +type GetVluCall struct { + Func *wasmlib.ScView + Params MutableGetVluParams + Results ImmutableGetVluResults +} + type Funcs struct{} var ScFuncs Funcs @@ -92,13 +108,13 @@ func (sc Funcs) Increment(ctx wasmlib.ScFuncCallContext) *IncrementCall { func (sc Funcs) IncrementWithDelay(ctx wasmlib.ScFuncCallContext) *IncrementWithDelayCall { f := &IncrementWithDelayCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncIncrementWithDelay)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Init(ctx wasmlib.ScFuncCallContext) *InitCall { - f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit, keyMap[:], idxMap[:])} - f.Func.SetPtrs(&f.Params.id, nil) + f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -120,22 +136,40 @@ func (sc Funcs) PostIncrement(ctx wasmlib.ScFuncCallContext) *PostIncrementCall func (sc Funcs) RepeatMany(ctx wasmlib.ScFuncCallContext) *RepeatManyCall { f := &RepeatManyCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncRepeatMany)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } -func (sc Funcs) TestLeb128(ctx wasmlib.ScFuncCallContext) *TestLeb128Call { - return &TestLeb128Call{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTestLeb128)} +func (sc Funcs) TestVliCodec(ctx wasmlib.ScFuncCallContext) *TestVliCodecCall { + return &TestVliCodecCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTestVliCodec)} +} + +func (sc Funcs) TestVluCodec(ctx wasmlib.ScFuncCallContext) *TestVluCodecCall { + return &TestVluCodecCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTestVluCodec)} } func (sc Funcs) WhenMustIncrement(ctx wasmlib.ScFuncCallContext) *WhenMustIncrementCall { f := &WhenMustIncrementCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncWhenMustIncrement)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GetCounter(ctx wasmlib.ScViewCallContext) *GetCounterCall { f := &GetCounterCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetCounter)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) + return f +} + +func (sc Funcs) GetVli(ctx wasmlib.ScViewCallContext) *GetVliCall { + f := &GetVliCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetVli)} + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) + return f +} + +func (sc Funcs) GetVlu(ctx wasmlib.ScViewCallContext) *GetVluCall { + f := &GetVluCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetVlu)} + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/inccounter/go/inccounter/inccounter.go b/contracts/wasm/inccounter/go/inccounter/inccounter.go index 23e1dd665e..9a1ee47c00 100644 --- a/contracts/wasm/inccounter/go/inccounter/inccounter.go +++ b/contracts/wasm/inccounter/go/inccounter/inccounter.go @@ -4,9 +4,14 @@ package inccounter import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "strconv" + + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) +const hex = "0123456789abcdef" + var LocalStateMustIncrement = false func funcInit(ctx wasmlib.ScFuncContext, f *InitContext) { @@ -47,6 +52,12 @@ func funcIncrement(ctx wasmlib.ScFuncContext, f *IncrementContext) { counter.SetValue(counter.Value() + 1) } +func funcIncrementWithDelay(ctx wasmlib.ScFuncContext, f *IncrementWithDelayContext) { + delay := f.Params.Delay().Value() + inc := ScFuncs.CallIncrement(ctx) + inc.Func.Delay(delay).Post() +} + func funcLocalStateInternalCall(ctx wasmlib.ScFuncContext, f *LocalStateInternalCallContext) { LocalStateMustIncrement = false whenMustIncrementState(ctx, f.State) @@ -82,7 +93,7 @@ func funcPostIncrement(ctx wasmlib.ScFuncContext, f *PostIncrementContext) { value := counter.Value() counter.SetValue(value + 1) if value == 0 { - ScFuncs.PostIncrement(ctx).Func.TransferIotas(1).Post() + ScFuncs.PostIncrement(ctx).Func.Post() } } @@ -99,16 +110,55 @@ func funcRepeatMany(ctx wasmlib.ScFuncContext, f *RepeatManyContext) { } } stateRepeats.SetValue(repeats - 1) - ScFuncs.RepeatMany(ctx).Func.TransferIotas(1).Post() + ScFuncs.RepeatMany(ctx).Func.Post() +} + +//nolint:unparam +func funcTestVliCodec(ctx wasmlib.ScFuncContext, f *TestVliCodecContext) { + vliSave(ctx, "v-129", -129) + vliSave(ctx, "v-128", -128) + vliSave(ctx, "v-127", -127) + vliSave(ctx, "v-126", -126) + vliSave(ctx, "v-65", -65) + vliSave(ctx, "v-64", -64) + vliSave(ctx, "v-63", -63) + vliSave(ctx, "v-62", -62) + vliSave(ctx, "v-2", -2) + vliSave(ctx, "v-1", -1) + vliSave(ctx, "v 0", 0) + vliSave(ctx, "v+1", 1) + vliSave(ctx, "v+2", 2) + vliSave(ctx, "v+62", 62) + vliSave(ctx, "v+63", 63) + vliSave(ctx, "v+64", 64) + vliSave(ctx, "v+65", 65) + vliSave(ctx, "v+126", 126) + vliSave(ctx, "v+127", 127) + vliSave(ctx, "v+128", 128) + vliSave(ctx, "v+129", 129) +} + +//nolint:unparam +func funcTestVluCodec(ctx wasmlib.ScFuncContext, f *TestVluCodecContext) { + vluSave(ctx, "v 0", 0) + vluSave(ctx, "v+1", 1) + vluSave(ctx, "v+2", 2) + vluSave(ctx, "v+62", 62) + vluSave(ctx, "v+63", 63) + vluSave(ctx, "v+64", 64) + vluSave(ctx, "v+65", 65) + vluSave(ctx, "v+126", 126) + vluSave(ctx, "v+127", 127) + vluSave(ctx, "v+128", 128) + vluSave(ctx, "v+129", 129) } func funcWhenMustIncrement(ctx wasmlib.ScFuncContext, f *WhenMustIncrementContext) { whenMustIncrementState(ctx, f.State) } -// note that get_counter mirrors the state of the 'counter' state variable +// note that getCounter mirrors the state of the 'counter' state variable // which means that if the state variable was not present it also will not be present in the result - func viewGetCounter(ctx wasmlib.ScViewContext, f *GetCounterContext) { counter := f.State.Counter() if counter.Exists() { @@ -116,43 +166,85 @@ func viewGetCounter(ctx wasmlib.ScViewContext, f *GetCounterContext) { } } -//nolint:unparam -func funcTestLeb128(ctx wasmlib.ScFuncContext, f *TestLeb128Context) { - leb128Save(ctx, "v-1", -1) - leb128Save(ctx, "v-2", -2) - leb128Save(ctx, "v-126", -126) - leb128Save(ctx, "v-127", -127) - leb128Save(ctx, "v-128", -128) - leb128Save(ctx, "v-129", -129) - leb128Save(ctx, "v0", 0) - leb128Save(ctx, "v+1", 1) - leb128Save(ctx, "v+2", 2) - leb128Save(ctx, "v+126", 126) - leb128Save(ctx, "v+127", 127) - leb128Save(ctx, "v+128", 128) - leb128Save(ctx, "v+129", 129) -} - -func leb128Save(ctx wasmlib.ScFuncContext, name string, value int64) { - encoder := wasmlib.NewBytesEncoder() - encoder.Int64(value) - spot := ctx.State().GetBytes(wasmlib.Key(name)) - spot.SetValue(encoder.Data()) - - bytes := spot.Value() - decoder := wasmlib.NewBytesDecoder(bytes) - retrieved := decoder.Int64() - if retrieved != value { - ctx.Log(name + " in : " + ctx.Utility().String(value)) - ctx.Log(name + " out: " + ctx.Utility().String(retrieved)) +//nolint:dupl +func viewGetVli(ctx wasmlib.ScViewContext, f *GetVliContext) { + enc := wasmtypes.NewWasmEncoder() + n := f.Params.Ni64().Value() + buf := enc.VliEncode(n).Buf() + dec := wasmtypes.NewWasmDecoder(buf) + x := wasmtypes.Int64Decode(dec) + + str := strconv.FormatInt(n, 10) + " -" + for j := 0; j < len(buf); j++ { + b := buf[j] + str += " " + string(append([]byte(nil), hex[(b>>4)&0x0f], hex[b&0x0f])) + } + str += " - " + strconv.FormatInt(x, 10) + + f.Results.Ni64().SetValue(n) + f.Results.Xi64().SetValue(x) + f.Results.Str().SetValue(str) + f.Results.Buf().SetValue(buf) +} + +//nolint:dupl +func viewGetVlu(ctx wasmlib.ScViewContext, f *GetVluContext) { + enc := wasmtypes.NewWasmEncoder() + n := f.Params.Nu64().Value() + buf := enc.VluEncode(n).Buf() + dec := wasmtypes.NewWasmDecoder(buf) + x := wasmtypes.Uint64Decode(dec) + + str := strconv.FormatUint(n, 10) + " -" + for j := 0; j < len(buf); j++ { + b := buf[j] + str += " " + string(append([]byte(nil), hex[(b>>4)&0x0f], hex[b&0x0f])) } + str += " - " + strconv.FormatUint(x, 10) + + f.Results.Nu64().SetValue(n) + f.Results.Xu64().SetValue(x) + f.Results.Str().SetValue(str) + f.Results.Buf().SetValue(buf) } +//////////////////////////////// util funcs \\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + func localStatePost(ctx wasmlib.ScFuncContext, nr int64) { // note: we add a dummy parameter here to prevent "duplicate outputs not allowed" error f := ScFuncs.WhenMustIncrement(ctx) f.Params.Dummy().SetValue(nr) - f.Func.TransferIotas(1).Post() + f.Func.Post() +} + +func vliSave(ctx wasmlib.ScFuncContext, name string, value int64) { + enc := wasmtypes.NewWasmEncoder() + state := ctx.RawState() + key := []byte(name) + state.Set(key, enc.VliEncode(value).Buf()) + + buf := state.Get(key) + dec := wasmtypes.NewWasmDecoder(buf) + val := dec.VliDecode(64) + if val != value { + ctx.Log(name + " in : " + wasmtypes.Int64ToString(value)) + ctx.Log(name + " out: " + wasmtypes.Int64ToString(val)) + } +} + +func vluSave(ctx wasmlib.ScFuncContext, name string, value uint64) { + enc := wasmtypes.NewWasmEncoder() + state := ctx.RawState() + key := []byte(name) + state.Set(key, enc.VluEncode(value).Buf()) + + buf := state.Get(key) + dec := wasmtypes.NewWasmDecoder(buf) + val := dec.VluDecode(64) + if val != value { + ctx.Log(name + " in : " + wasmtypes.Uint64ToString(value)) + ctx.Log(name + " out: " + wasmtypes.Uint64ToString(val)) + } } func whenMustIncrementState(ctx wasmlib.ScFuncContext, state MutableIncCounterState) { @@ -163,9 +255,3 @@ func whenMustIncrementState(ctx wasmlib.ScFuncContext, state MutableIncCounterSt counter := state.Counter() counter.SetValue(counter.Value() + 1) } - -func funcIncrementWithDelay(ctx wasmlib.ScFuncContext, f *IncrementWithDelayContext) { - delay := f.Params.Delay().Value() - inc := ScFuncs.CallIncrement(ctx) - inc.Func.Delay(delay).TransferIotas(1).Post() -} diff --git a/contracts/wasm/inccounter/go/inccounter/keys.go b/contracts/wasm/inccounter/go/inccounter/keys.go deleted file mode 100644 index 1741cdd8f9..0000000000 --- a/contracts/wasm/inccounter/go/inccounter/keys.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package inccounter - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamCounter = 0 - IdxParamDelay = 1 - IdxParamDummy = 2 - IdxParamNumRepeats = 3 - - IdxResultCounter = 4 - - IdxStateCounter = 5 - IdxStateNumRepeats = 6 -) - -const keyMapLen = 7 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamCounter, - ParamDelay, - ParamDummy, - ParamNumRepeats, - ResultCounter, - StateCounter, - StateNumRepeats, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/inccounter/go/inccounter/lib.go b/contracts/wasm/inccounter/go/inccounter/lib.go index 944556592f..c5ad476342 100644 --- a/contracts/wasm/inccounter/go/inccounter/lib.go +++ b/contracts/wasm/inccounter/go/inccounter/lib.go @@ -7,28 +7,58 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncCallIncrement, funcCallIncrementThunk) - exports.AddFunc(FuncCallIncrementRecurse5x, funcCallIncrementRecurse5xThunk) - exports.AddFunc(FuncEndlessLoop, funcEndlessLoopThunk) - exports.AddFunc(FuncIncrement, funcIncrementThunk) - exports.AddFunc(FuncIncrementWithDelay, funcIncrementWithDelayThunk) - exports.AddFunc(FuncInit, funcInitThunk) - exports.AddFunc(FuncLocalStateInternalCall, funcLocalStateInternalCallThunk) - exports.AddFunc(FuncLocalStatePost, funcLocalStatePostThunk) - exports.AddFunc(FuncLocalStateSandboxCall, funcLocalStateSandboxCallThunk) - exports.AddFunc(FuncPostIncrement, funcPostIncrementThunk) - exports.AddFunc(FuncRepeatMany, funcRepeatManyThunk) - exports.AddFunc(FuncTestLeb128, funcTestLeb128Thunk) - exports.AddFunc(FuncWhenMustIncrement, funcWhenMustIncrementThunk) - exports.AddView(ViewGetCounter, viewGetCounterThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncCallIncrement, + FuncCallIncrementRecurse5x, + FuncEndlessLoop, + FuncIncrement, + FuncIncrementWithDelay, + FuncInit, + FuncLocalStateInternalCall, + FuncLocalStatePost, + FuncLocalStateSandboxCall, + FuncPostIncrement, + FuncRepeatMany, + FuncTestVliCodec, + FuncTestVluCodec, + FuncWhenMustIncrement, + ViewGetCounter, + ViewGetVli, + ViewGetVlu, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcCallIncrementThunk, + funcCallIncrementRecurse5xThunk, + funcEndlessLoopThunk, + funcIncrementThunk, + funcIncrementWithDelayThunk, + funcInitThunk, + funcLocalStateInternalCallThunk, + funcLocalStatePostThunk, + funcLocalStateSandboxCallThunk, + funcPostIncrementThunk, + funcRepeatManyThunk, + funcTestVliCodecThunk, + funcTestVluCodecThunk, + funcWhenMustIncrementThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetCounterThunk, + viewGetVliThunk, + viewGetVluThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type CallIncrementContext struct { @@ -39,7 +69,7 @@ func funcCallIncrementThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcCallIncrement") f := &CallIncrementContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcCallIncrement(ctx, f) @@ -54,7 +84,7 @@ func funcCallIncrementRecurse5xThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcCallIncrementRecurse5x") f := &CallIncrementRecurse5xContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcCallIncrementRecurse5x(ctx, f) @@ -69,7 +99,7 @@ func funcEndlessLoopThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcEndlessLoop") f := &EndlessLoopContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcEndlessLoop(ctx, f) @@ -84,7 +114,7 @@ func funcIncrementThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcIncrement") f := &IncrementContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcIncrement(ctx, f) @@ -100,10 +130,10 @@ func funcIncrementWithDelayThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcIncrementWithDelay") f := &IncrementWithDelayContext{ Params: ImmutableIncrementWithDelayParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Delay().Exists(), "missing mandatory delay") @@ -120,10 +150,10 @@ func funcInitThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcInit") f := &InitContext{ Params: ImmutableInitParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcInit(ctx, f) @@ -138,7 +168,7 @@ func funcLocalStateInternalCallThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcLocalStateInternalCall") f := &LocalStateInternalCallContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcLocalStateInternalCall(ctx, f) @@ -153,7 +183,7 @@ func funcLocalStatePostThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcLocalStatePost") f := &LocalStatePostContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcLocalStatePost(ctx, f) @@ -168,7 +198,7 @@ func funcLocalStateSandboxCallThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcLocalStateSandboxCall") f := &LocalStateSandboxCallContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcLocalStateSandboxCall(ctx, f) @@ -183,7 +213,7 @@ func funcPostIncrementThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcPostIncrement") f := &PostIncrementContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcPostIncrement(ctx, f) @@ -199,29 +229,44 @@ func funcRepeatManyThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcRepeatMany") f := &RepeatManyContext{ Params: ImmutableRepeatManyParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcRepeatMany(ctx, f) ctx.Log("inccounter.funcRepeatMany ok") } -type TestLeb128Context struct { +type TestVliCodecContext struct { + State MutableIncCounterState +} + +func funcTestVliCodecThunk(ctx wasmlib.ScFuncContext) { + ctx.Log("inccounter.funcTestVliCodec") + f := &TestVliCodecContext{ + State: MutableIncCounterState{ + proxy: wasmlib.NewStateProxy(), + }, + } + funcTestVliCodec(ctx, f) + ctx.Log("inccounter.funcTestVliCodec ok") +} + +type TestVluCodecContext struct { State MutableIncCounterState } -func funcTestLeb128Thunk(ctx wasmlib.ScFuncContext) { - ctx.Log("inccounter.funcTestLeb128") - f := &TestLeb128Context{ +func funcTestVluCodecThunk(ctx wasmlib.ScFuncContext) { + ctx.Log("inccounter.funcTestVluCodec") + f := &TestVluCodecContext{ State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } - funcTestLeb128(ctx, f) - ctx.Log("inccounter.funcTestLeb128 ok") + funcTestVluCodec(ctx, f) + ctx.Log("inccounter.funcTestVluCodec ok") } type WhenMustIncrementContext struct { @@ -233,10 +278,10 @@ func funcWhenMustIncrementThunk(ctx wasmlib.ScFuncContext) { ctx.Log("inccounter.funcWhenMustIncrement") f := &WhenMustIncrementContext{ Params: ImmutableWhenMustIncrementParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcWhenMustIncrement(ctx, f) @@ -250,14 +295,68 @@ type GetCounterContext struct { func viewGetCounterThunk(ctx wasmlib.ScViewContext) { ctx.Log("inccounter.viewGetCounter") + results := wasmlib.NewScDict() f := &GetCounterContext{ Results: MutableGetCounterResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableIncCounterState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetCounter(ctx, f) + ctx.Results(results) ctx.Log("inccounter.viewGetCounter ok") } + +type GetVliContext struct { + Params ImmutableGetVliParams + Results MutableGetVliResults + State ImmutableIncCounterState +} + +func viewGetVliThunk(ctx wasmlib.ScViewContext) { + ctx.Log("inccounter.viewGetVli") + results := wasmlib.NewScDict() + f := &GetVliContext{ + Params: ImmutableGetVliParams{ + proxy: wasmlib.NewParamsProxy(), + }, + Results: MutableGetVliResults{ + proxy: results.AsProxy(), + }, + State: ImmutableIncCounterState{ + proxy: wasmlib.NewStateProxy(), + }, + } + ctx.Require(f.Params.Ni64().Exists(), "missing mandatory ni64") + viewGetVli(ctx, f) + ctx.Results(results) + ctx.Log("inccounter.viewGetVli ok") +} + +type GetVluContext struct { + Params ImmutableGetVluParams + Results MutableGetVluResults + State ImmutableIncCounterState +} + +func viewGetVluThunk(ctx wasmlib.ScViewContext) { + ctx.Log("inccounter.viewGetVlu") + results := wasmlib.NewScDict() + f := &GetVluContext{ + Params: ImmutableGetVluParams{ + proxy: wasmlib.NewParamsProxy(), + }, + Results: MutableGetVluResults{ + proxy: results.AsProxy(), + }, + State: ImmutableIncCounterState{ + proxy: wasmlib.NewStateProxy(), + }, + } + ctx.Require(f.Params.Nu64().Exists(), "missing mandatory nu64") + viewGetVlu(ctx, f) + ctx.Results(results) + ctx.Log("inccounter.viewGetVlu ok") +} diff --git a/contracts/wasm/inccounter/go/inccounter/params.go b/contracts/wasm/inccounter/go/inccounter/params.go index c9c340257e..017d37be87 100644 --- a/contracts/wasm/inccounter/go/inccounter/params.go +++ b/contracts/wasm/inccounter/go/inccounter/params.go @@ -7,68 +7,100 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableIncrementWithDelayParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableIncrementWithDelayParams) Delay() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamDelay)) +func (s ImmutableIncrementWithDelayParams) Delay() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamDelay)) } type MutableIncrementWithDelayParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableIncrementWithDelayParams) Delay() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamDelay)) +func (s MutableIncrementWithDelayParams) Delay() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamDelay)) } type ImmutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableInitParams) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, idxMap[IdxParamCounter]) +func (s ImmutableInitParams) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamCounter)) } type MutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableInitParams) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, idxMap[IdxParamCounter]) +func (s MutableInitParams) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamCounter)) } type ImmutableRepeatManyParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRepeatManyParams) NumRepeats() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamNumRepeats)) +func (s ImmutableRepeatManyParams) NumRepeats() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamNumRepeats)) } type MutableRepeatManyParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRepeatManyParams) NumRepeats() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamNumRepeats)) +func (s MutableRepeatManyParams) NumRepeats() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamNumRepeats)) } type ImmutableWhenMustIncrementParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableWhenMustIncrementParams) Dummy() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamDummy)) +func (s ImmutableWhenMustIncrementParams) Dummy() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamDummy)) } type MutableWhenMustIncrementParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableWhenMustIncrementParams) Dummy() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamDummy)) +func (s MutableWhenMustIncrementParams) Dummy() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamDummy)) +} + +type ImmutableGetVliParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetVliParams) Ni64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamNi64)) +} + +type MutableGetVliParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetVliParams) Ni64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamNi64)) +} + +type ImmutableGetVluParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetVluParams) Nu64() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamNu64)) +} + +type MutableGetVluParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetVluParams) Nu64() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamNu64)) } diff --git a/contracts/wasm/inccounter/go/inccounter/results.go b/contracts/wasm/inccounter/go/inccounter/results.go index 585f59b62f..bc6b2da0d9 100644 --- a/contracts/wasm/inccounter/go/inccounter/results.go +++ b/contracts/wasm/inccounter/go/inccounter/results.go @@ -7,20 +7,100 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableGetCounterResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetCounterResults) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultCounter)) +func (s ImmutableGetCounterResults) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultCounter)) } type MutableGetCounterResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetCounterResults) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultCounter)) +func (s MutableGetCounterResults) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultCounter)) +} + +type ImmutableGetVliResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetVliResults) Buf() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultBuf)) +} + +func (s ImmutableGetVliResults) Ni64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultNi64)) +} + +func (s ImmutableGetVliResults) Str() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultStr)) +} + +func (s ImmutableGetVliResults) Xi64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultXi64)) +} + +type MutableGetVliResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetVliResults) Buf() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultBuf)) +} + +func (s MutableGetVliResults) Ni64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultNi64)) +} + +func (s MutableGetVliResults) Str() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultStr)) +} + +func (s MutableGetVliResults) Xi64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultXi64)) +} + +type ImmutableGetVluResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetVluResults) Buf() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultBuf)) +} + +func (s ImmutableGetVluResults) Nu64() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultNu64)) +} + +func (s ImmutableGetVluResults) Str() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultStr)) +} + +func (s ImmutableGetVluResults) Xu64() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultXu64)) +} + +type MutableGetVluResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetVluResults) Buf() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultBuf)) +} + +func (s MutableGetVluResults) Nu64() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultNu64)) +} + +func (s MutableGetVluResults) Str() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultStr)) +} + +func (s MutableGetVluResults) Xu64() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultXu64)) } diff --git a/contracts/wasm/inccounter/go/inccounter/state.go b/contracts/wasm/inccounter/go/inccounter/state.go index f406babfb8..20cecd965f 100644 --- a/contracts/wasm/inccounter/go/inccounter/state.go +++ b/contracts/wasm/inccounter/go/inccounter/state.go @@ -7,32 +7,32 @@ package inccounter -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableIncCounterState struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableIncCounterState) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateCounter)) +func (s ImmutableIncCounterState) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(StateCounter)) } -func (s ImmutableIncCounterState) NumRepeats() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateNumRepeats)) +func (s ImmutableIncCounterState) NumRepeats() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(StateNumRepeats)) } type MutableIncCounterState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableIncCounterState) AsImmutable() ImmutableIncCounterState { return ImmutableIncCounterState(s) } -func (s MutableIncCounterState) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateCounter)) +func (s MutableIncCounterState) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(StateCounter)) } -func (s MutableIncCounterState) NumRepeats() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateNumRepeats)) +func (s MutableIncCounterState) NumRepeats() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(StateNumRepeats)) } diff --git a/contracts/wasm/inccounter/go/main.go b/contracts/wasm/inccounter/go/main.go index 47c9e2a29f..b41fcde26e 100644 --- a/contracts/wasm/inccounter/go/main.go +++ b/contracts/wasm/inccounter/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/inccounter/go/inccounter" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + inccounter.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - inccounter.OnLoad() + inccounter.OnLoad(-1) } diff --git a/contracts/wasm/inccounter/schema.yaml b/contracts/wasm/inccounter/schema.yaml index 587b65366b..91ec5304c5 100644 --- a/contracts/wasm/inccounter/schema.yaml +++ b/contracts/wasm/inccounter/schema.yaml @@ -12,7 +12,7 @@ funcs: increment: {} incrementWithDelay: params: - delay: Int32 // delay in seconds + delay: Uint32 // delay in seconds init: params: counter: Int64? // value to initialize state counter with @@ -23,7 +23,8 @@ funcs: repeatMany: params: numRepeats: Int64? // number of times to recursively call myself - testLeb128: {} + testVliCodec: {} + testVluCodec: {} whenMustIncrement: params: dummy: Int64? // dummy param to prevent 'duplicate outputs not allowed' @@ -31,3 +32,19 @@ views: getCounter: results: counter: Int64 + getVli: + params: + ni64: Int64 + results: + ni64: Int64 + xi64: Int64 + buf: Bytes + str: String + getVlu: + params: + nu64: Uint64 + results: + nu64: Uint64 + xu64: Uint64 + buf: Bytes + str: String diff --git a/contracts/wasm/inccounter/src/consts.rs b/contracts/wasm/inccounter/src/consts.rs index e1590fc5ba..2011b76b66 100644 --- a/contracts/wasm/inccounter/src/consts.rs +++ b/contracts/wasm/inccounter/src/consts.rs @@ -16,9 +16,17 @@ pub const HSC_NAME : ScHname = ScHname(0xaf2438e9); pub const PARAM_COUNTER : &str = "counter"; pub const PARAM_DELAY : &str = "delay"; pub const PARAM_DUMMY : &str = "dummy"; +pub const PARAM_NI64 : &str = "ni64"; +pub const PARAM_NU64 : &str = "nu64"; pub const PARAM_NUM_REPEATS : &str = "numRepeats"; +pub const RESULT_BUF : &str = "buf"; pub const RESULT_COUNTER : &str = "counter"; +pub const RESULT_NI64 : &str = "ni64"; +pub const RESULT_NU64 : &str = "nu64"; +pub const RESULT_STR : &str = "str"; +pub const RESULT_XI64 : &str = "xi64"; +pub const RESULT_XU64 : &str = "xu64"; pub const STATE_COUNTER : &str = "counter"; pub const STATE_NUM_REPEATS : &str = "numRepeats"; @@ -34,9 +42,12 @@ pub const FUNC_LOCAL_STATE_POST : &str = "localStatePost"; pub const FUNC_LOCAL_STATE_SANDBOX_CALL : &str = "localStateSandboxCall"; pub const FUNC_POST_INCREMENT : &str = "postIncrement"; pub const FUNC_REPEAT_MANY : &str = "repeatMany"; -pub const FUNC_TEST_LEB128 : &str = "testLeb128"; +pub const FUNC_TEST_VLI_CODEC : &str = "testVliCodec"; +pub const FUNC_TEST_VLU_CODEC : &str = "testVluCodec"; pub const FUNC_WHEN_MUST_INCREMENT : &str = "whenMustIncrement"; pub const VIEW_GET_COUNTER : &str = "getCounter"; +pub const VIEW_GET_VLI : &str = "getVli"; +pub const VIEW_GET_VLU : &str = "getVlu"; pub const HFUNC_CALL_INCREMENT : ScHname = ScHname(0xeb5dcacd); pub const HFUNC_CALL_INCREMENT_RECURSE5X : ScHname = ScHname(0x8749fbff); @@ -49,6 +60,9 @@ pub const HFUNC_LOCAL_STATE_POST : ScHname = ScHname(0x3fd54d13); pub const HFUNC_LOCAL_STATE_SANDBOX_CALL : ScHname = ScHname(0x7bd22c53); pub const HFUNC_POST_INCREMENT : ScHname = ScHname(0x81c772f5); pub const HFUNC_REPEAT_MANY : ScHname = ScHname(0x4ff450d3); -pub const HFUNC_TEST_LEB128 : ScHname = ScHname(0xd8364cb9); +pub const HFUNC_TEST_VLI_CODEC : ScHname = ScHname(0xd5356012); +pub const HFUNC_TEST_VLU_CODEC : ScHname = ScHname(0x9f7f63e6); pub const HFUNC_WHEN_MUST_INCREMENT : ScHname = ScHname(0xb4c3e7a6); pub const HVIEW_GET_COUNTER : ScHname = ScHname(0xb423e607); +pub const HVIEW_GET_VLI : ScHname = ScHname(0x0ee16f89); +pub const HVIEW_GET_VLU : ScHname = ScHname(0x54d624e6); diff --git a/contracts/wasm/inccounter/src/contract.rs b/contracts/wasm/inccounter/src/contract.rs index 5f5c59845c..02ece4b5da 100644 --- a/contracts/wasm/inccounter/src/contract.rs +++ b/contracts/wasm/inccounter/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct CallIncrementCall { pub func: ScFunc, @@ -62,7 +57,11 @@ pub struct RepeatManyCall { pub params: MutableRepeatManyParams, } -pub struct TestLeb128Call { +pub struct TestVliCodecCall { + pub func: ScFunc, +} + +pub struct TestVluCodecCall { pub func: ScFunc, } @@ -76,106 +75,146 @@ pub struct GetCounterCall { pub results: ImmutableGetCounterResults, } +pub struct GetVliCall { + pub func: ScView, + pub params: MutableGetVliParams, + pub results: ImmutableGetVliResults, +} + +pub struct GetVluCall { + pub func: ScView, + pub params: MutableGetVluParams, + pub results: ImmutableGetVluResults, +} + pub struct ScFuncs { } impl ScFuncs { - pub fn call_increment(_ctx: & dyn ScFuncCallContext) -> CallIncrementCall { + pub fn call_increment(_ctx: &dyn ScFuncCallContext) -> CallIncrementCall { CallIncrementCall { func: ScFunc::new(HSC_NAME, HFUNC_CALL_INCREMENT), } } - pub fn call_increment_recurse5x(_ctx: & dyn ScFuncCallContext) -> CallIncrementRecurse5xCall { + pub fn call_increment_recurse5x(_ctx: &dyn ScFuncCallContext) -> CallIncrementRecurse5xCall { CallIncrementRecurse5xCall { func: ScFunc::new(HSC_NAME, HFUNC_CALL_INCREMENT_RECURSE5X), } } - pub fn endless_loop(_ctx: & dyn ScFuncCallContext) -> EndlessLoopCall { + pub fn endless_loop(_ctx: &dyn ScFuncCallContext) -> EndlessLoopCall { EndlessLoopCall { func: ScFunc::new(HSC_NAME, HFUNC_ENDLESS_LOOP), } } - pub fn increment(_ctx: & dyn ScFuncCallContext) -> IncrementCall { + pub fn increment(_ctx: &dyn ScFuncCallContext) -> IncrementCall { IncrementCall { func: ScFunc::new(HSC_NAME, HFUNC_INCREMENT), } } - pub fn increment_with_delay(_ctx: & dyn ScFuncCallContext) -> IncrementWithDelayCall { + pub fn increment_with_delay(_ctx: &dyn ScFuncCallContext) -> IncrementWithDelayCall { let mut f = IncrementWithDelayCall { func: ScFunc::new(HSC_NAME, HFUNC_INCREMENT_WITH_DELAY), - params: MutableIncrementWithDelayParams { id: 0 }, + params: MutableIncrementWithDelayParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn init(_ctx: & dyn ScFuncCallContext) -> InitCall { + pub fn init(_ctx: &dyn ScFuncCallContext) -> InitCall { let mut f = InitCall { func: ScInitFunc::new(HSC_NAME, HFUNC_INIT), - params: MutableInitParams { id: 0 }, + params: MutableInitParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScInitFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn local_state_internal_call(_ctx: & dyn ScFuncCallContext) -> LocalStateInternalCallCall { + pub fn local_state_internal_call(_ctx: &dyn ScFuncCallContext) -> LocalStateInternalCallCall { LocalStateInternalCallCall { func: ScFunc::new(HSC_NAME, HFUNC_LOCAL_STATE_INTERNAL_CALL), } } - pub fn local_state_post(_ctx: & dyn ScFuncCallContext) -> LocalStatePostCall { + pub fn local_state_post(_ctx: &dyn ScFuncCallContext) -> LocalStatePostCall { LocalStatePostCall { func: ScFunc::new(HSC_NAME, HFUNC_LOCAL_STATE_POST), } } - pub fn local_state_sandbox_call(_ctx: & dyn ScFuncCallContext) -> LocalStateSandboxCallCall { + pub fn local_state_sandbox_call(_ctx: &dyn ScFuncCallContext) -> LocalStateSandboxCallCall { LocalStateSandboxCallCall { func: ScFunc::new(HSC_NAME, HFUNC_LOCAL_STATE_SANDBOX_CALL), } } - pub fn post_increment(_ctx: & dyn ScFuncCallContext) -> PostIncrementCall { + pub fn post_increment(_ctx: &dyn ScFuncCallContext) -> PostIncrementCall { PostIncrementCall { func: ScFunc::new(HSC_NAME, HFUNC_POST_INCREMENT), } } - pub fn repeat_many(_ctx: & dyn ScFuncCallContext) -> RepeatManyCall { + pub fn repeat_many(_ctx: &dyn ScFuncCallContext) -> RepeatManyCall { let mut f = RepeatManyCall { func: ScFunc::new(HSC_NAME, HFUNC_REPEAT_MANY), - params: MutableRepeatManyParams { id: 0 }, + params: MutableRepeatManyParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn test_leb128(_ctx: & dyn ScFuncCallContext) -> TestLeb128Call { - TestLeb128Call { - func: ScFunc::new(HSC_NAME, HFUNC_TEST_LEB128), + pub fn test_vli_codec(_ctx: &dyn ScFuncCallContext) -> TestVliCodecCall { + TestVliCodecCall { + func: ScFunc::new(HSC_NAME, HFUNC_TEST_VLI_CODEC), } } - pub fn when_must_increment(_ctx: & dyn ScFuncCallContext) -> WhenMustIncrementCall { + pub fn test_vlu_codec(_ctx: &dyn ScFuncCallContext) -> TestVluCodecCall { + TestVluCodecCall { + func: ScFunc::new(HSC_NAME, HFUNC_TEST_VLU_CODEC), + } + } + + pub fn when_must_increment(_ctx: &dyn ScFuncCallContext) -> WhenMustIncrementCall { let mut f = WhenMustIncrementCall { func: ScFunc::new(HSC_NAME, HFUNC_WHEN_MUST_INCREMENT), - params: MutableWhenMustIncrementParams { id: 0 }, + params: MutableWhenMustIncrementParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn get_counter(_ctx: & dyn ScViewCallContext) -> GetCounterCall { + pub fn get_counter(_ctx: &dyn ScViewCallContext) -> GetCounterCall { let mut f = GetCounterCall { func: ScView::new(HSC_NAME, HVIEW_GET_COUNTER), - results: ImmutableGetCounterResults { id: 0 }, + results: ImmutableGetCounterResults { proxy: Proxy::nil() }, + }; + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_vli(_ctx: &dyn ScViewCallContext) -> GetVliCall { + let mut f = GetVliCall { + func: ScView::new(HSC_NAME, HVIEW_GET_VLI), + params: MutableGetVliParams { proxy: Proxy::nil() }, + results: ImmutableGetVliResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_vlu(_ctx: &dyn ScViewCallContext) -> GetVluCall { + let mut f = GetVluCall { + func: ScView::new(HSC_NAME, HVIEW_GET_VLU), + params: MutableGetVluParams { proxy: Proxy::nil() }, + results: ImmutableGetVluResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/inccounter/src/inccounter.rs b/contracts/wasm/inccounter/src/inccounter.rs index a7fef760ca..5750a09296 100644 --- a/contracts/wasm/inccounter/src/inccounter.rs +++ b/contracts/wasm/inccounter/src/inccounter.rs @@ -6,8 +6,17 @@ use wasmlib::*; use crate::*; use crate::contract::*; +const HEX: &str = "0123456789abcdef"; + static mut LOCAL_STATE_MUST_INCREMENT: bool = false; +pub fn func_init(_ctx: &ScFuncContext, f: &InitContext) { + if f.params.counter().exists() { + let counter = f.params.counter().value(); + f.state.counter().set_value(counter); + } +} + pub fn func_call_increment(ctx: &ScFuncContext, f: &CallIncrementContext) { let counter = f.state.counter(); let value = counter.value(); @@ -38,14 +47,7 @@ pub fn func_increment(_ctx: &ScFuncContext, f: &IncrementContext) { pub fn func_increment_with_delay(ctx: &ScFuncContext, f: &IncrementWithDelayContext) { let delay = f.params.delay().value(); let inc = ScFuncs::call_increment(ctx); - inc.func.delay(delay).transfer_iotas(1).post(); -} - -pub fn func_init(_ctx: &ScFuncContext, f: &InitContext) { - if f.params.counter().exists() { - let counter = f.params.counter().value(); - f.state.counter().set_value(counter); - } + inc.func.delay(delay).post(); } pub fn func_local_state_internal_call(ctx: &ScFuncContext, f: &LocalStateInternalCallContext) { @@ -93,7 +95,7 @@ pub fn func_post_increment(ctx: &ScFuncContext, f: &PostIncrementContext) { let value = counter.value(); counter.set_value(value + 1); if value == 0 { - ScFuncs::increment(ctx).func.transfer_iotas(1).post(); + ScFuncs::increment(ctx).func.post(); } } @@ -110,23 +112,45 @@ pub fn func_repeat_many(ctx: &ScFuncContext, f: &RepeatManyContext) { } } state_repeats.set_value(repeats - 1); - ScFuncs::repeat_many(ctx).func.transfer_iotas(1).post(); + ScFuncs::repeat_many(ctx).func.post(); +} + +pub fn func_test_vli_codec(ctx: &ScFuncContext, _f: &TestVliCodecContext) { + vli_save(ctx, "v-129", -129); + vli_save(ctx, "v-128", -128); + vli_save(ctx, "v-127", -127); + vli_save(ctx, "v-126", -126); + vli_save(ctx, "v-65", -65); + vli_save(ctx, "v-64", -64); + vli_save(ctx, "v-63", -63); + vli_save(ctx, "v-62", -62); + vli_save(ctx, "v-2", -2); + vli_save(ctx, "v-1", -1); + vli_save(ctx, "v 0", 0); + vli_save(ctx, "v+1", 1); + vli_save(ctx, "v+2", 2); + vli_save(ctx, "v+62", 62); + vli_save(ctx, "v+63", 63); + vli_save(ctx, "v+64", 64); + vli_save(ctx, "v+65", 65); + vli_save(ctx, "v+126", 126); + vli_save(ctx, "v+127", 127); + vli_save(ctx, "v+128", 128); + vli_save(ctx, "v+129", 129); } -pub fn func_test_leb128(ctx: &ScFuncContext, _f: &TestLeb128Context) { - leb128_save(ctx, "v-1", -1); - leb128_save(ctx, "v-2", -2); - leb128_save(ctx, "v-126", -126); - leb128_save(ctx, "v-127", -127); - leb128_save(ctx, "v-128", -128); - leb128_save(ctx, "v-129", -129); - leb128_save(ctx, "v0", 0); - leb128_save(ctx, "v+1", 1); - leb128_save(ctx, "v+2", 2); - leb128_save(ctx, "v+126", 126); - leb128_save(ctx, "v+127", 127); - leb128_save(ctx, "v+128", 128); - leb128_save(ctx, "v+129", 129); +pub fn func_test_vlu_codec(ctx: &ScFuncContext, _f: &TestVluCodecContext) { + vlu_save(ctx, "v 0", 0); + vlu_save(ctx, "v+1", 1); + vlu_save(ctx, "v+2", 2); + vlu_save(ctx, "v+62", 62); + vlu_save(ctx, "v+63", 63); + vlu_save(ctx, "v+64", 64); + vlu_save(ctx, "v+65", 65); + vlu_save(ctx, "v+126", 126); + vlu_save(ctx, "v+127", 127); + vlu_save(ctx, "v+128", 128); + vlu_save(ctx, "v+129", 129); } pub fn func_when_must_increment(ctx: &ScFuncContext, f: &WhenMustIncrementContext) { @@ -142,26 +166,87 @@ pub fn view_get_counter(_ctx: &ScViewContext, f: &GetCounterContext) { } } -fn leb128_save(ctx: &ScFuncContext, name: &str, value: i64) { - let mut encoder = BytesEncoder::new(); - encoder.int64(value); - let spot = ctx.state().get_bytes(name); - spot.set_value(&encoder.data()); +pub fn view_get_vli(_ctx: &ScViewContext, f: &GetVliContext) { + let mut enc = WasmEncoder::new(); + let n = f.params.ni64().value(); + int64_encode(&mut enc,n); + let buf = enc.buf(); + let mut dec = WasmDecoder::new(&buf); + let x = int64_decode(&mut dec); - let bytes = spot.value(); - let mut decoder = BytesDecoder::new(&bytes); - let retrieved = decoder.int64(); - if retrieved != value { - ctx.log(&(name.to_string() + " in : " + &value.to_string())); - ctx.log(&(name.to_string() + " out: " + &retrieved.to_string())); + let mut str = n.to_string() + " -"; + for b in &buf { + let h1 = ((b >> 4) & 0x0f) as usize; + let h2 = (b & 0x0f) as usize; + str += &(" ".to_string() + &HEX[h1..h1+1] + &HEX[h2..h2+1]); } + str += &(" - ".to_string() + &x.to_string()); + + f.results.ni64().set_value(n); + f.results.xi64().set_value(x); + f.results.str().set_value(&str); + f.results.buf().set_value(&buf); } +pub fn view_get_vlu(_ctx: &ScViewContext, f: &GetVluContext) { + let mut enc = WasmEncoder::new(); + let n = f.params.nu64().value(); + uint64_encode(&mut enc, n); + let buf = enc.buf(); + let mut dec = WasmDecoder::new(&buf); + let x = uint64_decode(&mut dec); + + let mut str = n.to_string() + " -"; + for b in &buf { + let h1 = ((b >> 4) & 0x0f) as usize; + let h2 = (b & 0x0f) as usize; + str += &(" ".to_string() + &HEX[h1..h1+1] + &HEX[h2..h2+1]); + } + str += &(" - ".to_string() + &x.to_string()); + + f.results.nu64().set_value(n); + f.results.xu64().set_value(x); + f.results.str().set_value(&str); + f.results.buf().set_value(&buf); +} + +//////////////////////////////// util funcs \\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + fn local_state_post(ctx: &ScFuncContext, nr: i64) { //note: we add a dummy parameter here to prevent "duplicate outputs not allowed" error let f = ScFuncs::when_must_increment(ctx); f.params.dummy().set_value(nr); - f.func.transfer_iotas(1).post(); + f.func.post(); +} + +fn vli_save(ctx: &ScFuncContext, name: &str, value: i64) { + let mut enc = WasmEncoder::new(); + let state = ctx.raw_state(); + let key = string_to_bytes(name); + state.set(&key, &enc.vli_encode(value).buf()); + + let buf = state.get(&key); + let mut dec = WasmDecoder::new(&buf); + let val = dec.vli_decode(64); + if val != value { + ctx.log(&(name.to_string() + " in : " + &value.to_string())); + ctx.log(&(name.to_string() + " out: " + &val.to_string())); + } +} + +fn vlu_save(ctx: &ScFuncContext, name: &str, value: u64) { + let mut enc = WasmEncoder::new(); + let state = ctx.raw_state(); + let key = string_to_bytes(name); + state.set(&key, &enc.vlu_encode(value).buf()); + + let buf = state.get(&key); + let mut dec = WasmDecoder::new(&buf); + let val = dec.vlu_decode(64); + if val != value { + ctx.log(&(name.to_string() + " in : " + &value.to_string())); + ctx.log(&(name.to_string() + " out: " + &val.to_string())); + } } fn when_must_increment_state(ctx: &ScFuncContext, state: &MutableIncCounterState) { diff --git a/contracts/wasm/inccounter/src/keys.rs b/contracts/wasm/inccounter/src/keys.rs deleted file mode 100644 index cdbc2c396b..0000000000 --- a/contracts/wasm/inccounter/src/keys.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_COUNTER : usize = 0; -pub(crate) const IDX_PARAM_DELAY : usize = 1; -pub(crate) const IDX_PARAM_DUMMY : usize = 2; -pub(crate) const IDX_PARAM_NUM_REPEATS : usize = 3; - -pub(crate) const IDX_RESULT_COUNTER : usize = 4; - -pub(crate) const IDX_STATE_COUNTER : usize = 5; -pub(crate) const IDX_STATE_NUM_REPEATS : usize = 6; - -pub const KEY_MAP_LEN: usize = 7; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_COUNTER, - PARAM_DELAY, - PARAM_DUMMY, - PARAM_NUM_REPEATS, - RESULT_COUNTER, - STATE_COUNTER, - STATE_NUM_REPEATS, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/inccounter/src/lib.rs b/contracts/wasm/inccounter/src/lib.rs index e29777eda3..9fc00af8a5 100644 --- a/contracts/wasm/inccounter/src/lib.rs +++ b/contracts/wasm/inccounter/src/lib.rs @@ -10,45 +10,71 @@ use inccounter::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; mod consts; mod contract; -mod keys; mod params; mod results; mod state; + mod inccounter; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_CALL_INCREMENT, + FUNC_CALL_INCREMENT_RECURSE5X, + FUNC_ENDLESS_LOOP, + FUNC_INCREMENT, + FUNC_INCREMENT_WITH_DELAY, + FUNC_INIT, + FUNC_LOCAL_STATE_INTERNAL_CALL, + FUNC_LOCAL_STATE_POST, + FUNC_LOCAL_STATE_SANDBOX_CALL, + FUNC_POST_INCREMENT, + FUNC_REPEAT_MANY, + FUNC_TEST_VLI_CODEC, + FUNC_TEST_VLU_CODEC, + FUNC_WHEN_MUST_INCREMENT, + VIEW_GET_COUNTER, + VIEW_GET_VLI, + VIEW_GET_VLU, + ], + funcs: &[ + func_call_increment_thunk, + func_call_increment_recurse5x_thunk, + func_endless_loop_thunk, + func_increment_thunk, + func_increment_with_delay_thunk, + func_init_thunk, + func_local_state_internal_call_thunk, + func_local_state_post_thunk, + func_local_state_sandbox_call_thunk, + func_post_increment_thunk, + func_repeat_many_thunk, + func_test_vli_codec_thunk, + func_test_vlu_codec_thunk, + func_when_must_increment_thunk, + ], + views: &[ + view_get_counter_thunk, + view_get_vli_thunk, + view_get_vlu_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_CALL_INCREMENT, func_call_increment_thunk); - exports.add_func(FUNC_CALL_INCREMENT_RECURSE5X, func_call_increment_recurse5x_thunk); - exports.add_func(FUNC_ENDLESS_LOOP, func_endless_loop_thunk); - exports.add_func(FUNC_INCREMENT, func_increment_thunk); - exports.add_func(FUNC_INCREMENT_WITH_DELAY, func_increment_with_delay_thunk); - exports.add_func(FUNC_INIT, func_init_thunk); - exports.add_func(FUNC_LOCAL_STATE_INTERNAL_CALL, func_local_state_internal_call_thunk); - exports.add_func(FUNC_LOCAL_STATE_POST, func_local_state_post_thunk); - exports.add_func(FUNC_LOCAL_STATE_SANDBOX_CALL, func_local_state_sandbox_call_thunk); - exports.add_func(FUNC_POST_INCREMENT, func_post_increment_thunk); - exports.add_func(FUNC_REPEAT_MANY, func_repeat_many_thunk); - exports.add_func(FUNC_TEST_LEB128, func_test_leb128_thunk); - exports.add_func(FUNC_WHEN_MUST_INCREMENT, func_when_must_increment_thunk); - exports.add_view(VIEW_GET_COUNTER, view_get_counter_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct CallIncrementContext { @@ -58,9 +84,7 @@ pub struct CallIncrementContext { fn func_call_increment_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcCallIncrement"); let f = CallIncrementContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_call_increment(ctx, &f); ctx.log("inccounter.funcCallIncrement ok"); @@ -73,9 +97,7 @@ pub struct CallIncrementRecurse5xContext { fn func_call_increment_recurse5x_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcCallIncrementRecurse5x"); let f = CallIncrementRecurse5xContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_call_increment_recurse5x(ctx, &f); ctx.log("inccounter.funcCallIncrementRecurse5x ok"); @@ -88,9 +110,7 @@ pub struct EndlessLoopContext { fn func_endless_loop_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcEndlessLoop"); let f = EndlessLoopContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_endless_loop(ctx, &f); ctx.log("inccounter.funcEndlessLoop ok"); @@ -103,9 +123,7 @@ pub struct IncrementContext { fn func_increment_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcIncrement"); let f = IncrementContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_increment(ctx, &f); ctx.log("inccounter.funcIncrement ok"); @@ -119,12 +137,8 @@ pub struct IncrementWithDelayContext { fn func_increment_with_delay_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcIncrementWithDelay"); let f = IncrementWithDelayContext { - params: ImmutableIncrementWithDelayParams { - id: OBJ_ID_PARAMS, - }, - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + params: ImmutableIncrementWithDelayParams { proxy: params_proxy() }, + state: MutableIncCounterState { proxy: state_proxy() }, }; ctx.require(f.params.delay().exists(), "missing mandatory delay"); func_increment_with_delay(ctx, &f); @@ -139,12 +153,8 @@ pub struct InitContext { fn func_init_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcInit"); let f = InitContext { - params: ImmutableInitParams { - id: OBJ_ID_PARAMS, - }, - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + params: ImmutableInitParams { proxy: params_proxy() }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_init(ctx, &f); ctx.log("inccounter.funcInit ok"); @@ -157,9 +167,7 @@ pub struct LocalStateInternalCallContext { fn func_local_state_internal_call_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcLocalStateInternalCall"); let f = LocalStateInternalCallContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_local_state_internal_call(ctx, &f); ctx.log("inccounter.funcLocalStateInternalCall ok"); @@ -172,9 +180,7 @@ pub struct LocalStatePostContext { fn func_local_state_post_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcLocalStatePost"); let f = LocalStatePostContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_local_state_post(ctx, &f); ctx.log("inccounter.funcLocalStatePost ok"); @@ -187,9 +193,7 @@ pub struct LocalStateSandboxCallContext { fn func_local_state_sandbox_call_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcLocalStateSandboxCall"); let f = LocalStateSandboxCallContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_local_state_sandbox_call(ctx, &f); ctx.log("inccounter.funcLocalStateSandboxCall ok"); @@ -202,9 +206,7 @@ pub struct PostIncrementContext { fn func_post_increment_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcPostIncrement"); let f = PostIncrementContext { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_post_increment(ctx, &f); ctx.log("inccounter.funcPostIncrement ok"); @@ -218,30 +220,37 @@ pub struct RepeatManyContext { fn func_repeat_many_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcRepeatMany"); let f = RepeatManyContext { - params: ImmutableRepeatManyParams { - id: OBJ_ID_PARAMS, - }, - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + params: ImmutableRepeatManyParams { proxy: params_proxy() }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_repeat_many(ctx, &f); ctx.log("inccounter.funcRepeatMany ok"); } -pub struct TestLeb128Context { +pub struct TestVliCodecContext { + state: MutableIncCounterState, +} + +fn func_test_vli_codec_thunk(ctx: &ScFuncContext) { + ctx.log("inccounter.funcTestVliCodec"); + let f = TestVliCodecContext { + state: MutableIncCounterState { proxy: state_proxy() }, + }; + func_test_vli_codec(ctx, &f); + ctx.log("inccounter.funcTestVliCodec ok"); +} + +pub struct TestVluCodecContext { state: MutableIncCounterState, } -fn func_test_leb128_thunk(ctx: &ScFuncContext) { - ctx.log("inccounter.funcTestLeb128"); - let f = TestLeb128Context { - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, +fn func_test_vlu_codec_thunk(ctx: &ScFuncContext) { + ctx.log("inccounter.funcTestVluCodec"); + let f = TestVluCodecContext { + state: MutableIncCounterState { proxy: state_proxy() }, }; - func_test_leb128(ctx, &f); - ctx.log("inccounter.funcTestLeb128 ok"); + func_test_vlu_codec(ctx, &f); + ctx.log("inccounter.funcTestVluCodec ok"); } pub struct WhenMustIncrementContext { @@ -252,12 +261,8 @@ pub struct WhenMustIncrementContext { fn func_when_must_increment_thunk(ctx: &ScFuncContext) { ctx.log("inccounter.funcWhenMustIncrement"); let f = WhenMustIncrementContext { - params: ImmutableWhenMustIncrementParams { - id: OBJ_ID_PARAMS, - }, - state: MutableIncCounterState { - id: OBJ_ID_STATE, - }, + params: ImmutableWhenMustIncrementParams { proxy: params_proxy() }, + state: MutableIncCounterState { proxy: state_proxy() }, }; func_when_must_increment(ctx, &f); ctx.log("inccounter.funcWhenMustIncrement ok"); @@ -271,13 +276,48 @@ pub struct GetCounterContext { fn view_get_counter_thunk(ctx: &ScViewContext) { ctx.log("inccounter.viewGetCounter"); let f = GetCounterContext { - results: MutableGetCounterResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableIncCounterState { - id: OBJ_ID_STATE, - }, + results: MutableGetCounterResults { proxy: results_proxy() }, + state: ImmutableIncCounterState { proxy: state_proxy() }, }; view_get_counter(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("inccounter.viewGetCounter ok"); } + +pub struct GetVliContext { + params: ImmutableGetVliParams, + results: MutableGetVliResults, + state: ImmutableIncCounterState, +} + +fn view_get_vli_thunk(ctx: &ScViewContext) { + ctx.log("inccounter.viewGetVli"); + let f = GetVliContext { + params: ImmutableGetVliParams { proxy: params_proxy() }, + results: MutableGetVliResults { proxy: results_proxy() }, + state: ImmutableIncCounterState { proxy: state_proxy() }, + }; + ctx.require(f.params.ni64().exists(), "missing mandatory ni64"); + view_get_vli(ctx, &f); + ctx.results(&f.results.proxy.kv_store); + ctx.log("inccounter.viewGetVli ok"); +} + +pub struct GetVluContext { + params: ImmutableGetVluParams, + results: MutableGetVluResults, + state: ImmutableIncCounterState, +} + +fn view_get_vlu_thunk(ctx: &ScViewContext) { + ctx.log("inccounter.viewGetVlu"); + let f = GetVluContext { + params: ImmutableGetVluParams { proxy: params_proxy() }, + results: MutableGetVluResults { proxy: results_proxy() }, + state: ImmutableIncCounterState { proxy: state_proxy() }, + }; + ctx.require(f.params.nu64().exists(), "missing mandatory nu64"); + view_get_vlu(ctx, &f); + ctx.results(&f.results.proxy.kv_store); + ctx.log("inccounter.viewGetVlu ok"); +} diff --git a/contracts/wasm/inccounter/src/params.rs b/contracts/wasm/inccounter/src/params.rs index 27d5a8ff01..311b1b3527 100644 --- a/contracts/wasm/inccounter/src/params.rs +++ b/contracts/wasm/inccounter/src/params.rs @@ -9,95 +9,136 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableIncrementWithDelayParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableIncrementWithDelayParams { - pub fn delay(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_DELAY.get_key_id()) + pub fn delay(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_DELAY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableIncrementWithDelayParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableIncrementWithDelayParams { - pub fn delay(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_DELAY.get_key_id()) + pub fn delay(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_DELAY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableInitParams { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, idx_map(IDX_PARAM_COUNTER)) + ScImmutableInt64::new(self.proxy.root(PARAM_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableInitParams { pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, idx_map(IDX_PARAM_COUNTER)) + ScMutableInt64::new(self.proxy.root(PARAM_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRepeatManyParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRepeatManyParams { pub fn num_repeats(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_NUM_REPEATS.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_NUM_REPEATS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRepeatManyParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRepeatManyParams { pub fn num_repeats(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_NUM_REPEATS.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_NUM_REPEATS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableWhenMustIncrementParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableWhenMustIncrementParams { pub fn dummy(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_DUMMY.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_DUMMY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableWhenMustIncrementParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableWhenMustIncrementParams { pub fn dummy(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_DUMMY.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_DUMMY)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetVliParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetVliParams { + pub fn ni64(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(PARAM_NI64)) + } +} + +#[derive(Clone)] +pub struct MutableGetVliParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetVliParams { + pub fn ni64(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(PARAM_NI64)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetVluParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetVluParams { + pub fn nu64(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(PARAM_NU64)) + } +} + +#[derive(Clone)] +pub struct MutableGetVluParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetVluParams { + pub fn nu64(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(PARAM_NU64)) } } diff --git a/contracts/wasm/inccounter/src/results.rs b/contracts/wasm/inccounter/src/results.rs index 4106744dcb..5afa0ca1b0 100644 --- a/contracts/wasm/inccounter/src/results.rs +++ b/contracts/wasm/inccounter/src/results.rs @@ -9,29 +9,118 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetCounterResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetCounterResults { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_COUNTER.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetCounterResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetCounterResults { pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_COUNTER.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_COUNTER)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetVliResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetVliResults { + pub fn buf(&self) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.root(RESULT_BUF)) + } + + pub fn ni64(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_NI64)) + } + + pub fn str(&self) -> ScImmutableString { + ScImmutableString::new(self.proxy.root(RESULT_STR)) + } + + pub fn xi64(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_XI64)) + } +} + +#[derive(Clone)] +pub struct MutableGetVliResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetVliResults { + pub fn buf(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.root(RESULT_BUF)) + } + + pub fn ni64(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_NI64)) + } + + pub fn str(&self) -> ScMutableString { + ScMutableString::new(self.proxy.root(RESULT_STR)) + } + + pub fn xi64(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_XI64)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetVluResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetVluResults { + pub fn buf(&self) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.root(RESULT_BUF)) + } + + pub fn nu64(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_NU64)) + } + + pub fn str(&self) -> ScImmutableString { + ScImmutableString::new(self.proxy.root(RESULT_STR)) + } + + pub fn xu64(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_XU64)) + } +} + +#[derive(Clone)] +pub struct MutableGetVluResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetVluResults { + pub fn buf(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.root(RESULT_BUF)) + } + + pub fn nu64(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_NU64)) + } + + pub fn str(&self) -> ScMutableString { + ScMutableString::new(self.proxy.root(RESULT_STR)) + } + + pub fn xu64(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_XU64)) } } diff --git a/contracts/wasm/inccounter/src/state.rs b/contracts/wasm/inccounter/src/state.rs index 908f5c9aeb..193e18a445 100644 --- a/contracts/wasm/inccounter/src/state.rs +++ b/contracts/wasm/inccounter/src/state.rs @@ -9,41 +9,39 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableIncCounterState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableIncCounterState { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_COUNTER.get_key_id()) + ScImmutableInt64::new(self.proxy.root(STATE_COUNTER)) } pub fn num_repeats(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_NUM_REPEATS.get_key_id()) + ScImmutableInt64::new(self.proxy.root(STATE_NUM_REPEATS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableIncCounterState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableIncCounterState { pub fn as_immutable(&self) -> ImmutableIncCounterState { - ImmutableIncCounterState { id: self.id } + ImmutableIncCounterState { proxy: self.proxy.root("") } } pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_COUNTER.get_key_id()) + ScMutableInt64::new(self.proxy.root(STATE_COUNTER)) } pub fn num_repeats(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_NUM_REPEATS.get_key_id()) + ScMutableInt64::new(self.proxy.root(STATE_NUM_REPEATS)) } } diff --git a/contracts/wasm/inccounter/test/inccounter_bg.wasm b/contracts/wasm/inccounter/test/inccounter_bg.wasm index 8f2f783f82..a1883fafa0 100644 Binary files a/contracts/wasm/inccounter/test/inccounter_bg.wasm and b/contracts/wasm/inccounter/test/inccounter_bg.wasm differ diff --git a/contracts/wasm/inccounter/test/inccounter_test.go b/contracts/wasm/inccounter/test/inccounter_test.go index 0cae80b4ab..2046564ad6 100644 --- a/contracts/wasm/inccounter/test/inccounter_test.go +++ b/contracts/wasm/inccounter/test/inccounter_test.go @@ -4,12 +4,13 @@ package test import ( + "fmt" "testing" "time" "github.com/iotaledger/wasp/contracts/wasm/inccounter/go/inccounter" - "github.com/iotaledger/wasp/packages/vm/wasmhost" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmhost" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -32,7 +33,7 @@ func TestIncrementOnce(t *testing.T) { ctx := setupTest(t) increment := inccounter.ScFuncs.Increment(ctx) - increment.Func.TransferIotas(1).Post() + increment.Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 1) @@ -42,11 +43,11 @@ func TestIncrementTwice(t *testing.T) { ctx := setupTest(t) increment := inccounter.ScFuncs.Increment(ctx) - increment.Func.TransferIotas(1).Post() + increment.Func.Post() require.NoError(t, ctx.Err) increment = inccounter.ScFuncs.Increment(ctx) - increment.Func.TransferIotas(1).Post() + increment.Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 2) @@ -57,7 +58,7 @@ func TestIncrementRepeatThrice(t *testing.T) { repeatMany := inccounter.ScFuncs.RepeatMany(ctx) repeatMany.Params.NumRepeats().SetValue(3) - repeatMany.Func.TransferIotas(1).Post() + repeatMany.Func.Post() require.NoError(t, ctx.Err) require.True(t, ctx.WaitForPendingRequests(3)) @@ -69,7 +70,7 @@ func TestIncrementCallIncrement(t *testing.T) { ctx := setupTest(t) callIncrement := inccounter.ScFuncs.CallIncrement(ctx) - callIncrement.Func.TransferIotas(1).Post() + callIncrement.Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 2) @@ -79,7 +80,7 @@ func TestIncrementCallIncrementRecurse5x(t *testing.T) { ctx := setupTest(t) callIncrementRecurse5x := inccounter.ScFuncs.CallIncrementRecurse5x(ctx) - callIncrementRecurse5x.Func.TransferIotas(1).Post() + callIncrementRecurse5x.Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 6) @@ -89,7 +90,7 @@ func TestIncrementPostIncrement(t *testing.T) { ctx := setupTest(t) postIncrement := inccounter.ScFuncs.PostIncrement(ctx) - postIncrement.Func.TransferIotas(1).Post() + postIncrement.Func.Post() require.NoError(t, ctx.Err) require.True(t, ctx.WaitForPendingRequests(1)) @@ -101,7 +102,7 @@ func TestIncrementLocalStateInternalCall(t *testing.T) { ctx := setupTest(t) localStateInternalCall := inccounter.ScFuncs.LocalStateInternalCall(ctx) - localStateInternalCall.Func.TransferIotas(1).Post() + localStateInternalCall.Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 2) @@ -111,18 +112,18 @@ func TestIncrementLocalStateSandboxCall(t *testing.T) { ctx := setupTest(t) localStateSandboxCall := inccounter.ScFuncs.LocalStateSandboxCall(ctx) - localStateSandboxCall.Func.TransferIotas(1).Post() + localStateSandboxCall.Func.Post() require.NoError(t, ctx.Err) - if *wasmsolo.GoDebug { - // when using WasmGoVM the 3 posts are run only after - // the LocalStateMustIncrement has been set to true - checkStateCounter(t, ctx, 2) + if ctx.IsWasm { + // global var in wasm execution has no effect + checkStateCounter(t, ctx, nil) return } - // global var in wasm execution has no effect - checkStateCounter(t, ctx, nil) + // when using WasmGoVM the 3 posts are run only after + // the LocalStateMustIncrement has been set to true + checkStateCounter(t, ctx, 2) } func TestIncrementLocalStatePost(t *testing.T) { @@ -134,46 +135,86 @@ func TestIncrementLocalStatePost(t *testing.T) { require.True(t, ctx.WaitForPendingRequests(3)) - if *wasmsolo.GoDebug { - // when using WasmGoVM the 3 posts are run only after - // the LocalStateMustIncrement has been set to true - checkStateCounter(t, ctx, 3) + if ctx.IsWasm { + // global var in wasm execution has no effect + checkStateCounter(t, ctx, nil) return } - // global var in wasm execution has no effect - checkStateCounter(t, ctx, nil) + // when using WasmGoVM the 3 posts are run only after + // the LocalStateMustIncrement has been set to true + checkStateCounter(t, ctx, 3) } -func TestLeb128(t *testing.T) { - wasmhost.DisableWasmTimeout = true +func TestVliCodec(t *testing.T) { ctx := setupTest(t) + + f := inccounter.ScFuncs.TestVliCodec(ctx) + save := wasmhost.DisableWasmTimeout wasmhost.DisableWasmTimeout = false + f.Func.Post() + wasmhost.DisableWasmTimeout = save + require.NoError(t, ctx.Err) +} + +func TestVluCodec(t *testing.T) { + ctx := setupTest(t) - testLeb128 := inccounter.ScFuncs.TestLeb128(ctx) - testLeb128.Func.TransferIotas(1).Post() + f := inccounter.ScFuncs.TestVluCodec(ctx) + save := wasmhost.DisableWasmTimeout + wasmhost.DisableWasmTimeout = false + f.Func.Post() + wasmhost.DisableWasmTimeout = save require.NoError(t, ctx.Err) } +func TestVli(t *testing.T) { + ctx := setupTest(t) + + for i := int64(-200); i < 200; i++ { + vli := inccounter.ScFuncs.GetVli(ctx) + vli.Params.Ni64().SetValue(i) + vli.Func.Call() + require.NoError(t, ctx.Err) + fmt.Printf("Bytes: %s\n", vli.Results.Str().Value()) + require.Equal(t, i, vli.Results.Ni64().Value()) + require.Equal(t, i, vli.Results.Xi64().Value()) + } +} + +func TestVlu(t *testing.T) { + ctx := setupTest(t) + + for i := uint64(0); i < 400; i++ { + vli := inccounter.ScFuncs.GetVlu(ctx) + vli.Params.Nu64().SetValue(i) + vli.Func.Call() + require.NoError(t, ctx.Err) + fmt.Printf("Bytes: %s\n", vli.Results.Str().Value()) + require.Equal(t, i, vli.Results.Nu64().Value()) + require.Equal(t, i, vli.Results.Xu64().Value()) + } +} + func TestLoop(t *testing.T) { - if *wasmsolo.GoDebug || *wasmsolo.GoWasmEdge { + ctx := setupTest(t) + + if !ctx.IsWasm || *wasmsolo.UseWasmEdge { // no timeout possible because goroutines cannot be killed // or because there is no way to interrupt the Wasm code t.SkipNow() } - ctx := setupTest(t) - save := wasmhost.DisableWasmTimeout wasmhost.DisableWasmTimeout = false wasmhost.WasmTimeout = 1 * time.Second endlessLoop := inccounter.ScFuncs.EndlessLoop(ctx) - endlessLoop.Func.TransferIotas(1).Post() + endlessLoop.Func.Post() require.Error(t, ctx.Err) require.Contains(t, ctx.Err.Error(), "interrupt") wasmhost.DisableWasmTimeout = save - inccounter.ScFuncs.Increment(ctx).Func.TransferIotas(1).Post() + inccounter.ScFuncs.Increment(ctx).Func.Post() require.NoError(t, ctx.Err) checkStateCounter(t, ctx, 1) diff --git a/contracts/wasm/inccounter/ts/inccounter/consts.ts b/contracts/wasm/inccounter/ts/inccounter/consts.ts index ca522a8a58..237257288f 100644 --- a/contracts/wasm/inccounter/ts/inccounter/consts.ts +++ b/contracts/wasm/inccounter/ts/inccounter/consts.ts @@ -5,18 +5,26 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "inccounter"; export const ScDescription = ""; -export const HScName = new wasmlib.ScHname(0xaf2438e9); +export const HScName = new wasmtypes.ScHname(0xaf2438e9); export const ParamCounter = "counter"; export const ParamDelay = "delay"; export const ParamDummy = "dummy"; +export const ParamNi64 = "ni64"; +export const ParamNu64 = "nu64"; export const ParamNumRepeats = "numRepeats"; +export const ResultBuf = "buf"; export const ResultCounter = "counter"; +export const ResultNi64 = "ni64"; +export const ResultNu64 = "nu64"; +export const ResultStr = "str"; +export const ResultXi64 = "xi64"; +export const ResultXu64 = "xu64"; export const StateCounter = "counter"; export const StateNumRepeats = "numRepeats"; @@ -32,21 +40,27 @@ export const FuncLocalStatePost = "localStatePost"; export const FuncLocalStateSandboxCall = "localStateSandboxCall"; export const FuncPostIncrement = "postIncrement"; export const FuncRepeatMany = "repeatMany"; -export const FuncTestLeb128 = "testLeb128"; +export const FuncTestVliCodec = "testVliCodec"; +export const FuncTestVluCodec = "testVluCodec"; export const FuncWhenMustIncrement = "whenMustIncrement"; export const ViewGetCounter = "getCounter"; +export const ViewGetVli = "getVli"; +export const ViewGetVlu = "getVlu"; -export const HFuncCallIncrement = new wasmlib.ScHname(0xeb5dcacd); -export const HFuncCallIncrementRecurse5x = new wasmlib.ScHname(0x8749fbff); -export const HFuncEndlessLoop = new wasmlib.ScHname(0x365f0929); -export const HFuncIncrement = new wasmlib.ScHname(0xd351bd12); -export const HFuncIncrementWithDelay = new wasmlib.ScHname(0xa235bba7); -export const HFuncInit = new wasmlib.ScHname(0x1f44d644); -export const HFuncLocalStateInternalCall = new wasmlib.ScHname(0xecfc5d33); -export const HFuncLocalStatePost = new wasmlib.ScHname(0x3fd54d13); -export const HFuncLocalStateSandboxCall = new wasmlib.ScHname(0x7bd22c53); -export const HFuncPostIncrement = new wasmlib.ScHname(0x81c772f5); -export const HFuncRepeatMany = new wasmlib.ScHname(0x4ff450d3); -export const HFuncTestLeb128 = new wasmlib.ScHname(0xd8364cb9); -export const HFuncWhenMustIncrement = new wasmlib.ScHname(0xb4c3e7a6); -export const HViewGetCounter = new wasmlib.ScHname(0xb423e607); +export const HFuncCallIncrement = new wasmtypes.ScHname(0xeb5dcacd); +export const HFuncCallIncrementRecurse5x = new wasmtypes.ScHname(0x8749fbff); +export const HFuncEndlessLoop = new wasmtypes.ScHname(0x365f0929); +export const HFuncIncrement = new wasmtypes.ScHname(0xd351bd12); +export const HFuncIncrementWithDelay = new wasmtypes.ScHname(0xa235bba7); +export const HFuncInit = new wasmtypes.ScHname(0x1f44d644); +export const HFuncLocalStateInternalCall = new wasmtypes.ScHname(0xecfc5d33); +export const HFuncLocalStatePost = new wasmtypes.ScHname(0x3fd54d13); +export const HFuncLocalStateSandboxCall = new wasmtypes.ScHname(0x7bd22c53); +export const HFuncPostIncrement = new wasmtypes.ScHname(0x81c772f5); +export const HFuncRepeatMany = new wasmtypes.ScHname(0x4ff450d3); +export const HFuncTestVliCodec = new wasmtypes.ScHname(0xd5356012); +export const HFuncTestVluCodec = new wasmtypes.ScHname(0x9f7f63e6); +export const HFuncWhenMustIncrement = new wasmtypes.ScHname(0xb4c3e7a6); +export const HViewGetCounter = new wasmtypes.ScHname(0xb423e607); +export const HViewGetVli = new wasmtypes.ScHname(0x0ee16f89); +export const HViewGetVlu = new wasmtypes.ScHname(0x54d624e6); diff --git a/contracts/wasm/inccounter/ts/inccounter/contract.ts b/contracts/wasm/inccounter/ts/inccounter/contract.ts index 497a9052cc..27b919d2e5 100644 --- a/contracts/wasm/inccounter/ts/inccounter/contract.ts +++ b/contracts/wasm/inccounter/ts/inccounter/contract.ts @@ -13,7 +13,7 @@ export class CallIncrementCall { } export class CallIncrementContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class CallIncrementRecurse5xCall { @@ -21,7 +21,7 @@ export class CallIncrementRecurse5xCall { } export class CallIncrementRecurse5xContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class EndlessLoopCall { @@ -29,7 +29,7 @@ export class EndlessLoopCall { } export class EndlessLoopContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class IncrementCall { @@ -37,27 +37,27 @@ export class IncrementCall { } export class IncrementContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class IncrementWithDelayCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncIncrementWithDelay); - params: sc.MutableIncrementWithDelayParams = new sc.MutableIncrementWithDelayParams(); + params: sc.MutableIncrementWithDelayParams = new sc.MutableIncrementWithDelayParams(wasmlib.ScView.nilProxy); } export class IncrementWithDelayContext { - params: sc.ImmutableIncrementWithDelayParams = new sc.ImmutableIncrementWithDelayParams(); - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + params: sc.ImmutableIncrementWithDelayParams = new sc.ImmutableIncrementWithDelayParams(wasmlib.paramsProxy()); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); - params: sc.MutableInitParams = new sc.MutableInitParams(); + params: sc.MutableInitParams = new sc.MutableInitParams(wasmlib.ScView.nilProxy); } export class InitContext { - params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + params: sc.ImmutableInitParams = new sc.ImmutableInitParams(wasmlib.paramsProxy()); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class LocalStateInternalCallCall { @@ -65,7 +65,7 @@ export class LocalStateInternalCallCall { } export class LocalStateInternalCallContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class LocalStatePostCall { @@ -73,7 +73,7 @@ export class LocalStatePostCall { } export class LocalStatePostContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class LocalStateSandboxCallCall { @@ -81,7 +81,7 @@ export class LocalStateSandboxCallCall { } export class LocalStateSandboxCallContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class PostIncrementCall { @@ -89,111 +89,161 @@ export class PostIncrementCall { } export class PostIncrementContext { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class RepeatManyCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRepeatMany); - params: sc.MutableRepeatManyParams = new sc.MutableRepeatManyParams(); + params: sc.MutableRepeatManyParams = new sc.MutableRepeatManyParams(wasmlib.ScView.nilProxy); } export class RepeatManyContext { - params: sc.ImmutableRepeatManyParams = new sc.ImmutableRepeatManyParams(); - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + params: sc.ImmutableRepeatManyParams = new sc.ImmutableRepeatManyParams(wasmlib.paramsProxy()); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } -export class TestLeb128Call { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestLeb128); +export class TestVliCodecCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestVliCodec); } -export class TestLeb128Context { - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); +export class TestVliCodecContext { + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); +} + +export class TestVluCodecCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestVluCodec); +} + +export class TestVluCodecContext { + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class WhenMustIncrementCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWhenMustIncrement); - params: sc.MutableWhenMustIncrementParams = new sc.MutableWhenMustIncrementParams(); + params: sc.MutableWhenMustIncrementParams = new sc.MutableWhenMustIncrementParams(wasmlib.ScView.nilProxy); } export class WhenMustIncrementContext { - params: sc.ImmutableWhenMustIncrementParams = new sc.ImmutableWhenMustIncrementParams(); - state: sc.MutableIncCounterState = new sc.MutableIncCounterState(); + params: sc.ImmutableWhenMustIncrementParams = new sc.ImmutableWhenMustIncrementParams(wasmlib.paramsProxy()); + state: sc.MutableIncCounterState = new sc.MutableIncCounterState(wasmlib.ScState.proxy()); } export class GetCounterCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetCounter); - results: sc.ImmutableGetCounterResults = new sc.ImmutableGetCounterResults(); + results: sc.ImmutableGetCounterResults = new sc.ImmutableGetCounterResults(wasmlib.ScView.nilProxy); } export class GetCounterContext { - results: sc.MutableGetCounterResults = new sc.MutableGetCounterResults(); - state: sc.ImmutableIncCounterState = new sc.ImmutableIncCounterState(); + results: sc.MutableGetCounterResults = new sc.MutableGetCounterResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableIncCounterState = new sc.ImmutableIncCounterState(wasmlib.ScState.proxy()); +} + +export class GetVliCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetVli); + params: sc.MutableGetVliParams = new sc.MutableGetVliParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetVliResults = new sc.ImmutableGetVliResults(wasmlib.ScView.nilProxy); +} + +export class GetVliContext { + params: sc.ImmutableGetVliParams = new sc.ImmutableGetVliParams(wasmlib.paramsProxy()); + results: sc.MutableGetVliResults = new sc.MutableGetVliResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableIncCounterState = new sc.ImmutableIncCounterState(wasmlib.ScState.proxy()); +} + +export class GetVluCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetVlu); + params: sc.MutableGetVluParams = new sc.MutableGetVluParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetVluResults = new sc.ImmutableGetVluResults(wasmlib.ScView.nilProxy); +} + +export class GetVluContext { + params: sc.ImmutableGetVluParams = new sc.ImmutableGetVluParams(wasmlib.paramsProxy()); + results: sc.MutableGetVluResults = new sc.MutableGetVluResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableIncCounterState = new sc.ImmutableIncCounterState(wasmlib.ScState.proxy()); } export class ScFuncs { - static callIncrement(ctx: wasmlib.ScFuncCallContext): CallIncrementCall { - return new CallIncrementCall(); - } - - static callIncrementRecurse5x(ctx: wasmlib.ScFuncCallContext): CallIncrementRecurse5xCall { - return new CallIncrementRecurse5xCall(); - } - - static endlessLoop(ctx: wasmlib.ScFuncCallContext): EndlessLoopCall { - return new EndlessLoopCall(); - } - - static increment(ctx: wasmlib.ScFuncCallContext): IncrementCall { - return new IncrementCall(); - } - - static incrementWithDelay(ctx: wasmlib.ScFuncCallContext): IncrementWithDelayCall { - let f = new IncrementWithDelayCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static init(ctx: wasmlib.ScFuncCallContext): InitCall { - let f = new InitCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static localStateInternalCall(ctx: wasmlib.ScFuncCallContext): LocalStateInternalCallCall { - return new LocalStateInternalCallCall(); - } - - static localStatePost(ctx: wasmlib.ScFuncCallContext): LocalStatePostCall { - return new LocalStatePostCall(); - } - - static localStateSandboxCall(ctx: wasmlib.ScFuncCallContext): LocalStateSandboxCallCall { - return new LocalStateSandboxCallCall(); - } - - static postIncrement(ctx: wasmlib.ScFuncCallContext): PostIncrementCall { - return new PostIncrementCall(); - } - - static repeatMany(ctx: wasmlib.ScFuncCallContext): RepeatManyCall { - let f = new RepeatManyCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static testLeb128(ctx: wasmlib.ScFuncCallContext): TestLeb128Call { - return new TestLeb128Call(); - } - - static whenMustIncrement(ctx: wasmlib.ScFuncCallContext): WhenMustIncrementCall { - let f = new WhenMustIncrementCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static getCounter(ctx: wasmlib.ScViewCallContext): GetCounterCall { - let f = new GetCounterCall(); - f.func.setPtrs(null, f.results); - return f; - } + static callIncrement(_ctx: wasmlib.ScFuncCallContext): CallIncrementCall { + return new CallIncrementCall(); + } + + static callIncrementRecurse5x(_ctx: wasmlib.ScFuncCallContext): CallIncrementRecurse5xCall { + return new CallIncrementRecurse5xCall(); + } + + static endlessLoop(_ctx: wasmlib.ScFuncCallContext): EndlessLoopCall { + return new EndlessLoopCall(); + } + + static increment(_ctx: wasmlib.ScFuncCallContext): IncrementCall { + return new IncrementCall(); + } + + static incrementWithDelay(_ctx: wasmlib.ScFuncCallContext): IncrementWithDelayCall { + const f = new IncrementWithDelayCall(); + f.params = new sc.MutableIncrementWithDelayParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static init(_ctx: wasmlib.ScFuncCallContext): InitCall { + const f = new InitCall(); + f.params = new sc.MutableInitParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static localStateInternalCall(_ctx: wasmlib.ScFuncCallContext): LocalStateInternalCallCall { + return new LocalStateInternalCallCall(); + } + + static localStatePost(_ctx: wasmlib.ScFuncCallContext): LocalStatePostCall { + return new LocalStatePostCall(); + } + + static localStateSandboxCall(_ctx: wasmlib.ScFuncCallContext): LocalStateSandboxCallCall { + return new LocalStateSandboxCallCall(); + } + + static postIncrement(_ctx: wasmlib.ScFuncCallContext): PostIncrementCall { + return new PostIncrementCall(); + } + + static repeatMany(_ctx: wasmlib.ScFuncCallContext): RepeatManyCall { + const f = new RepeatManyCall(); + f.params = new sc.MutableRepeatManyParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static testVliCodec(_ctx: wasmlib.ScFuncCallContext): TestVliCodecCall { + return new TestVliCodecCall(); + } + + static testVluCodec(_ctx: wasmlib.ScFuncCallContext): TestVluCodecCall { + return new TestVluCodecCall(); + } + + static whenMustIncrement(_ctx: wasmlib.ScFuncCallContext): WhenMustIncrementCall { + const f = new WhenMustIncrementCall(); + f.params = new sc.MutableWhenMustIncrementParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static getCounter(_ctx: wasmlib.ScViewCallContext): GetCounterCall { + const f = new GetCounterCall(); + f.results = new sc.ImmutableGetCounterResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getVli(_ctx: wasmlib.ScViewCallContext): GetVliCall { + const f = new GetVliCall(); + f.params = new sc.MutableGetVliParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetVliResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getVlu(_ctx: wasmlib.ScViewCallContext): GetVluCall { + const f = new GetVluCall(); + f.params = new sc.MutableGetVluParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetVluResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/inccounter/ts/inccounter/inccounter.ts b/contracts/wasm/inccounter/ts/inccounter/inccounter.ts index eb1d9a4766..d576686478 100644 --- a/contracts/wasm/inccounter/ts/inccounter/inccounter.ts +++ b/contracts/wasm/inccounter/ts/inccounter/inccounter.ts @@ -2,10 +2,20 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; +const hex = "0123456789abcdef"; + let localStateMustIncrement: boolean = false; +export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { + if (f.params.counter().exists()) { + let counter = f.params.counter().value(); + f.state.counter().setValue(counter); + } +} + export function funcCallIncrement(ctx: wasmlib.ScFuncContext, f: sc.CallIncrementContext): void { let counter = f.state.counter(); let value = counter.value(); @@ -37,14 +47,7 @@ export function funcIncrement(ctx: wasmlib.ScFuncContext, f: sc.IncrementContext export function funcIncrementWithDelay(ctx: wasmlib.ScFuncContext, f: sc.IncrementWithDelayContext): void { let delay = f.params.delay().value(); let inc = sc.ScFuncs.callIncrement(ctx); - inc.func.delay(delay).transferIotas(1).post(); -} - -export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { - if (f.params.counter().exists()) { - let counter = f.params.counter().value(); - f.state.counter().setValue(counter); - } + inc.func.delay(delay).post(); } export function funcLocalStateInternalCall(ctx: wasmlib.ScFuncContext, f: sc.LocalStateInternalCallContext): void { @@ -80,7 +83,7 @@ export function funcPostIncrement(ctx: wasmlib.ScFuncContext, f: sc.PostIncremen let value = counter.value(); counter.setValue(value + 1); if (value == 0) { - sc.ScFuncs.increment(ctx).func.transferIotas(1).post(); + sc.ScFuncs.increment(ctx).func.post(); } } @@ -97,40 +100,77 @@ export function funcRepeatMany(ctx: wasmlib.ScFuncContext, f: sc.RepeatManyConte } } stateRepeats.setValue(repeats - 1); - sc.ScFuncs.repeatMany(ctx).func.transferIotas(1).post(); + sc.ScFuncs.repeatMany(ctx).func.post(); } -let hex = "0123456789abcdef"; +export function funcTestVliCodec(ctx: wasmlib.ScFuncContext, f: sc.TestVliCodecContext): void { + for (let i: i64 = -1600; i < 1600; i++) { + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.int64Encode(enc, i); + let buf = enc.buf(); + // let txt = i.toString() + " -"; + // for (let j = 0; j < buf.length; j++) { + // let b = buf[j]; + // txt += " " + hex.charAt((b >> 4) & 0x0f) + hex.charAt(b & 0x0f); + // } + let dec = new wasmtypes.WasmDecoder(buf); + let v = wasmtypes.int64Decode(dec); + // txt += " - " + v.toString(); + // ctx.log(txt); + ctx.require(i == v, "coder value mismatch") + } -export function funcTestLeb128(ctx: wasmlib.ScFuncContext, f: sc.TestLeb128Context): void { - for (let i: i64 = -1000000; i < 1000000; i++) { - let d = new wasmlib.BytesEncoder(); - d.int64(i); + vliSave(ctx, "v-129", -129); + vliSave(ctx, "v-128", -128); + vliSave(ctx, "v-127", -127); + vliSave(ctx, "v-126", -126); + vliSave(ctx, "v-65", -65); + vliSave(ctx, "v-64", -64); + vliSave(ctx, "v-63", -63); + vliSave(ctx, "v-62", -62); + vliSave(ctx, "v-2", -2); + vliSave(ctx, "v-1", -1); + vliSave(ctx, "v 0", 0); + vliSave(ctx, "v+1", 1); + vliSave(ctx, "v+2", 2); + vliSave(ctx, "v+62", 62); + vliSave(ctx, "v+63", 63); + vliSave(ctx, "v+64", 64); + vliSave(ctx, "v+65", 65); + vliSave(ctx, "v+126", 126); + vliSave(ctx, "v+127", 127); + vliSave(ctx, "v+128", 128); + vliSave(ctx, "v+129", 129); +} + +export function funcTestVluCodec(ctx: wasmlib.ScFuncContext, f: sc.TestVluCodecContext): void { + for (let i: u64 = 0; i < 3200; i++) { + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint64Encode(enc, i); + let buf = enc.buf(); // let txt = i.toString() + " -"; - // for (let j = 0; j < d.buf.length; j++) { - // let b = d.buf[j]; - // txt += " " + hex[(b >> 4) & 0x0f] + hex[d.buf[j] & 0x0f]; + // for (let j = 0; j < buf.length; j++) { + // let b = buf[j]; + // txt += " " + hex.charAt((b >> 4) & 0x0f) + hex.charAt(b & 0x0f); // } - let e = new wasmlib.BytesDecoder(d.buf); - let v = e.int64(); + let dec = new wasmtypes.WasmDecoder(buf); + let v = wasmtypes.uint64Decode(dec); // txt += " - " + v.toString(); // ctx.log(txt); ctx.require(i == v, "coder value mismatch") } - leb128Save(ctx, "v-1", -1); - leb128Save(ctx, "v-2", -2); - leb128Save(ctx, "v-126", -126); - leb128Save(ctx, "v-127", -127); - leb128Save(ctx, "v-128", -128); - leb128Save(ctx, "v-129", -129); - leb128Save(ctx, "v0", 0); - leb128Save(ctx, "v+1", 1); - leb128Save(ctx, "v+2", 2); - leb128Save(ctx, "v+126", 126); - leb128Save(ctx, "v+127", 127); - leb128Save(ctx, "v+128", 128); - leb128Save(ctx, "v+129", 129); + vluSave(ctx, "v 0", 0); + vluSave(ctx, "v+1", 1); + vluSave(ctx, "v+2", 2); + vluSave(ctx, "v+62", 62); + vluSave(ctx, "v+63", 63); + vluSave(ctx, "v+64", 64); + vluSave(ctx, "v+65", 65); + vluSave(ctx, "v+126", 126); + vluSave(ctx, "v+127", 127); + vluSave(ctx, "v+128", 128); + vluSave(ctx, "v+129", 129); } export function funcWhenMustIncrement(ctx: wasmlib.ScFuncContext, f: sc.WhenMustIncrementContext): void { @@ -146,26 +186,85 @@ export function viewGetCounter(ctx: wasmlib.ScViewContext, f: sc.GetCounterConte } } -function leb128Save(ctx: wasmlib.ScFuncContext, name: string, value: i64): void { - let encoder = new wasmlib.BytesEncoder(); - encoder.int64(value); - let spot = ctx.state().getBytes(wasmlib.Key32.fromString(name)); - spot.setValue(encoder.data()); +export function viewGetVli(ctx: wasmlib.ScViewContext, f: sc.GetVliContext): void { + let enc = new wasmtypes.WasmEncoder(); + let n = f.params.ni64().value(); + wasmtypes.int64Encode(enc, n); + let buf = enc.buf(); + let dec = new wasmtypes.WasmDecoder(buf); + let x = wasmtypes.int64Decode(dec); - let bytes = spot.value(); - let decoder = new wasmlib.BytesDecoder(bytes); - let retrieved = decoder.int64(); - if (retrieved != value) { - ctx.log(name.toString() + " in : " + value.toString()); - ctx.log(name.toString() + " out: " + retrieved.toString()); + let str = n.toString() + " -"; + for (let j = 0; j < buf.length; j++) { + let b = buf[j]; + str += " " + hex.charAt((b >> 4) & 0x0f) + hex.charAt(b & 0x0f); + } + str += " - " + x.toString(); + + f.results.ni64().setValue(n); + f.results.xi64().setValue(x); + f.results.str().setValue(str); + f.results.buf().setValue(buf); +} + +export function viewGetVlu(ctx: wasmlib.ScViewContext, f: sc.GetVluContext): void { + let enc = new wasmtypes.WasmEncoder(); + let n = f.params.nu64().value(); + wasmtypes.uint64Encode(enc, n); + let buf = enc.buf(); + let dec = new wasmtypes.WasmDecoder(buf); + let x = wasmtypes.uint64Decode(dec); + + let str = n.toString() + " -"; + for (let j = 0; j < buf.length; j++) { + let b = buf[j]; + str += " " + hex.charAt((b >> 4) & 0x0f) + hex.charAt(b & 0x0f); } + str += " - " + x.toString(); + + f.results.nu64().setValue(n); + f.results.xu64().setValue(x); + f.results.str().setValue(str); + f.results.buf().setValue(buf); } +//////////////////////////////// util funcs \\\\\\\\\\\\\\\\\\\\\\\\\\\\\ + function localStatePost(ctx: wasmlib.ScFuncContext, nr: i64): void { //note: we add a dummy parameter here to prevent "duplicate outputs not allowed" error let f = sc.ScFuncs.whenMustIncrement(ctx); f.params.dummy().setValue(nr); - f.func.transferIotas(1).post(); + f.func.post(); +} + +function vliSave(ctx: wasmlib.ScFuncContext, name: string, value: i64): void { + const enc = new wasmtypes.WasmEncoder(); + const state = ctx.rawState(); + const key = wasmtypes.stringToBytes(name); + state.set(key, enc.vliEncode(value).buf()); + + const buf = state.get(key); + const dec = new wasmtypes.WasmDecoder(buf); + const val = dec.vliDecode(64); + if (val != value) { + ctx.log(name.toString() + " in : " + value.toString()); + ctx.log(name.toString() + " out: " + val.toString()); + } +} + +function vluSave(ctx: wasmlib.ScFuncContext, name: string, value: u64): void { + const enc = new wasmtypes.WasmEncoder(); + const state = ctx.rawState(); + const key = wasmtypes.stringToBytes(name); + state.set(key, enc.vluEncode(value).buf()); + + const buf = state.get(key); + const dec = new wasmtypes.WasmDecoder(buf); + const val = dec.vluDecode(64); + if (val != value) { + ctx.log(name.toString() + " in : " + value.toString()); + ctx.log(name.toString() + " out: " + val.toString()); + } } function whenMustIncrementState(ctx: wasmlib.ScFuncContext, state: sc.MutableIncCounterState): void { diff --git a/contracts/wasm/inccounter/ts/inccounter/index.ts b/contracts/wasm/inccounter/ts/inccounter/index.ts index f944f6c574..96f957fe81 100644 --- a/contracts/wasm/inccounter/ts/inccounter/index.ts +++ b/contracts/wasm/inccounter/ts/inccounter/index.ts @@ -9,7 +9,6 @@ export * from "./inccounter"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/inccounter/ts/inccounter/keys.ts b/contracts/wasm/inccounter/ts/inccounter/keys.ts deleted file mode 100644 index 94e03bd1c1..0000000000 --- a/contracts/wasm/inccounter/ts/inccounter/keys.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamCounter = 0; -export const IdxParamDelay = 1; -export const IdxParamDummy = 2; -export const IdxParamNumRepeats = 3; - -export const IdxResultCounter = 4; - -export const IdxStateCounter = 5; -export const IdxStateNumRepeats = 6; - -export let keyMap: string[] = [ - sc.ParamCounter, - sc.ParamDelay, - sc.ParamDummy, - sc.ParamNumRepeats, - sc.ResultCounter, - sc.StateCounter, - sc.StateNumRepeats, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/inccounter/ts/inccounter/lib.ts b/contracts/wasm/inccounter/ts/inccounter/lib.ts index 59d72dbea3..359ce25fd2 100644 --- a/contracts/wasm/inccounter/ts/inccounter/lib.ts +++ b/contracts/wasm/inccounter/ts/inccounter/lib.ts @@ -8,36 +8,60 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncCallIncrement, + sc.FuncCallIncrementRecurse5x, + sc.FuncEndlessLoop, + sc.FuncIncrement, + sc.FuncIncrementWithDelay, + sc.FuncInit, + sc.FuncLocalStateInternalCall, + sc.FuncLocalStatePost, + sc.FuncLocalStateSandboxCall, + sc.FuncPostIncrement, + sc.FuncRepeatMany, + sc.FuncTestVliCodec, + sc.FuncTestVluCodec, + sc.FuncWhenMustIncrement, + sc.ViewGetCounter, + sc.ViewGetVli, + sc.ViewGetVlu, + ], + funcs: [ + funcCallIncrementThunk, + funcCallIncrementRecurse5xThunk, + funcEndlessLoopThunk, + funcIncrementThunk, + funcIncrementWithDelayThunk, + funcInitThunk, + funcLocalStateInternalCallThunk, + funcLocalStatePostThunk, + funcLocalStateSandboxCallThunk, + funcPostIncrementThunk, + funcRepeatManyThunk, + funcTestVliCodecThunk, + funcTestVluCodecThunk, + funcWhenMustIncrementThunk, + ], + views: [ + viewGetCounterThunk, + viewGetVliThunk, + viewGetVluThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncCallIncrement, funcCallIncrementThunk); - exports.addFunc(sc.FuncCallIncrementRecurse5x, funcCallIncrementRecurse5xThunk); - exports.addFunc(sc.FuncEndlessLoop, funcEndlessLoopThunk); - exports.addFunc(sc.FuncIncrement, funcIncrementThunk); - exports.addFunc(sc.FuncIncrementWithDelay, funcIncrementWithDelayThunk); - exports.addFunc(sc.FuncInit, funcInitThunk); - exports.addFunc(sc.FuncLocalStateInternalCall, funcLocalStateInternalCallThunk); - exports.addFunc(sc.FuncLocalStatePost, funcLocalStatePostThunk); - exports.addFunc(sc.FuncLocalStateSandboxCall, funcLocalStateSandboxCallThunk); - exports.addFunc(sc.FuncPostIncrement, funcPostIncrementThunk); - exports.addFunc(sc.FuncRepeatMany, funcRepeatManyThunk); - exports.addFunc(sc.FuncTestLeb128, funcTestLeb128Thunk); - exports.addFunc(sc.FuncWhenMustIncrement, funcWhenMustIncrementThunk); - exports.addView(sc.ViewGetCounter, viewGetCounterThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcCallIncrementThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcCallIncrement"); let f = new sc.CallIncrementContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcCallIncrement(ctx, f); ctx.log("inccounter.funcCallIncrement ok"); } @@ -45,7 +69,6 @@ function funcCallIncrementThunk(ctx: wasmlib.ScFuncContext): void { function funcCallIncrementRecurse5xThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcCallIncrementRecurse5x"); let f = new sc.CallIncrementRecurse5xContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcCallIncrementRecurse5x(ctx, f); ctx.log("inccounter.funcCallIncrementRecurse5x ok"); } @@ -53,7 +76,6 @@ function funcCallIncrementRecurse5xThunk(ctx: wasmlib.ScFuncContext): void { function funcEndlessLoopThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcEndlessLoop"); let f = new sc.EndlessLoopContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcEndlessLoop(ctx, f); ctx.log("inccounter.funcEndlessLoop ok"); } @@ -61,7 +83,6 @@ function funcEndlessLoopThunk(ctx: wasmlib.ScFuncContext): void { function funcIncrementThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcIncrement"); let f = new sc.IncrementContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcIncrement(ctx, f); ctx.log("inccounter.funcIncrement ok"); } @@ -69,8 +90,6 @@ function funcIncrementThunk(ctx: wasmlib.ScFuncContext): void { function funcIncrementWithDelayThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcIncrementWithDelay"); let f = new sc.IncrementWithDelayContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.delay().exists(), "missing mandatory delay"); sc.funcIncrementWithDelay(ctx, f); ctx.log("inccounter.funcIncrementWithDelay ok"); @@ -79,8 +98,6 @@ function funcIncrementWithDelayThunk(ctx: wasmlib.ScFuncContext): void { function funcInitThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcInit"); let f = new sc.InitContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcInit(ctx, f); ctx.log("inccounter.funcInit ok"); } @@ -88,7 +105,6 @@ function funcInitThunk(ctx: wasmlib.ScFuncContext): void { function funcLocalStateInternalCallThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcLocalStateInternalCall"); let f = new sc.LocalStateInternalCallContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcLocalStateInternalCall(ctx, f); ctx.log("inccounter.funcLocalStateInternalCall ok"); } @@ -96,7 +112,6 @@ function funcLocalStateInternalCallThunk(ctx: wasmlib.ScFuncContext): void { function funcLocalStatePostThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcLocalStatePost"); let f = new sc.LocalStatePostContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcLocalStatePost(ctx, f); ctx.log("inccounter.funcLocalStatePost ok"); } @@ -104,7 +119,6 @@ function funcLocalStatePostThunk(ctx: wasmlib.ScFuncContext): void { function funcLocalStateSandboxCallThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcLocalStateSandboxCall"); let f = new sc.LocalStateSandboxCallContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcLocalStateSandboxCall(ctx, f); ctx.log("inccounter.funcLocalStateSandboxCall ok"); } @@ -112,7 +126,6 @@ function funcLocalStateSandboxCallThunk(ctx: wasmlib.ScFuncContext): void { function funcPostIncrementThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcPostIncrement"); let f = new sc.PostIncrementContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcPostIncrement(ctx, f); ctx.log("inccounter.funcPostIncrement ok"); } @@ -120,25 +133,27 @@ function funcPostIncrementThunk(ctx: wasmlib.ScFuncContext): void { function funcRepeatManyThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcRepeatMany"); let f = new sc.RepeatManyContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcRepeatMany(ctx, f); ctx.log("inccounter.funcRepeatMany ok"); } -function funcTestLeb128Thunk(ctx: wasmlib.ScFuncContext): void { - ctx.log("inccounter.funcTestLeb128"); - let f = new sc.TestLeb128Context(); - f.state.mapID = wasmlib.OBJ_ID_STATE; - sc.funcTestLeb128(ctx, f); - ctx.log("inccounter.funcTestLeb128 ok"); +function funcTestVliCodecThunk(ctx: wasmlib.ScFuncContext): void { + ctx.log("inccounter.funcTestVliCodec"); + let f = new sc.TestVliCodecContext(); + sc.funcTestVliCodec(ctx, f); + ctx.log("inccounter.funcTestVliCodec ok"); +} + +function funcTestVluCodecThunk(ctx: wasmlib.ScFuncContext): void { + ctx.log("inccounter.funcTestVluCodec"); + let f = new sc.TestVluCodecContext(); + sc.funcTestVluCodec(ctx, f); + ctx.log("inccounter.funcTestVluCodec ok"); } function funcWhenMustIncrementThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("inccounter.funcWhenMustIncrement"); let f = new sc.WhenMustIncrementContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcWhenMustIncrement(ctx, f); ctx.log("inccounter.funcWhenMustIncrement ok"); } @@ -146,8 +161,31 @@ function funcWhenMustIncrementThunk(ctx: wasmlib.ScFuncContext): void { function viewGetCounterThunk(ctx: wasmlib.ScViewContext): void { ctx.log("inccounter.viewGetCounter"); let f = new sc.GetCounterContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetCounterResults(results.asProxy()); sc.viewGetCounter(ctx, f); + ctx.results(results); ctx.log("inccounter.viewGetCounter ok"); } + +function viewGetVliThunk(ctx: wasmlib.ScViewContext): void { + ctx.log("inccounter.viewGetVli"); + let f = new sc.GetVliContext(); + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetVliResults(results.asProxy()); + ctx.require(f.params.ni64().exists(), "missing mandatory ni64"); + sc.viewGetVli(ctx, f); + ctx.results(results); + ctx.log("inccounter.viewGetVli ok"); +} + +function viewGetVluThunk(ctx: wasmlib.ScViewContext): void { + ctx.log("inccounter.viewGetVlu"); + let f = new sc.GetVluContext(); + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetVluResults(results.asProxy()); + ctx.require(f.params.nu64().exists(), "missing mandatory nu64"); + sc.viewGetVlu(ctx, f); + ctx.results(results); + ctx.log("inccounter.viewGetVlu ok"); +} diff --git a/contracts/wasm/inccounter/ts/inccounter/params.ts b/contracts/wasm/inccounter/ts/inccounter/params.ts index b12f5f1fa0..311792e40d 100644 --- a/contracts/wasm/inccounter/ts/inccounter/params.ts +++ b/contracts/wasm/inccounter/ts/inccounter/params.ts @@ -5,53 +5,77 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableIncrementWithDelayParams extends wasmlib.ScMapID { - delay(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamDelay)); +export class ImmutableIncrementWithDelayParams extends wasmtypes.ScProxy { + delay(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamDelay)); } } -export class MutableIncrementWithDelayParams extends wasmlib.ScMapID { - delay(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamDelay)); +export class MutableIncrementWithDelayParams extends wasmtypes.ScProxy { + delay(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamDelay)); } } -export class ImmutableInitParams extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, sc.idxMap[sc.IdxParamCounter]); +export class ImmutableInitParams extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamCounter)); } } -export class MutableInitParams extends wasmlib.ScMapID { - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, sc.idxMap[sc.IdxParamCounter]); +export class MutableInitParams extends wasmtypes.ScProxy { + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamCounter)); } } -export class ImmutableRepeatManyParams extends wasmlib.ScMapID { - numRepeats(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNumRepeats)); +export class ImmutableRepeatManyParams extends wasmtypes.ScProxy { + numRepeats(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamNumRepeats)); } } -export class MutableRepeatManyParams extends wasmlib.ScMapID { - numRepeats(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamNumRepeats)); +export class MutableRepeatManyParams extends wasmtypes.ScProxy { + numRepeats(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamNumRepeats)); } } -export class ImmutableWhenMustIncrementParams extends wasmlib.ScMapID { - dummy(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamDummy)); +export class ImmutableWhenMustIncrementParams extends wasmtypes.ScProxy { + dummy(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamDummy)); } } -export class MutableWhenMustIncrementParams extends wasmlib.ScMapID { - dummy(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamDummy)); +export class MutableWhenMustIncrementParams extends wasmtypes.ScProxy { + dummy(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamDummy)); + } +} + +export class ImmutableGetVliParams extends wasmtypes.ScProxy { + ni64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamNi64)); + } +} + +export class MutableGetVliParams extends wasmtypes.ScProxy { + ni64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamNi64)); + } +} + +export class ImmutableGetVluParams extends wasmtypes.ScProxy { + nu64(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamNu64)); + } +} + +export class MutableGetVluParams extends wasmtypes.ScProxy { + nu64(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamNu64)); } } diff --git a/contracts/wasm/inccounter/ts/inccounter/results.ts b/contracts/wasm/inccounter/ts/inccounter/results.ts index dbb6323dcd..b582b65f89 100644 --- a/contracts/wasm/inccounter/ts/inccounter/results.ts +++ b/contracts/wasm/inccounter/ts/inccounter/results.ts @@ -5,17 +5,89 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableGetCounterResults extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCounter)); +export class ImmutableGetCounterResults extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultCounter)); } } -export class MutableGetCounterResults extends wasmlib.ScMapID { - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCounter)); +export class MutableGetCounterResults extends wasmtypes.ScProxy { + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultCounter)); + } +} + +export class ImmutableGetVliResults extends wasmtypes.ScProxy { + buf(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultBuf)); + } + + ni64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultNi64)); + } + + str(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultStr)); + } + + xi64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultXi64)); + } +} + +export class MutableGetVliResults extends wasmtypes.ScProxy { + buf(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultBuf)); + } + + ni64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultNi64)); + } + + str(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultStr)); + } + + xi64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultXi64)); + } +} + +export class ImmutableGetVluResults extends wasmtypes.ScProxy { + buf(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultBuf)); + } + + nu64(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultNu64)); + } + + str(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultStr)); + } + + xu64(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultXu64)); + } +} + +export class MutableGetVluResults extends wasmtypes.ScProxy { + buf(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultBuf)); + } + + nu64(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultNu64)); + } + + str(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultStr)); + } + + xu64(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultXu64)); } } diff --git a/contracts/wasm/inccounter/ts/inccounter/state.ts b/contracts/wasm/inccounter/ts/inccounter/state.ts index e121f2c893..051f301d6e 100644 --- a/contracts/wasm/inccounter/ts/inccounter/state.ts +++ b/contracts/wasm/inccounter/ts/inccounter/state.ts @@ -5,31 +5,29 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableIncCounterState extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateCounter)); +export class ImmutableIncCounterState extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.StateCounter)); } - numRepeats(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateNumRepeats)); + numRepeats(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.StateNumRepeats)); } } -export class MutableIncCounterState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableIncCounterState { - const imm = new sc.ImmutableIncCounterState(); - imm.mapID = this.mapID; - return imm; +export class MutableIncCounterState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableIncCounterState { + return new sc.ImmutableIncCounterState(this.proxy); } - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateCounter)); + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.StateCounter)); } - numRepeats(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateNumRepeats)); + numRepeats(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.StateNumRepeats)); } } diff --git a/contracts/wasm/testcore/Cargo.toml b/contracts/wasm/testcore/Cargo.toml index 05b874a9e1..616bd7fdc8 100644 --- a/contracts/wasm/testcore/Cargo.toml +++ b/contracts/wasm/testcore/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/testcore/go/main.go b/contracts/wasm/testcore/go/main.go index 9d0d44a9eb..3fd933caa2 100644 --- a/contracts/wasm/testcore/go/main.go +++ b/contracts/wasm/testcore/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + testcore.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - testcore.OnLoad() + testcore.OnLoad(-1) } diff --git a/contracts/wasm/testcore/go/testcore/consts.go b/contracts/wasm/testcore/go/testcore/consts.go index d1e82b1b9c..47241b51a8 100644 --- a/contracts/wasm/testcore/go/testcore/consts.go +++ b/contracts/wasm/testcore/go/testcore/consts.go @@ -7,12 +7,12 @@ package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "testcore" ScDescription = "Core test for ISCP wasmlib Rust/Wasm library" - HScName = wasmlib.ScHname(0x370d33ad) + HScName = wasmtypes.ScHname(0x370d33ad) ) const ( @@ -95,36 +95,36 @@ const ( ) const ( - HFuncCallOnChain = wasmlib.ScHname(0x95a3d123) - HFuncCheckContextFromFullEP = wasmlib.ScHname(0xa56c24ba) - HFuncDoNothing = wasmlib.ScHname(0xdda4a6de) - HFuncGetMintedSupply = wasmlib.ScHname(0x0c2d113c) - HFuncIncCounter = wasmlib.ScHname(0x7b287419) - HFuncInit = wasmlib.ScHname(0x1f44d644) - HFuncPassTypesFull = wasmlib.ScHname(0x733ea0ea) - HFuncRunRecursion = wasmlib.ScHname(0x833425fd) - HFuncSendToAddress = wasmlib.ScHname(0x63ce4634) - HFuncSetInt = wasmlib.ScHname(0x62056f74) - HFuncSpawn = wasmlib.ScHname(0xec929d12) - HFuncTestBlockContext1 = wasmlib.ScHname(0x796d4136) - HFuncTestBlockContext2 = wasmlib.ScHname(0x758b0452) - HFuncTestCallPanicFullEP = wasmlib.ScHname(0x4c878834) - HFuncTestCallPanicViewEPFromFull = wasmlib.ScHname(0xfd7e8c1d) - HFuncTestChainOwnerIDFull = wasmlib.ScHname(0x2aff1167) - HFuncTestEventLogDeploy = wasmlib.ScHname(0x96ff760a) - HFuncTestEventLogEventData = wasmlib.ScHname(0x0efcf939) - HFuncTestEventLogGenericData = wasmlib.ScHname(0x6a16629d) - HFuncTestPanicFullEP = wasmlib.ScHname(0x24fdef07) - HFuncWithdrawToChain = wasmlib.ScHname(0x437bc026) - HViewCheckContextFromViewEP = wasmlib.ScHname(0x88ff0167) - HViewFibonacci = wasmlib.ScHname(0x7940873c) - HViewGetCounter = wasmlib.ScHname(0xb423e607) - HViewGetInt = wasmlib.ScHname(0x1887e5ef) - HViewGetStringValue = wasmlib.ScHname(0xcf0a4d32) - HViewJustView = wasmlib.ScHname(0x33b8972e) - HViewPassTypesView = wasmlib.ScHname(0x1a5b87ea) - HViewTestCallPanicViewEPFromView = wasmlib.ScHname(0x91b10c99) - HViewTestChainOwnerIDView = wasmlib.ScHname(0x26586c33) - HViewTestPanicViewEP = wasmlib.ScHname(0x22bc4d72) - HViewTestSandboxCall = wasmlib.ScHname(0x42d72b63) + HFuncCallOnChain = wasmtypes.ScHname(0x95a3d123) + HFuncCheckContextFromFullEP = wasmtypes.ScHname(0xa56c24ba) + HFuncDoNothing = wasmtypes.ScHname(0xdda4a6de) + HFuncGetMintedSupply = wasmtypes.ScHname(0x0c2d113c) + HFuncIncCounter = wasmtypes.ScHname(0x7b287419) + HFuncInit = wasmtypes.ScHname(0x1f44d644) + HFuncPassTypesFull = wasmtypes.ScHname(0x733ea0ea) + HFuncRunRecursion = wasmtypes.ScHname(0x833425fd) + HFuncSendToAddress = wasmtypes.ScHname(0x63ce4634) + HFuncSetInt = wasmtypes.ScHname(0x62056f74) + HFuncSpawn = wasmtypes.ScHname(0xec929d12) + HFuncTestBlockContext1 = wasmtypes.ScHname(0x796d4136) + HFuncTestBlockContext2 = wasmtypes.ScHname(0x758b0452) + HFuncTestCallPanicFullEP = wasmtypes.ScHname(0x4c878834) + HFuncTestCallPanicViewEPFromFull = wasmtypes.ScHname(0xfd7e8c1d) + HFuncTestChainOwnerIDFull = wasmtypes.ScHname(0x2aff1167) + HFuncTestEventLogDeploy = wasmtypes.ScHname(0x96ff760a) + HFuncTestEventLogEventData = wasmtypes.ScHname(0x0efcf939) + HFuncTestEventLogGenericData = wasmtypes.ScHname(0x6a16629d) + HFuncTestPanicFullEP = wasmtypes.ScHname(0x24fdef07) + HFuncWithdrawToChain = wasmtypes.ScHname(0x437bc026) + HViewCheckContextFromViewEP = wasmtypes.ScHname(0x88ff0167) + HViewFibonacci = wasmtypes.ScHname(0x7940873c) + HViewGetCounter = wasmtypes.ScHname(0xb423e607) + HViewGetInt = wasmtypes.ScHname(0x1887e5ef) + HViewGetStringValue = wasmtypes.ScHname(0xcf0a4d32) + HViewJustView = wasmtypes.ScHname(0x33b8972e) + HViewPassTypesView = wasmtypes.ScHname(0x1a5b87ea) + HViewTestCallPanicViewEPFromView = wasmtypes.ScHname(0x91b10c99) + HViewTestChainOwnerIDView = wasmtypes.ScHname(0x26586c33) + HViewTestPanicViewEP = wasmtypes.ScHname(0x22bc4d72) + HViewTestSandboxCall = wasmtypes.ScHname(0x42d72b63) ) diff --git a/contracts/wasm/testcore/go/testcore/contract.go b/contracts/wasm/testcore/go/testcore/contract.go index 6799a98352..1ead64ad99 100644 --- a/contracts/wasm/testcore/go/testcore/contract.go +++ b/contracts/wasm/testcore/go/testcore/contract.go @@ -7,7 +7,7 @@ package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type CallOnChainCall struct { Func *wasmlib.ScFunc @@ -168,13 +168,14 @@ var ScFuncs Funcs func (sc Funcs) CallOnChain(ctx wasmlib.ScFuncCallContext) *CallOnChainCall { f := &CallOnChainCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncCallOnChain)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) + wasmlib.NewCallResultsProxy(&f.Func.ScView, &f.Results.proxy) return f } func (sc Funcs) CheckContextFromFullEP(ctx wasmlib.ScFuncCallContext) *CheckContextFromFullEPCall { f := &CheckContextFromFullEPCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncCheckContextFromFullEP)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -184,7 +185,7 @@ func (sc Funcs) DoNothing(ctx wasmlib.ScFuncCallContext) *DoNothingCall { func (sc Funcs) GetMintedSupply(ctx wasmlib.ScFuncCallContext) *GetMintedSupplyCall { f := &GetMintedSupplyCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncGetMintedSupply)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(&f.Func.ScView, &f.Results.proxy) return f } @@ -193,38 +194,39 @@ func (sc Funcs) IncCounter(ctx wasmlib.ScFuncCallContext) *IncCounterCall { } func (sc Funcs) Init(ctx wasmlib.ScFuncCallContext) *InitCall { - f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit, keyMap[:], idxMap[:])} - f.Func.SetPtrs(&f.Params.id, nil) + f := &InitCall{Func: wasmlib.NewScInitFunc(ctx, HScName, HFuncInit)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) PassTypesFull(ctx wasmlib.ScFuncCallContext) *PassTypesFullCall { f := &PassTypesFullCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncPassTypesFull)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) RunRecursion(ctx wasmlib.ScFuncCallContext) *RunRecursionCall { f := &RunRecursionCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncRunRecursion)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) + wasmlib.NewCallResultsProxy(&f.Func.ScView, &f.Results.proxy) return f } func (sc Funcs) SendToAddress(ctx wasmlib.ScFuncCallContext) *SendToAddressCall { f := &SendToAddressCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSendToAddress)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetInt(ctx wasmlib.ScFuncCallContext) *SetIntCall { f := &SetIntCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetInt)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Spawn(ctx wasmlib.ScFuncCallContext) *SpawnCall { f := &SpawnCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSpawn)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -246,7 +248,7 @@ func (sc Funcs) TestCallPanicViewEPFromFull(ctx wasmlib.ScFuncCallContext) *Test func (sc Funcs) TestChainOwnerIDFull(ctx wasmlib.ScFuncCallContext) *TestChainOwnerIDFullCall { f := &TestChainOwnerIDFullCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTestChainOwnerIDFull)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(&f.Func.ScView, &f.Results.proxy) return f } @@ -260,7 +262,7 @@ func (sc Funcs) TestEventLogEventData(ctx wasmlib.ScFuncCallContext) *TestEventL func (sc Funcs) TestEventLogGenericData(ctx wasmlib.ScFuncCallContext) *TestEventLogGenericDataCall { f := &TestEventLogGenericDataCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTestEventLogGenericData)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -270,37 +272,40 @@ func (sc Funcs) TestPanicFullEP(ctx wasmlib.ScFuncCallContext) *TestPanicFullEPC func (sc Funcs) WithdrawToChain(ctx wasmlib.ScFuncCallContext) *WithdrawToChainCall { f := &WithdrawToChainCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncWithdrawToChain)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) CheckContextFromViewEP(ctx wasmlib.ScViewCallContext) *CheckContextFromViewEPCall { f := &CheckContextFromViewEPCall{Func: wasmlib.NewScView(ctx, HScName, HViewCheckContextFromViewEP)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) return f } func (sc Funcs) Fibonacci(ctx wasmlib.ScViewCallContext) *FibonacciCall { f := &FibonacciCall{Func: wasmlib.NewScView(ctx, HScName, HViewFibonacci)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetCounter(ctx wasmlib.ScViewCallContext) *GetCounterCall { f := &GetCounterCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetCounter)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetInt(ctx wasmlib.ScViewCallContext) *GetIntCall { f := &GetIntCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetInt)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetStringValue(ctx wasmlib.ScViewCallContext) *GetStringValueCall { f := &GetStringValueCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetStringValue)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } @@ -310,7 +315,7 @@ func (sc Funcs) JustView(ctx wasmlib.ScViewCallContext) *JustViewCall { func (sc Funcs) PassTypesView(ctx wasmlib.ScViewCallContext) *PassTypesViewCall { f := &PassTypesViewCall{Func: wasmlib.NewScView(ctx, HScName, HViewPassTypesView)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) return f } @@ -320,7 +325,7 @@ func (sc Funcs) TestCallPanicViewEPFromView(ctx wasmlib.ScViewCallContext) *Test func (sc Funcs) TestChainOwnerIDView(ctx wasmlib.ScViewCallContext) *TestChainOwnerIDViewCall { f := &TestChainOwnerIDViewCall{Func: wasmlib.NewScView(ctx, HScName, HViewTestChainOwnerIDView)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } @@ -330,6 +335,6 @@ func (sc Funcs) TestPanicViewEP(ctx wasmlib.ScViewCallContext) *TestPanicViewEPC func (sc Funcs) TestSandboxCall(ctx wasmlib.ScViewCallContext) *TestSandboxCallCall { f := &TestSandboxCallCall{Func: wasmlib.NewScView(ctx, HScName, HViewTestSandboxCall)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/testcore/go/testcore/keys.go b/contracts/wasm/testcore/go/testcore/keys.go deleted file mode 100644 index bf75b33824..0000000000 --- a/contracts/wasm/testcore/go/testcore/keys.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package testcore - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamAddress = 0 - IdxParamAgentID = 1 - IdxParamCaller = 2 - IdxParamChainID = 3 - IdxParamChainOwnerID = 4 - IdxParamContractCreator = 5 - IdxParamContractID = 6 - IdxParamCounter = 7 - IdxParamFail = 8 - IdxParamHash = 9 - IdxParamHname = 10 - IdxParamHnameContract = 11 - IdxParamHnameEP = 12 - IdxParamHnameZero = 13 - IdxParamInt64 = 14 - IdxParamInt64Zero = 15 - IdxParamIntValue = 16 - IdxParamName = 17 - IdxParamProgHash = 18 - IdxParamString = 19 - IdxParamStringZero = 20 - IdxParamVarName = 21 - - IdxResultChainOwnerID = 22 - IdxResultCounter = 23 - IdxResultIntValue = 24 - IdxResultMintedColor = 25 - IdxResultMintedSupply = 26 - IdxResultSandboxCall = 27 - IdxResultValues = 28 - IdxResultVars = 29 - - IdxStateCounter = 30 - IdxStateHnameEP = 31 - IdxStateInts = 32 - IdxStateMintedColor = 33 - IdxStateMintedSupply = 34 -) - -const keyMapLen = 35 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamAddress, - ParamAgentID, - ParamCaller, - ParamChainID, - ParamChainOwnerID, - ParamContractCreator, - ParamContractID, - ParamCounter, - ParamFail, - ParamHash, - ParamHname, - ParamHnameContract, - ParamHnameEP, - ParamHnameZero, - ParamInt64, - ParamInt64Zero, - ParamIntValue, - ParamName, - ParamProgHash, - ParamString, - ParamStringZero, - ParamVarName, - ResultChainOwnerID, - ResultCounter, - ResultIntValue, - ResultMintedColor, - ResultMintedSupply, - ResultSandboxCall, - ResultValues, - ResultVars, - StateCounter, - StateHnameEP, - StateInts, - StateMintedColor, - StateMintedSupply, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/testcore/go/testcore/lib.go b/contracts/wasm/testcore/go/testcore/lib.go index d24d89a3b2..225653e877 100644 --- a/contracts/wasm/testcore/go/testcore/lib.go +++ b/contracts/wasm/testcore/go/testcore/lib.go @@ -8,46 +8,88 @@ //nolint:dupl package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncCallOnChain, funcCallOnChainThunk) - exports.AddFunc(FuncCheckContextFromFullEP, funcCheckContextFromFullEPThunk) - exports.AddFunc(FuncDoNothing, funcDoNothingThunk) - exports.AddFunc(FuncGetMintedSupply, funcGetMintedSupplyThunk) - exports.AddFunc(FuncIncCounter, funcIncCounterThunk) - exports.AddFunc(FuncInit, funcInitThunk) - exports.AddFunc(FuncPassTypesFull, funcPassTypesFullThunk) - exports.AddFunc(FuncRunRecursion, funcRunRecursionThunk) - exports.AddFunc(FuncSendToAddress, funcSendToAddressThunk) - exports.AddFunc(FuncSetInt, funcSetIntThunk) - exports.AddFunc(FuncSpawn, funcSpawnThunk) - exports.AddFunc(FuncTestBlockContext1, funcTestBlockContext1Thunk) - exports.AddFunc(FuncTestBlockContext2, funcTestBlockContext2Thunk) - exports.AddFunc(FuncTestCallPanicFullEP, funcTestCallPanicFullEPThunk) - exports.AddFunc(FuncTestCallPanicViewEPFromFull, funcTestCallPanicViewEPFromFullThunk) - exports.AddFunc(FuncTestChainOwnerIDFull, funcTestChainOwnerIDFullThunk) - exports.AddFunc(FuncTestEventLogDeploy, funcTestEventLogDeployThunk) - exports.AddFunc(FuncTestEventLogEventData, funcTestEventLogEventDataThunk) - exports.AddFunc(FuncTestEventLogGenericData, funcTestEventLogGenericDataThunk) - exports.AddFunc(FuncTestPanicFullEP, funcTestPanicFullEPThunk) - exports.AddFunc(FuncWithdrawToChain, funcWithdrawToChainThunk) - exports.AddView(ViewCheckContextFromViewEP, viewCheckContextFromViewEPThunk) - exports.AddView(ViewFibonacci, viewFibonacciThunk) - exports.AddView(ViewGetCounter, viewGetCounterThunk) - exports.AddView(ViewGetInt, viewGetIntThunk) - exports.AddView(ViewGetStringValue, viewGetStringValueThunk) - exports.AddView(ViewJustView, viewJustViewThunk) - exports.AddView(ViewPassTypesView, viewPassTypesViewThunk) - exports.AddView(ViewTestCallPanicViewEPFromView, viewTestCallPanicViewEPFromViewThunk) - exports.AddView(ViewTestChainOwnerIDView, viewTestChainOwnerIDViewThunk) - exports.AddView(ViewTestPanicViewEP, viewTestPanicViewEPThunk) - exports.AddView(ViewTestSandboxCall, viewTestSandboxCallThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() - } +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncCallOnChain, + FuncCheckContextFromFullEP, + FuncDoNothing, + FuncGetMintedSupply, + FuncIncCounter, + FuncInit, + FuncPassTypesFull, + FuncRunRecursion, + FuncSendToAddress, + FuncSetInt, + FuncSpawn, + FuncTestBlockContext1, + FuncTestBlockContext2, + FuncTestCallPanicFullEP, + FuncTestCallPanicViewEPFromFull, + FuncTestChainOwnerIDFull, + FuncTestEventLogDeploy, + FuncTestEventLogEventData, + FuncTestEventLogGenericData, + FuncTestPanicFullEP, + FuncWithdrawToChain, + ViewCheckContextFromViewEP, + ViewFibonacci, + ViewGetCounter, + ViewGetInt, + ViewGetStringValue, + ViewJustView, + ViewPassTypesView, + ViewTestCallPanicViewEPFromView, + ViewTestChainOwnerIDView, + ViewTestPanicViewEP, + ViewTestSandboxCall, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcCallOnChainThunk, + funcCheckContextFromFullEPThunk, + funcDoNothingThunk, + funcGetMintedSupplyThunk, + funcIncCounterThunk, + funcInitThunk, + funcPassTypesFullThunk, + funcRunRecursionThunk, + funcSendToAddressThunk, + funcSetIntThunk, + funcSpawnThunk, + funcTestBlockContext1Thunk, + funcTestBlockContext2Thunk, + funcTestCallPanicFullEPThunk, + funcTestCallPanicViewEPFromFullThunk, + funcTestChainOwnerIDFullThunk, + funcTestEventLogDeployThunk, + funcTestEventLogEventDataThunk, + funcTestEventLogGenericDataThunk, + funcTestPanicFullEPThunk, + funcWithdrawToChainThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewCheckContextFromViewEPThunk, + viewFibonacciThunk, + viewGetCounterThunk, + viewGetIntThunk, + viewGetStringValueThunk, + viewJustViewThunk, + viewPassTypesViewThunk, + viewTestCallPanicViewEPFromViewThunk, + viewTestChainOwnerIDViewThunk, + viewTestPanicViewEPThunk, + viewTestSandboxCallThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return + } + + wasmlib.ScExportsExport(&exportMap) } type CallOnChainContext struct { @@ -58,19 +100,21 @@ type CallOnChainContext struct { func funcCallOnChainThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcCallOnChain") + results := wasmlib.NewScDict() f := &CallOnChainContext{ Params: ImmutableCallOnChainParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableCallOnChainResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.IntValue().Exists(), "missing mandatory intValue") funcCallOnChain(ctx, f) + ctx.Results(results) ctx.Log("testcore.funcCallOnChain ok") } @@ -83,10 +127,10 @@ func funcCheckContextFromFullEPThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcCheckContextFromFullEP") f := &CheckContextFromFullEPContext{ Params: ImmutableCheckContextFromFullEPParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.AgentID().Exists(), "missing mandatory agentID") @@ -106,7 +150,7 @@ func funcDoNothingThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcDoNothing") f := &DoNothingContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcDoNothing(ctx, f) @@ -120,15 +164,17 @@ type GetMintedSupplyContext struct { func funcGetMintedSupplyThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcGetMintedSupply") + results := wasmlib.NewScDict() f := &GetMintedSupplyContext{ Results: MutableGetMintedSupplyResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcGetMintedSupply(ctx, f) + ctx.Results(results) ctx.Log("testcore.funcGetMintedSupply ok") } @@ -140,7 +186,7 @@ func funcIncCounterThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcIncCounter") f := &IncCounterContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcIncCounter(ctx, f) @@ -156,10 +202,10 @@ func funcInitThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcInit") f := &InitContext{ Params: ImmutableInitParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcInit(ctx, f) @@ -175,10 +221,10 @@ func funcPassTypesFullThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcPassTypesFull") f := &PassTypesFullContext{ Params: ImmutablePassTypesFullParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Address().Exists(), "missing mandatory address") @@ -204,19 +250,21 @@ type RunRecursionContext struct { func funcRunRecursionThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcRunRecursion") + results := wasmlib.NewScDict() f := &RunRecursionContext{ Params: ImmutableRunRecursionParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableRunRecursionResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.IntValue().Exists(), "missing mandatory intValue") funcRunRecursion(ctx, f) + ctx.Results(results) ctx.Log("testcore.funcRunRecursion ok") } @@ -227,16 +275,16 @@ type SendToAddressContext struct { func funcSendToAddressThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcSendToAddress") - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &SendToAddressContext{ Params: ImmutableSendToAddressParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + ctx.Require(f.Params.Address().Exists(), "missing mandatory address") funcSendToAddress(ctx, f) ctx.Log("testcore.funcSendToAddress ok") @@ -251,10 +299,10 @@ func funcSetIntThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcSetInt") f := &SetIntContext{ Params: ImmutableSetIntParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.IntValue().Exists(), "missing mandatory intValue") @@ -272,10 +320,10 @@ func funcSpawnThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcSpawn") f := &SpawnContext{ Params: ImmutableSpawnParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.ProgHash().Exists(), "missing mandatory progHash") @@ -291,7 +339,7 @@ func funcTestBlockContext1Thunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestBlockContext1") f := &TestBlockContext1Context{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestBlockContext1(ctx, f) @@ -306,7 +354,7 @@ func funcTestBlockContext2Thunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestBlockContext2") f := &TestBlockContext2Context{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestBlockContext2(ctx, f) @@ -321,7 +369,7 @@ func funcTestCallPanicFullEPThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestCallPanicFullEP") f := &TestCallPanicFullEPContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestCallPanicFullEP(ctx, f) @@ -336,7 +384,7 @@ func funcTestCallPanicViewEPFromFullThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestCallPanicViewEPFromFull") f := &TestCallPanicViewEPFromFullContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestCallPanicViewEPFromFull(ctx, f) @@ -350,15 +398,17 @@ type TestChainOwnerIDFullContext struct { func funcTestChainOwnerIDFullThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestChainOwnerIDFull") + results := wasmlib.NewScDict() f := &TestChainOwnerIDFullContext{ Results: MutableTestChainOwnerIDFullResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestChainOwnerIDFull(ctx, f) + ctx.Results(results) ctx.Log("testcore.funcTestChainOwnerIDFull ok") } @@ -370,7 +420,7 @@ func funcTestEventLogDeployThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestEventLogDeploy") f := &TestEventLogDeployContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestEventLogDeploy(ctx, f) @@ -385,7 +435,7 @@ func funcTestEventLogEventDataThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestEventLogEventData") f := &TestEventLogEventDataContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestEventLogEventData(ctx, f) @@ -401,10 +451,10 @@ func funcTestEventLogGenericDataThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestEventLogGenericData") f := &TestEventLogGenericDataContext{ Params: ImmutableTestEventLogGenericDataParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Counter().Exists(), "missing mandatory counter") @@ -420,7 +470,7 @@ func funcTestPanicFullEPThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcTestPanicFullEP") f := &TestPanicFullEPContext{ State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcTestPanicFullEP(ctx, f) @@ -436,10 +486,10 @@ func funcWithdrawToChainThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testcore.funcWithdrawToChain") f := &WithdrawToChainContext{ Params: ImmutableWithdrawToChainParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.ChainID().Exists(), "missing mandatory chainID") @@ -456,10 +506,10 @@ func viewCheckContextFromViewEPThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewCheckContextFromViewEP") f := &CheckContextFromViewEPContext{ Params: ImmutableCheckContextFromViewEPParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.AgentID().Exists(), "missing mandatory agentID") @@ -478,19 +528,21 @@ type FibonacciContext struct { func viewFibonacciThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewFibonacci") + results := wasmlib.NewScDict() f := &FibonacciContext{ Params: ImmutableFibonacciParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableFibonacciResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.IntValue().Exists(), "missing mandatory intValue") viewFibonacci(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewFibonacci ok") } @@ -501,15 +553,17 @@ type GetCounterContext struct { func viewGetCounterThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewGetCounter") + results := wasmlib.NewScDict() f := &GetCounterContext{ Results: MutableGetCounterResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetCounter(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewGetCounter ok") } @@ -521,19 +575,21 @@ type GetIntContext struct { func viewGetIntThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewGetInt") + results := wasmlib.NewScDict() f := &GetIntContext{ Params: ImmutableGetIntParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableGetIntResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") viewGetInt(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewGetInt ok") } @@ -545,19 +601,21 @@ type GetStringValueContext struct { func viewGetStringValueThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewGetStringValue") + results := wasmlib.NewScDict() f := &GetStringValueContext{ Params: ImmutableGetStringValueParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableGetStringValueResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.VarName().Exists(), "missing mandatory varName") viewGetStringValue(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewGetStringValue ok") } @@ -569,7 +627,7 @@ func viewJustViewThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewJustView") f := &JustViewContext{ State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewJustView(ctx, f) @@ -585,10 +643,10 @@ func viewPassTypesViewThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewPassTypesView") f := &PassTypesViewContext{ Params: ImmutablePassTypesViewParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Address().Exists(), "missing mandatory address") @@ -614,7 +672,7 @@ func viewTestCallPanicViewEPFromViewThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewTestCallPanicViewEPFromView") f := &TestCallPanicViewEPFromViewContext{ State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewTestCallPanicViewEPFromView(ctx, f) @@ -628,15 +686,17 @@ type TestChainOwnerIDViewContext struct { func viewTestChainOwnerIDViewThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewTestChainOwnerIDView") + results := wasmlib.NewScDict() f := &TestChainOwnerIDViewContext{ Results: MutableTestChainOwnerIDViewResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewTestChainOwnerIDView(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewTestChainOwnerIDView ok") } @@ -648,7 +708,7 @@ func viewTestPanicViewEPThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewTestPanicViewEP") f := &TestPanicViewEPContext{ State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewTestPanicViewEP(ctx, f) @@ -662,14 +722,16 @@ type TestSandboxCallContext struct { func viewTestSandboxCallThunk(ctx wasmlib.ScViewContext) { ctx.Log("testcore.viewTestSandboxCall") + results := wasmlib.NewScDict() f := &TestSandboxCallContext{ Results: MutableTestSandboxCallResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestCoreState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewTestSandboxCall(ctx, f) + ctx.Results(results) ctx.Log("testcore.viewTestSandboxCall ok") } diff --git a/contracts/wasm/testcore/go/testcore/params.go b/contracts/wasm/testcore/go/testcore/params.go index d72858d871..0e6ed33026 100644 --- a/contracts/wasm/testcore/go/testcore/params.go +++ b/contracts/wasm/testcore/go/testcore/params.go @@ -7,484 +7,484 @@ package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableCallOnChainParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableCallOnChainParams) HnameContract() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHnameContract)) +func (s ImmutableCallOnChainParams) HnameContract() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHnameContract)) } -func (s ImmutableCallOnChainParams) HnameEP() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHnameEP)) +func (s ImmutableCallOnChainParams) HnameEP() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHnameEP)) } -func (s ImmutableCallOnChainParams) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s ImmutableCallOnChainParams) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamIntValue)) } type MutableCallOnChainParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableCallOnChainParams) HnameContract() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHnameContract)) +func (s MutableCallOnChainParams) HnameContract() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHnameContract)) } -func (s MutableCallOnChainParams) HnameEP() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHnameEP)) +func (s MutableCallOnChainParams) HnameEP() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHnameEP)) } -func (s MutableCallOnChainParams) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s MutableCallOnChainParams) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamIntValue)) } type ImmutableCheckContextFromFullEPParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableCheckContextFromFullEPParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s ImmutableCheckContextFromFullEPParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s ImmutableCheckContextFromFullEPParams) Caller() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamCaller)) +func (s ImmutableCheckContextFromFullEPParams) Caller() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamCaller)) } -func (s ImmutableCheckContextFromFullEPParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutableCheckContextFromFullEPParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } -func (s ImmutableCheckContextFromFullEPParams) ChainOwnerID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamChainOwnerID)) +func (s ImmutableCheckContextFromFullEPParams) ChainOwnerID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamChainOwnerID)) } -func (s ImmutableCheckContextFromFullEPParams) ContractCreator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamContractCreator)) +func (s ImmutableCheckContextFromFullEPParams) ContractCreator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamContractCreator)) } type MutableCheckContextFromFullEPParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableCheckContextFromFullEPParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s MutableCheckContextFromFullEPParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s MutableCheckContextFromFullEPParams) Caller() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamCaller)) +func (s MutableCheckContextFromFullEPParams) Caller() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamCaller)) } -func (s MutableCheckContextFromFullEPParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutableCheckContextFromFullEPParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } -func (s MutableCheckContextFromFullEPParams) ChainOwnerID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamChainOwnerID)) +func (s MutableCheckContextFromFullEPParams) ChainOwnerID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamChainOwnerID)) } -func (s MutableCheckContextFromFullEPParams) ContractCreator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamContractCreator)) +func (s MutableCheckContextFromFullEPParams) ContractCreator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamContractCreator)) } type ImmutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableInitParams) Fail() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, idxMap[IdxParamFail]) +func (s ImmutableInitParams) Fail() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamFail)) } type MutableInitParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableInitParams) Fail() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, idxMap[IdxParamFail]) +func (s MutableInitParams) Fail() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamFail)) } type ImmutablePassTypesFullParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutablePassTypesFullParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutablePassTypesFullParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } -func (s ImmutablePassTypesFullParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s ImmutablePassTypesFullParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s ImmutablePassTypesFullParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutablePassTypesFullParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } -func (s ImmutablePassTypesFullParams) ContractID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamContractID)) +func (s ImmutablePassTypesFullParams) ContractID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamContractID)) } -func (s ImmutablePassTypesFullParams) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s ImmutablePassTypesFullParams) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamHash)) } -func (s ImmutablePassTypesFullParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s ImmutablePassTypesFullParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) } -func (s ImmutablePassTypesFullParams) HnameZero() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHnameZero)) +func (s ImmutablePassTypesFullParams) HnameZero() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHnameZero)) } -func (s ImmutablePassTypesFullParams) Int64() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s ImmutablePassTypesFullParams) Int64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamInt64)) } -func (s ImmutablePassTypesFullParams) Int64Zero() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamInt64Zero)) +func (s ImmutablePassTypesFullParams) Int64Zero() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamInt64Zero)) } -func (s ImmutablePassTypesFullParams) String() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamString)) +func (s ImmutablePassTypesFullParams) String() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamString)) } -func (s ImmutablePassTypesFullParams) StringZero() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamStringZero)) +func (s ImmutablePassTypesFullParams) StringZero() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamStringZero)) } type MutablePassTypesFullParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutablePassTypesFullParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutablePassTypesFullParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } -func (s MutablePassTypesFullParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s MutablePassTypesFullParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s MutablePassTypesFullParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutablePassTypesFullParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } -func (s MutablePassTypesFullParams) ContractID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamContractID)) +func (s MutablePassTypesFullParams) ContractID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamContractID)) } -func (s MutablePassTypesFullParams) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s MutablePassTypesFullParams) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamHash)) } -func (s MutablePassTypesFullParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s MutablePassTypesFullParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) } -func (s MutablePassTypesFullParams) HnameZero() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHnameZero)) +func (s MutablePassTypesFullParams) HnameZero() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHnameZero)) } -func (s MutablePassTypesFullParams) Int64() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s MutablePassTypesFullParams) Int64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamInt64)) } -func (s MutablePassTypesFullParams) Int64Zero() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamInt64Zero)) +func (s MutablePassTypesFullParams) Int64Zero() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamInt64Zero)) } -func (s MutablePassTypesFullParams) String() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamString)) +func (s MutablePassTypesFullParams) String() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamString)) } -func (s MutablePassTypesFullParams) StringZero() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamStringZero)) +func (s MutablePassTypesFullParams) StringZero() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamStringZero)) } type ImmutableRunRecursionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRunRecursionParams) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s ImmutableRunRecursionParams) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamIntValue)) } type MutableRunRecursionParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRunRecursionParams) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s MutableRunRecursionParams) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamIntValue)) } type ImmutableSendToAddressParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSendToAddressParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutableSendToAddressParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } type MutableSendToAddressParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSendToAddressParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutableSendToAddressParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } type ImmutableSetIntParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSetIntParams) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s ImmutableSetIntParams) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamIntValue)) } -func (s ImmutableSetIntParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableSetIntParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableSetIntParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSetIntParams) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s MutableSetIntParams) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamIntValue)) } -func (s MutableSetIntParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableSetIntParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableSpawnParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableSpawnParams) ProgHash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamProgHash)) +func (s ImmutableSpawnParams) ProgHash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamProgHash)) } type MutableSpawnParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableSpawnParams) ProgHash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamProgHash)) +func (s MutableSpawnParams) ProgHash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamProgHash)) } type ImmutableTestEventLogGenericDataParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTestEventLogGenericDataParams) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamCounter)) +func (s ImmutableTestEventLogGenericDataParams) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamCounter)) } type MutableTestEventLogGenericDataParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTestEventLogGenericDataParams) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamCounter)) +func (s MutableTestEventLogGenericDataParams) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamCounter)) } type ImmutableWithdrawToChainParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableWithdrawToChainParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutableWithdrawToChainParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } type MutableWithdrawToChainParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableWithdrawToChainParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutableWithdrawToChainParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } type ImmutableCheckContextFromViewEPParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableCheckContextFromViewEPParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s ImmutableCheckContextFromViewEPParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s ImmutableCheckContextFromViewEPParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutableCheckContextFromViewEPParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } -func (s ImmutableCheckContextFromViewEPParams) ChainOwnerID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamChainOwnerID)) +func (s ImmutableCheckContextFromViewEPParams) ChainOwnerID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamChainOwnerID)) } -func (s ImmutableCheckContextFromViewEPParams) ContractCreator() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamContractCreator)) +func (s ImmutableCheckContextFromViewEPParams) ContractCreator() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamContractCreator)) } type MutableCheckContextFromViewEPParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableCheckContextFromViewEPParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s MutableCheckContextFromViewEPParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s MutableCheckContextFromViewEPParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutableCheckContextFromViewEPParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } -func (s MutableCheckContextFromViewEPParams) ChainOwnerID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamChainOwnerID)) +func (s MutableCheckContextFromViewEPParams) ChainOwnerID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamChainOwnerID)) } -func (s MutableCheckContextFromViewEPParams) ContractCreator() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamContractCreator)) +func (s MutableCheckContextFromViewEPParams) ContractCreator() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamContractCreator)) } type ImmutableFibonacciParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableFibonacciParams) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s ImmutableFibonacciParams) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamIntValue)) } type MutableFibonacciParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableFibonacciParams) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamIntValue)) +func (s MutableFibonacciParams) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamIntValue)) } type ImmutableGetIntParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetIntParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableGetIntParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableGetIntParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetIntParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableGetIntParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableGetStringValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetStringValueParams) VarName() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamVarName)) +func (s ImmutableGetStringValueParams) VarName() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamVarName)) } type MutableGetStringValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetStringValueParams) VarName() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamVarName)) +func (s MutableGetStringValueParams) VarName() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamVarName)) } type ImmutablePassTypesViewParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutablePassTypesViewParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutablePassTypesViewParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } -func (s ImmutablePassTypesViewParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s ImmutablePassTypesViewParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s ImmutablePassTypesViewParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutablePassTypesViewParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } -func (s ImmutablePassTypesViewParams) ContractID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamContractID)) +func (s ImmutablePassTypesViewParams) ContractID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamContractID)) } -func (s ImmutablePassTypesViewParams) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s ImmutablePassTypesViewParams) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamHash)) } -func (s ImmutablePassTypesViewParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s ImmutablePassTypesViewParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) } -func (s ImmutablePassTypesViewParams) HnameZero() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHnameZero)) +func (s ImmutablePassTypesViewParams) HnameZero() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHnameZero)) } -func (s ImmutablePassTypesViewParams) Int64() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s ImmutablePassTypesViewParams) Int64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamInt64)) } -func (s ImmutablePassTypesViewParams) Int64Zero() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamInt64Zero)) +func (s ImmutablePassTypesViewParams) Int64Zero() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamInt64Zero)) } -func (s ImmutablePassTypesViewParams) String() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamString)) +func (s ImmutablePassTypesViewParams) String() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamString)) } -func (s ImmutablePassTypesViewParams) StringZero() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamStringZero)) +func (s ImmutablePassTypesViewParams) StringZero() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamStringZero)) } type MutablePassTypesViewParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutablePassTypesViewParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutablePassTypesViewParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } -func (s MutablePassTypesViewParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s MutablePassTypesViewParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s MutablePassTypesViewParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutablePassTypesViewParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } -func (s MutablePassTypesViewParams) ContractID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamContractID)) +func (s MutablePassTypesViewParams) ContractID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamContractID)) } -func (s MutablePassTypesViewParams) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s MutablePassTypesViewParams) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamHash)) } -func (s MutablePassTypesViewParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s MutablePassTypesViewParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) } -func (s MutablePassTypesViewParams) HnameZero() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHnameZero)) +func (s MutablePassTypesViewParams) HnameZero() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHnameZero)) } -func (s MutablePassTypesViewParams) Int64() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s MutablePassTypesViewParams) Int64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamInt64)) } -func (s MutablePassTypesViewParams) Int64Zero() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamInt64Zero)) +func (s MutablePassTypesViewParams) Int64Zero() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamInt64Zero)) } -func (s MutablePassTypesViewParams) String() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamString)) +func (s MutablePassTypesViewParams) String() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamString)) } -func (s MutablePassTypesViewParams) StringZero() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamStringZero)) +func (s MutablePassTypesViewParams) StringZero() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamStringZero)) } diff --git a/contracts/wasm/testcore/go/testcore/results.go b/contracts/wasm/testcore/go/testcore/results.go index 2d11e8178c..0b01e33811 100644 --- a/contracts/wasm/testcore/go/testcore/results.go +++ b/contracts/wasm/testcore/go/testcore/results.go @@ -7,212 +7,216 @@ package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableCallOnChainResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableCallOnChainResults) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s ImmutableCallOnChainResults) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultIntValue)) } type MutableCallOnChainResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableCallOnChainResults) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s MutableCallOnChainResults) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultIntValue)) } type ImmutableGetMintedSupplyResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetMintedSupplyResults) MintedColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ResultMintedColor)) +func (s ImmutableGetMintedSupplyResults) MintedColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ResultMintedColor)) } -func (s ImmutableGetMintedSupplyResults) MintedSupply() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultMintedSupply)) +func (s ImmutableGetMintedSupplyResults) MintedSupply() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultMintedSupply)) } type MutableGetMintedSupplyResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetMintedSupplyResults) MintedColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ResultMintedColor)) +func (s MutableGetMintedSupplyResults) MintedColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ResultMintedColor)) } -func (s MutableGetMintedSupplyResults) MintedSupply() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultMintedSupply)) +func (s MutableGetMintedSupplyResults) MintedSupply() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultMintedSupply)) } type ImmutableRunRecursionResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableRunRecursionResults) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s ImmutableRunRecursionResults) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultIntValue)) } type MutableRunRecursionResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableRunRecursionResults) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s MutableRunRecursionResults) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultIntValue)) } type ImmutableTestChainOwnerIDFullResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTestChainOwnerIDFullResults) ChainOwnerID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) +func (s ImmutableTestChainOwnerIDFullResults) ChainOwnerID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultChainOwnerID)) } type MutableTestChainOwnerIDFullResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTestChainOwnerIDFullResults) ChainOwnerID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) +func (s MutableTestChainOwnerIDFullResults) ChainOwnerID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultChainOwnerID)) } type ImmutableFibonacciResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableFibonacciResults) IntValue() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s ImmutableFibonacciResults) IntValue() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultIntValue)) } type MutableFibonacciResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableFibonacciResults) IntValue() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultIntValue)) +func (s MutableFibonacciResults) IntValue() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultIntValue)) } type ImmutableGetCounterResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetCounterResults) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultCounter)) +func (s ImmutableGetCounterResults) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultCounter)) } type MutableGetCounterResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetCounterResults) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultCounter)) +func (s MutableGetCounterResults) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultCounter)) } type MapStringToImmutableInt64 struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapStringToImmutableInt64) GetInt64(key string) wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToImmutableInt64) GetInt64(key string) wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(m.proxy.Key(wasmtypes.StringToBytes(key))) } type ImmutableGetIntResults struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableGetIntResults) Values() MapStringToImmutableInt64 { - return MapStringToImmutableInt64{objID: s.id} + //nolint:gosimple + return MapStringToImmutableInt64{proxy: s.proxy} } type MapStringToMutableInt64 struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableInt64) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapStringToMutableInt64) GetInt64(key string) wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToMutableInt64) GetInt64(key string) wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(m.proxy.Key(wasmtypes.StringToBytes(key))) } type MutableGetIntResults struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableGetIntResults) Values() MapStringToMutableInt64 { - return MapStringToMutableInt64{objID: s.id} + //nolint:gosimple + return MapStringToMutableInt64{proxy: s.proxy} } type MapStringToImmutableString struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapStringToImmutableString) GetString(key string) wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToImmutableString) GetString(key string) wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(m.proxy.Key(wasmtypes.StringToBytes(key))) } type ImmutableGetStringValueResults struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableGetStringValueResults) Vars() MapStringToImmutableString { - return MapStringToImmutableString{objID: s.id} + //nolint:gosimple + return MapStringToImmutableString{proxy: s.proxy} } type MapStringToMutableString struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableString) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapStringToMutableString) GetString(key string) wasmlib.ScMutableString { - return wasmlib.NewScMutableString(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToMutableString) GetString(key string) wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(m.proxy.Key(wasmtypes.StringToBytes(key))) } type MutableGetStringValueResults struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableGetStringValueResults) Vars() MapStringToMutableString { - return MapStringToMutableString{objID: s.id} + //nolint:gosimple + return MapStringToMutableString{proxy: s.proxy} } type ImmutableTestChainOwnerIDViewResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTestChainOwnerIDViewResults) ChainOwnerID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) +func (s ImmutableTestChainOwnerIDViewResults) ChainOwnerID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultChainOwnerID)) } type MutableTestChainOwnerIDViewResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTestChainOwnerIDViewResults) ChainOwnerID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) +func (s MutableTestChainOwnerIDViewResults) ChainOwnerID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultChainOwnerID)) } type ImmutableTestSandboxCallResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTestSandboxCallResults) SandboxCall() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultSandboxCall)) +func (s ImmutableTestSandboxCallResults) SandboxCall() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultSandboxCall)) } type MutableTestSandboxCallResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTestSandboxCallResults) SandboxCall() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultSandboxCall)) +func (s MutableTestSandboxCallResults) SandboxCall() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultSandboxCall)) } diff --git a/contracts/wasm/testcore/go/testcore/state.go b/contracts/wasm/testcore/go/testcore/state.go index cb134bf3b5..5927de5346 100644 --- a/contracts/wasm/testcore/go/testcore/state.go +++ b/contracts/wasm/testcore/go/testcore/state.go @@ -7,58 +7,56 @@ package testcore -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableTestCoreState struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTestCoreState) Counter() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateCounter)) +func (s ImmutableTestCoreState) Counter() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(StateCounter)) } -func (s ImmutableTestCoreState) HnameEP() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(StateHnameEP)) +func (s ImmutableTestCoreState) HnameEP() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(StateHnameEP)) } func (s ImmutableTestCoreState) Ints() MapStringToImmutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateInts), wasmlib.TYPE_MAP) - return MapStringToImmutableInt64{objID: mapID} + return MapStringToImmutableInt64{proxy: s.proxy.Root(StateInts)} } -func (s ImmutableTestCoreState) MintedColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(StateMintedColor)) +func (s ImmutableTestCoreState) MintedColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(StateMintedColor)) } -func (s ImmutableTestCoreState) MintedSupply() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateMintedSupply)) +func (s ImmutableTestCoreState) MintedSupply() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateMintedSupply)) } type MutableTestCoreState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableTestCoreState) AsImmutable() ImmutableTestCoreState { return ImmutableTestCoreState(s) } -func (s MutableTestCoreState) Counter() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateCounter)) +func (s MutableTestCoreState) Counter() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(StateCounter)) } -func (s MutableTestCoreState) HnameEP() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(StateHnameEP)) +func (s MutableTestCoreState) HnameEP() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(StateHnameEP)) } func (s MutableTestCoreState) Ints() MapStringToMutableInt64 { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateInts), wasmlib.TYPE_MAP) - return MapStringToMutableInt64{objID: mapID} + return MapStringToMutableInt64{proxy: s.proxy.Root(StateInts)} } -func (s MutableTestCoreState) MintedColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(StateMintedColor)) +func (s MutableTestCoreState) MintedColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(StateMintedColor)) } -func (s MutableTestCoreState) MintedSupply() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateMintedSupply)) +func (s MutableTestCoreState) MintedSupply() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateMintedSupply)) } diff --git a/contracts/wasm/testcore/go/testcore/testcore.go b/contracts/wasm/testcore/go/testcore/testcore.go index 9537c6374a..3c2bce1111 100644 --- a/contracts/wasm/testcore/go/testcore/testcore.go +++ b/contracts/wasm/testcore/go/testcore/testcore.go @@ -5,9 +5,10 @@ package testcore import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coreaccounts" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coregovernance" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coregovernance" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) const ( @@ -18,7 +19,7 @@ const ( ) func funcCallOnChain(ctx wasmlib.ScFuncContext, f *CallOnChainContext) { - paramIn := f.Params.IntValue().Value() + paramInt := f.Params.IntValue().Value() hnameContract := ctx.Contract() if f.Params.HnameContract().Exists() { @@ -39,10 +40,11 @@ func funcCallOnChain(ctx wasmlib.ScFuncContext, f *CallOnChainContext) { counter.SetValue(counter.Value() + 1) - params := wasmlib.NewScMutableMap() - params.GetInt64(wasmlib.Key(ParamIntValue)).SetValue(paramIn) + params := wasmlib.NewScDict() + key := []byte(ParamIntValue) + params.Set(key, wasmtypes.Int64ToBytes(paramInt)) ret := ctx.Call(hnameContract, hnameEP, params, nil) - retVal := ret.GetInt64(wasmlib.Key(ResultIntValue)).Value() + retVal := wasmtypes.Int64FromBytes(ret.Get(key)) f.Results.IntValue().SetValue(retVal) } @@ -62,8 +64,8 @@ func funcDoNothing(ctx wasmlib.ScFuncContext, f *DoNothingContext) { func funcGetMintedSupply(ctx wasmlib.ScFuncContext, f *GetMintedSupplyContext) { minted := ctx.Minted() mintedColors := minted.Colors() - ctx.Require(mintedColors.Length() == 1, "test only supports one minted color") - color := mintedColors.GetColor(0).Value() + ctx.Require(len(mintedColors) == 1, "test only supports one minted color") + color := mintedColors[0] amount := minted.Balance(color) f.Results.MintedColor().SetValue(color) f.Results.MintedSupply().SetValue(amount) @@ -87,8 +89,8 @@ func funcPassTypesFull(ctx wasmlib.ScFuncContext, f *PassTypesFullContext) { ctx.Require(f.Params.Int64Zero().Value() == 0, "int64-0 wrong") ctx.Require(f.Params.String().Value() == string(ParamString), "string wrong") ctx.Require(f.Params.StringZero().Value() == "", "string-0 wrong") - ctx.Require(f.Params.Hname().Value() == wasmlib.NewScHname(string(ParamHname)), "Hname wrong") - ctx.Require(f.Params.HnameZero().Value() == wasmlib.ScHname(0), "Hname-0 wrong") + ctx.Require(f.Params.Hname().Value() == ctx.Utility().Hname(ParamHname), "Hname wrong") + ctx.Require(f.Params.HnameZero().Value() == 0, "Hname-0 wrong") } func funcRunRecursion(ctx wasmlib.ScFuncContext, f *RunRecursionContext) { @@ -106,8 +108,8 @@ func funcRunRecursion(ctx wasmlib.ScFuncContext, f *RunRecursionContext) { } func funcSendToAddress(ctx wasmlib.ScFuncContext, f *SendToAddressContext) { - balances := wasmlib.NewScTransfersFromBalances(ctx.Balances()) - ctx.TransferToAddress(f.Params.Address().Value(), balances) + transfer := wasmlib.NewScTransfersFromBalances(ctx.Balances()) + ctx.TransferToAddress(f.Params.Address().Value(), transfer) } func funcSetInt(ctx wasmlib.ScFuncContext, f *SetIntContext) { @@ -132,7 +134,7 @@ func funcTestChainOwnerIDFull(ctx wasmlib.ScFuncContext, f *TestChainOwnerIDFull func funcTestEventLogDeploy(ctx wasmlib.ScFuncContext, f *TestEventLogDeployContext) { // deploy the same contract with another name programHash := ctx.Utility().HashBlake2b([]byte("testcore")) - ctx.Deploy(programHash, ContractNameDeployed, "test contract deploy log", nil) + ctx.DeployContract(programHash, ContractNameDeployed, "test contract deploy log", nil) } //nolint:unparam @@ -151,7 +153,7 @@ func funcTestPanicFullEP(ctx wasmlib.ScFuncContext, f *TestPanicFullEPContext) { } func funcWithdrawToChain(ctx wasmlib.ScFuncContext, f *WithdrawToChainContext) { - coreaccounts.ScFuncs.Withdraw(ctx).Func.TransferIotas(1).PostToChain(f.Params.ChainID().Value()) + coreaccounts.ScFuncs.Withdraw(ctx).Func.PostToChain(f.Params.ChainID().Value()) } func viewCheckContextFromViewEP(ctx wasmlib.ScViewContext, f *CheckContextFromViewEPContext) { @@ -203,8 +205,8 @@ func viewPassTypesView(ctx wasmlib.ScViewContext, f *PassTypesViewContext) { ctx.Require(f.Params.Int64Zero().Value() == 0, "int64-0 wrong") ctx.Require(f.Params.String().Value() == string(ParamString), "string wrong") ctx.Require(f.Params.StringZero().Value() == "", "string-0 wrong") - ctx.Require(f.Params.Hname().Value() == wasmlib.NewScHname(string(ParamHname)), "Hname wrong") - ctx.Require(f.Params.HnameZero().Value() == wasmlib.ScHname(0), "Hname-0 wrong") + ctx.Require(f.Params.Hname().Value() == ctx.Utility().Hname(ParamHname), "Hname wrong") + ctx.Require(f.Params.HnameZero().Value() == 0, "Hname-0 wrong") } //nolint:unparam @@ -245,9 +247,9 @@ func viewGetStringValue(ctx wasmlib.ScViewContext, f *GetStringValueContext) { func funcSpawn(ctx wasmlib.ScFuncContext, f *SpawnContext) { spawnName := ScName + "_spawned" spawnDescr := "spawned contract description" - ctx.Deploy(f.Params.ProgHash().Value(), spawnName, spawnDescr, nil) + ctx.DeployContract(f.Params.ProgHash().Value(), spawnName, spawnDescr, nil) - spawnHname := wasmlib.NewScHname(spawnName) + spawnHname := ctx.Utility().Hname(spawnName) for i := 0; i < 5; i++ { ctx.Call(spawnHname, HFuncIncCounter, nil, nil) } diff --git a/contracts/wasm/testcore/schema.yaml b/contracts/wasm/testcore/schema.yaml index 722daf8c8b..f5ffc71215 100644 --- a/contracts/wasm/testcore/schema.yaml +++ b/contracts/wasm/testcore/schema.yaml @@ -7,7 +7,7 @@ state: hnameEP: Hname ints: map[String]Int64 mintedColor: Color - mintedSupply: Int64 + mintedSupply: Uint64 funcs: callOnChain: params: @@ -27,7 +27,7 @@ funcs: getMintedSupply: results: mintedColor: Color - mintedSupply: Int64 + mintedSupply: Uint64 incCounter: {} init: params: diff --git a/contracts/wasm/testcore/src/contract.rs b/contracts/wasm/testcore/src/contract.rs index a00e5b9eeb..fd89948907 100644 --- a/contracts/wasm/testcore/src/contract.rs +++ b/contracts/wasm/testcore/src/contract.rs @@ -7,13 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; -use crate::results::*; +use crate::*; pub struct CallOnChainCall { pub func: ScFunc, @@ -172,260 +167,265 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn call_on_chain(_ctx: & dyn ScFuncCallContext) -> CallOnChainCall { + pub fn call_on_chain(_ctx: &dyn ScFuncCallContext) -> CallOnChainCall { let mut f = CallOnChainCall { func: ScFunc::new(HSC_NAME, HFUNC_CALL_ON_CHAIN), - params: MutableCallOnChainParams { id: 0 }, - results: ImmutableCallOnChainResults { id: 0 }, + params: MutableCallOnChainParams { proxy: Proxy::nil() }, + results: ImmutableCallOnChainResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScFunc::link_params(&mut f.params.proxy, &f.func); + ScFunc::link_results(&mut f.results.proxy, &f.func); f } - pub fn check_context_from_full_ep(_ctx: & dyn ScFuncCallContext) -> CheckContextFromFullEPCall { + pub fn check_context_from_full_ep(_ctx: &dyn ScFuncCallContext) -> CheckContextFromFullEPCall { let mut f = CheckContextFromFullEPCall { func: ScFunc::new(HSC_NAME, HFUNC_CHECK_CONTEXT_FROM_FULL_EP), - params: MutableCheckContextFromFullEPParams { id: 0 }, + params: MutableCheckContextFromFullEPParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn do_nothing(_ctx: & dyn ScFuncCallContext) -> DoNothingCall { + pub fn do_nothing(_ctx: &dyn ScFuncCallContext) -> DoNothingCall { DoNothingCall { func: ScFunc::new(HSC_NAME, HFUNC_DO_NOTHING), } } - pub fn get_minted_supply(_ctx: & dyn ScFuncCallContext) -> GetMintedSupplyCall { + pub fn get_minted_supply(_ctx: &dyn ScFuncCallContext) -> GetMintedSupplyCall { let mut f = GetMintedSupplyCall { func: ScFunc::new(HSC_NAME, HFUNC_GET_MINTED_SUPPLY), - results: ImmutableGetMintedSupplyResults { id: 0 }, + results: ImmutableGetMintedSupplyResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScFunc::link_results(&mut f.results.proxy, &f.func); f } - pub fn inc_counter(_ctx: & dyn ScFuncCallContext) -> IncCounterCall { + pub fn inc_counter(_ctx: &dyn ScFuncCallContext) -> IncCounterCall { IncCounterCall { func: ScFunc::new(HSC_NAME, HFUNC_INC_COUNTER), } } - pub fn init(_ctx: & dyn ScFuncCallContext) -> InitCall { + pub fn init(_ctx: &dyn ScFuncCallContext) -> InitCall { let mut f = InitCall { func: ScInitFunc::new(HSC_NAME, HFUNC_INIT), - params: MutableInitParams { id: 0 }, + params: MutableInitParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScInitFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn pass_types_full(_ctx: & dyn ScFuncCallContext) -> PassTypesFullCall { + pub fn pass_types_full(_ctx: &dyn ScFuncCallContext) -> PassTypesFullCall { let mut f = PassTypesFullCall { func: ScFunc::new(HSC_NAME, HFUNC_PASS_TYPES_FULL), - params: MutablePassTypesFullParams { id: 0 }, + params: MutablePassTypesFullParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn run_recursion(_ctx: & dyn ScFuncCallContext) -> RunRecursionCall { + pub fn run_recursion(_ctx: &dyn ScFuncCallContext) -> RunRecursionCall { let mut f = RunRecursionCall { func: ScFunc::new(HSC_NAME, HFUNC_RUN_RECURSION), - params: MutableRunRecursionParams { id: 0 }, - results: ImmutableRunRecursionResults { id: 0 }, + params: MutableRunRecursionParams { proxy: Proxy::nil() }, + results: ImmutableRunRecursionResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScFunc::link_params(&mut f.params.proxy, &f.func); + ScFunc::link_results(&mut f.results.proxy, &f.func); f } - pub fn send_to_address(_ctx: & dyn ScFuncCallContext) -> SendToAddressCall { + pub fn send_to_address(_ctx: &dyn ScFuncCallContext) -> SendToAddressCall { let mut f = SendToAddressCall { func: ScFunc::new(HSC_NAME, HFUNC_SEND_TO_ADDRESS), - params: MutableSendToAddressParams { id: 0 }, + params: MutableSendToAddressParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_int(_ctx: & dyn ScFuncCallContext) -> SetIntCall { + pub fn set_int(_ctx: &dyn ScFuncCallContext) -> SetIntCall { let mut f = SetIntCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_INT), - params: MutableSetIntParams { id: 0 }, + params: MutableSetIntParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn spawn(_ctx: & dyn ScFuncCallContext) -> SpawnCall { + pub fn spawn(_ctx: &dyn ScFuncCallContext) -> SpawnCall { let mut f = SpawnCall { func: ScFunc::new(HSC_NAME, HFUNC_SPAWN), - params: MutableSpawnParams { id: 0 }, + params: MutableSpawnParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn test_block_context1(_ctx: & dyn ScFuncCallContext) -> TestBlockContext1Call { + pub fn test_block_context1(_ctx: &dyn ScFuncCallContext) -> TestBlockContext1Call { TestBlockContext1Call { func: ScFunc::new(HSC_NAME, HFUNC_TEST_BLOCK_CONTEXT1), } } - pub fn test_block_context2(_ctx: & dyn ScFuncCallContext) -> TestBlockContext2Call { + pub fn test_block_context2(_ctx: &dyn ScFuncCallContext) -> TestBlockContext2Call { TestBlockContext2Call { func: ScFunc::new(HSC_NAME, HFUNC_TEST_BLOCK_CONTEXT2), } } - pub fn test_call_panic_full_ep(_ctx: & dyn ScFuncCallContext) -> TestCallPanicFullEPCall { + pub fn test_call_panic_full_ep(_ctx: &dyn ScFuncCallContext) -> TestCallPanicFullEPCall { TestCallPanicFullEPCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_CALL_PANIC_FULL_EP), } } - pub fn test_call_panic_view_ep_from_full(_ctx: & dyn ScFuncCallContext) -> TestCallPanicViewEPFromFullCall { + pub fn test_call_panic_view_ep_from_full(_ctx: &dyn ScFuncCallContext) -> TestCallPanicViewEPFromFullCall { TestCallPanicViewEPFromFullCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_CALL_PANIC_VIEW_EP_FROM_FULL), } } - pub fn test_chain_owner_id_full(_ctx: & dyn ScFuncCallContext) -> TestChainOwnerIDFullCall { + pub fn test_chain_owner_id_full(_ctx: &dyn ScFuncCallContext) -> TestChainOwnerIDFullCall { let mut f = TestChainOwnerIDFullCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_CHAIN_OWNER_ID_FULL), - results: ImmutableTestChainOwnerIDFullResults { id: 0 }, + results: ImmutableTestChainOwnerIDFullResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScFunc::link_results(&mut f.results.proxy, &f.func); f } - pub fn test_event_log_deploy(_ctx: & dyn ScFuncCallContext) -> TestEventLogDeployCall { + pub fn test_event_log_deploy(_ctx: &dyn ScFuncCallContext) -> TestEventLogDeployCall { TestEventLogDeployCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_EVENT_LOG_DEPLOY), } } - pub fn test_event_log_event_data(_ctx: & dyn ScFuncCallContext) -> TestEventLogEventDataCall { + pub fn test_event_log_event_data(_ctx: &dyn ScFuncCallContext) -> TestEventLogEventDataCall { TestEventLogEventDataCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_EVENT_LOG_EVENT_DATA), } } - pub fn test_event_log_generic_data(_ctx: & dyn ScFuncCallContext) -> TestEventLogGenericDataCall { + pub fn test_event_log_generic_data(_ctx: &dyn ScFuncCallContext) -> TestEventLogGenericDataCall { let mut f = TestEventLogGenericDataCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_EVENT_LOG_GENERIC_DATA), - params: MutableTestEventLogGenericDataParams { id: 0 }, + params: MutableTestEventLogGenericDataParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn test_panic_full_ep(_ctx: & dyn ScFuncCallContext) -> TestPanicFullEPCall { + pub fn test_panic_full_ep(_ctx: &dyn ScFuncCallContext) -> TestPanicFullEPCall { TestPanicFullEPCall { func: ScFunc::new(HSC_NAME, HFUNC_TEST_PANIC_FULL_EP), } } - pub fn withdraw_to_chain(_ctx: & dyn ScFuncCallContext) -> WithdrawToChainCall { + pub fn withdraw_to_chain(_ctx: &dyn ScFuncCallContext) -> WithdrawToChainCall { let mut f = WithdrawToChainCall { func: ScFunc::new(HSC_NAME, HFUNC_WITHDRAW_TO_CHAIN), - params: MutableWithdrawToChainParams { id: 0 }, + params: MutableWithdrawToChainParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn check_context_from_view_ep(_ctx: & dyn ScViewCallContext) -> CheckContextFromViewEPCall { + pub fn check_context_from_view_ep(_ctx: &dyn ScViewCallContext) -> CheckContextFromViewEPCall { let mut f = CheckContextFromViewEPCall { func: ScView::new(HSC_NAME, HVIEW_CHECK_CONTEXT_FROM_VIEW_EP), - params: MutableCheckContextFromViewEPParams { id: 0 }, + params: MutableCheckContextFromViewEPParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScView::link_params(&mut f.params.proxy, &f.func); f } - pub fn fibonacci(_ctx: & dyn ScViewCallContext) -> FibonacciCall { + pub fn fibonacci(_ctx: &dyn ScViewCallContext) -> FibonacciCall { let mut f = FibonacciCall { func: ScView::new(HSC_NAME, HVIEW_FIBONACCI), - params: MutableFibonacciParams { id: 0 }, - results: ImmutableFibonacciResults { id: 0 }, + params: MutableFibonacciParams { proxy: Proxy::nil() }, + results: ImmutableFibonacciResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_counter(_ctx: & dyn ScViewCallContext) -> GetCounterCall { + pub fn get_counter(_ctx: &dyn ScViewCallContext) -> GetCounterCall { let mut f = GetCounterCall { func: ScView::new(HSC_NAME, HVIEW_GET_COUNTER), - results: ImmutableGetCounterResults { id: 0 }, + results: ImmutableGetCounterResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_int(_ctx: & dyn ScViewCallContext) -> GetIntCall { + pub fn get_int(_ctx: &dyn ScViewCallContext) -> GetIntCall { let mut f = GetIntCall { func: ScView::new(HSC_NAME, HVIEW_GET_INT), - params: MutableGetIntParams { id: 0 }, - results: ImmutableGetIntResults { id: 0 }, + params: MutableGetIntParams { proxy: Proxy::nil() }, + results: ImmutableGetIntResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_string_value(_ctx: & dyn ScViewCallContext) -> GetStringValueCall { + pub fn get_string_value(_ctx: &dyn ScViewCallContext) -> GetStringValueCall { let mut f = GetStringValueCall { func: ScView::new(HSC_NAME, HVIEW_GET_STRING_VALUE), - params: MutableGetStringValueParams { id: 0 }, - results: ImmutableGetStringValueResults { id: 0 }, + params: MutableGetStringValueParams { proxy: Proxy::nil() }, + results: ImmutableGetStringValueResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn just_view(_ctx: & dyn ScViewCallContext) -> JustViewCall { + pub fn just_view(_ctx: &dyn ScViewCallContext) -> JustViewCall { JustViewCall { func: ScView::new(HSC_NAME, HVIEW_JUST_VIEW), } } - pub fn pass_types_view(_ctx: & dyn ScViewCallContext) -> PassTypesViewCall { + pub fn pass_types_view(_ctx: &dyn ScViewCallContext) -> PassTypesViewCall { let mut f = PassTypesViewCall { func: ScView::new(HSC_NAME, HVIEW_PASS_TYPES_VIEW), - params: MutablePassTypesViewParams { id: 0 }, + params: MutablePassTypesViewParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScView::link_params(&mut f.params.proxy, &f.func); f } - pub fn test_call_panic_view_ep_from_view(_ctx: & dyn ScViewCallContext) -> TestCallPanicViewEPFromViewCall { + pub fn test_call_panic_view_ep_from_view(_ctx: &dyn ScViewCallContext) -> TestCallPanicViewEPFromViewCall { TestCallPanicViewEPFromViewCall { func: ScView::new(HSC_NAME, HVIEW_TEST_CALL_PANIC_VIEW_EP_FROM_VIEW), } } - pub fn test_chain_owner_id_view(_ctx: & dyn ScViewCallContext) -> TestChainOwnerIDViewCall { + pub fn test_chain_owner_id_view(_ctx: &dyn ScViewCallContext) -> TestChainOwnerIDViewCall { let mut f = TestChainOwnerIDViewCall { func: ScView::new(HSC_NAME, HVIEW_TEST_CHAIN_OWNER_ID_VIEW), - results: ImmutableTestChainOwnerIDViewResults { id: 0 }, + results: ImmutableTestChainOwnerIDViewResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn test_panic_view_ep(_ctx: & dyn ScViewCallContext) -> TestPanicViewEPCall { + pub fn test_panic_view_ep(_ctx: &dyn ScViewCallContext) -> TestPanicViewEPCall { TestPanicViewEPCall { func: ScView::new(HSC_NAME, HVIEW_TEST_PANIC_VIEW_EP), } } - pub fn test_sandbox_call(_ctx: & dyn ScViewCallContext) -> TestSandboxCallCall { + pub fn test_sandbox_call(_ctx: &dyn ScViewCallContext) -> TestSandboxCallCall { let mut f = TestSandboxCallCall { func: ScView::new(HSC_NAME, HVIEW_TEST_SANDBOX_CALL), - results: ImmutableTestSandboxCallResults { id: 0 }, + results: ImmutableTestSandboxCallResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/testcore/src/keys.rs b/contracts/wasm/testcore/src/keys.rs deleted file mode 100644 index 3144450f06..0000000000 --- a/contracts/wasm/testcore/src/keys.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_ADDRESS : usize = 0; -pub(crate) const IDX_PARAM_AGENT_ID : usize = 1; -pub(crate) const IDX_PARAM_CALLER : usize = 2; -pub(crate) const IDX_PARAM_CHAIN_ID : usize = 3; -pub(crate) const IDX_PARAM_CHAIN_OWNER_ID : usize = 4; -pub(crate) const IDX_PARAM_CONTRACT_CREATOR : usize = 5; -pub(crate) const IDX_PARAM_CONTRACT_ID : usize = 6; -pub(crate) const IDX_PARAM_COUNTER : usize = 7; -pub(crate) const IDX_PARAM_FAIL : usize = 8; -pub(crate) const IDX_PARAM_HASH : usize = 9; -pub(crate) const IDX_PARAM_HNAME : usize = 10; -pub(crate) const IDX_PARAM_HNAME_CONTRACT : usize = 11; -pub(crate) const IDX_PARAM_HNAME_EP : usize = 12; -pub(crate) const IDX_PARAM_HNAME_ZERO : usize = 13; -pub(crate) const IDX_PARAM_INT64 : usize = 14; -pub(crate) const IDX_PARAM_INT64_ZERO : usize = 15; -pub(crate) const IDX_PARAM_INT_VALUE : usize = 16; -pub(crate) const IDX_PARAM_NAME : usize = 17; -pub(crate) const IDX_PARAM_PROG_HASH : usize = 18; -pub(crate) const IDX_PARAM_STRING : usize = 19; -pub(crate) const IDX_PARAM_STRING_ZERO : usize = 20; -pub(crate) const IDX_PARAM_VAR_NAME : usize = 21; - -pub(crate) const IDX_RESULT_CHAIN_OWNER_ID : usize = 22; -pub(crate) const IDX_RESULT_COUNTER : usize = 23; -pub(crate) const IDX_RESULT_INT_VALUE : usize = 24; -pub(crate) const IDX_RESULT_MINTED_COLOR : usize = 25; -pub(crate) const IDX_RESULT_MINTED_SUPPLY : usize = 26; -pub(crate) const IDX_RESULT_SANDBOX_CALL : usize = 27; -pub(crate) const IDX_RESULT_VALUES : usize = 28; -pub(crate) const IDX_RESULT_VARS : usize = 29; - -pub(crate) const IDX_STATE_COUNTER : usize = 30; -pub(crate) const IDX_STATE_HNAME_EP : usize = 31; -pub(crate) const IDX_STATE_INTS : usize = 32; -pub(crate) const IDX_STATE_MINTED_COLOR : usize = 33; -pub(crate) const IDX_STATE_MINTED_SUPPLY : usize = 34; - -pub const KEY_MAP_LEN: usize = 35; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_ADDRESS, - PARAM_AGENT_ID, - PARAM_CALLER, - PARAM_CHAIN_ID, - PARAM_CHAIN_OWNER_ID, - PARAM_CONTRACT_CREATOR, - PARAM_CONTRACT_ID, - PARAM_COUNTER, - PARAM_FAIL, - PARAM_HASH, - PARAM_HNAME, - PARAM_HNAME_CONTRACT, - PARAM_HNAME_EP, - PARAM_HNAME_ZERO, - PARAM_INT64, - PARAM_INT64_ZERO, - PARAM_INT_VALUE, - PARAM_NAME, - PARAM_PROG_HASH, - PARAM_STRING, - PARAM_STRING_ZERO, - PARAM_VAR_NAME, - RESULT_CHAIN_OWNER_ID, - RESULT_COUNTER, - RESULT_INT_VALUE, - RESULT_MINTED_COLOR, - RESULT_MINTED_SUPPLY, - RESULT_SANDBOX_CALL, - RESULT_VALUES, - RESULT_VARS, - STATE_COUNTER, - STATE_HNAME_EP, - STATE_INTS, - STATE_MINTED_COLOR, - STATE_MINTED_SUPPLY, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/testcore/src/lib.rs b/contracts/wasm/testcore/src/lib.rs index d9e65ea0ae..82d2fa4adb 100644 --- a/contracts/wasm/testcore/src/lib.rs +++ b/contracts/wasm/testcore/src/lib.rs @@ -10,63 +10,101 @@ use testcore::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; mod consts; mod contract; -mod keys; mod params; mod results; mod state; + mod testcore; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_CALL_ON_CHAIN, + FUNC_CHECK_CONTEXT_FROM_FULL_EP, + FUNC_DO_NOTHING, + FUNC_GET_MINTED_SUPPLY, + FUNC_INC_COUNTER, + FUNC_INIT, + FUNC_PASS_TYPES_FULL, + FUNC_RUN_RECURSION, + FUNC_SEND_TO_ADDRESS, + FUNC_SET_INT, + FUNC_SPAWN, + FUNC_TEST_BLOCK_CONTEXT1, + FUNC_TEST_BLOCK_CONTEXT2, + FUNC_TEST_CALL_PANIC_FULL_EP, + FUNC_TEST_CALL_PANIC_VIEW_EP_FROM_FULL, + FUNC_TEST_CHAIN_OWNER_ID_FULL, + FUNC_TEST_EVENT_LOG_DEPLOY, + FUNC_TEST_EVENT_LOG_EVENT_DATA, + FUNC_TEST_EVENT_LOG_GENERIC_DATA, + FUNC_TEST_PANIC_FULL_EP, + FUNC_WITHDRAW_TO_CHAIN, + VIEW_CHECK_CONTEXT_FROM_VIEW_EP, + VIEW_FIBONACCI, + VIEW_GET_COUNTER, + VIEW_GET_INT, + VIEW_GET_STRING_VALUE, + VIEW_JUST_VIEW, + VIEW_PASS_TYPES_VIEW, + VIEW_TEST_CALL_PANIC_VIEW_EP_FROM_VIEW, + VIEW_TEST_CHAIN_OWNER_ID_VIEW, + VIEW_TEST_PANIC_VIEW_EP, + VIEW_TEST_SANDBOX_CALL, + ], + funcs: &[ + func_call_on_chain_thunk, + func_check_context_from_full_ep_thunk, + func_do_nothing_thunk, + func_get_minted_supply_thunk, + func_inc_counter_thunk, + func_init_thunk, + func_pass_types_full_thunk, + func_run_recursion_thunk, + func_send_to_address_thunk, + func_set_int_thunk, + func_spawn_thunk, + func_test_block_context1_thunk, + func_test_block_context2_thunk, + func_test_call_panic_full_ep_thunk, + func_test_call_panic_view_ep_from_full_thunk, + func_test_chain_owner_id_full_thunk, + func_test_event_log_deploy_thunk, + func_test_event_log_event_data_thunk, + func_test_event_log_generic_data_thunk, + func_test_panic_full_ep_thunk, + func_withdraw_to_chain_thunk, + ], + views: &[ + view_check_context_from_view_ep_thunk, + view_fibonacci_thunk, + view_get_counter_thunk, + view_get_int_thunk, + view_get_string_value_thunk, + view_just_view_thunk, + view_pass_types_view_thunk, + view_test_call_panic_view_ep_from_view_thunk, + view_test_chain_owner_id_view_thunk, + view_test_panic_view_ep_thunk, + view_test_sandbox_call_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_CALL_ON_CHAIN, func_call_on_chain_thunk); - exports.add_func(FUNC_CHECK_CONTEXT_FROM_FULL_EP, func_check_context_from_full_ep_thunk); - exports.add_func(FUNC_DO_NOTHING, func_do_nothing_thunk); - exports.add_func(FUNC_GET_MINTED_SUPPLY, func_get_minted_supply_thunk); - exports.add_func(FUNC_INC_COUNTER, func_inc_counter_thunk); - exports.add_func(FUNC_INIT, func_init_thunk); - exports.add_func(FUNC_PASS_TYPES_FULL, func_pass_types_full_thunk); - exports.add_func(FUNC_RUN_RECURSION, func_run_recursion_thunk); - exports.add_func(FUNC_SEND_TO_ADDRESS, func_send_to_address_thunk); - exports.add_func(FUNC_SET_INT, func_set_int_thunk); - exports.add_func(FUNC_SPAWN, func_spawn_thunk); - exports.add_func(FUNC_TEST_BLOCK_CONTEXT1, func_test_block_context1_thunk); - exports.add_func(FUNC_TEST_BLOCK_CONTEXT2, func_test_block_context2_thunk); - exports.add_func(FUNC_TEST_CALL_PANIC_FULL_EP, func_test_call_panic_full_ep_thunk); - exports.add_func(FUNC_TEST_CALL_PANIC_VIEW_EP_FROM_FULL, func_test_call_panic_view_ep_from_full_thunk); - exports.add_func(FUNC_TEST_CHAIN_OWNER_ID_FULL, func_test_chain_owner_id_full_thunk); - exports.add_func(FUNC_TEST_EVENT_LOG_DEPLOY, func_test_event_log_deploy_thunk); - exports.add_func(FUNC_TEST_EVENT_LOG_EVENT_DATA, func_test_event_log_event_data_thunk); - exports.add_func(FUNC_TEST_EVENT_LOG_GENERIC_DATA, func_test_event_log_generic_data_thunk); - exports.add_func(FUNC_TEST_PANIC_FULL_EP, func_test_panic_full_ep_thunk); - exports.add_func(FUNC_WITHDRAW_TO_CHAIN, func_withdraw_to_chain_thunk); - exports.add_view(VIEW_CHECK_CONTEXT_FROM_VIEW_EP, view_check_context_from_view_ep_thunk); - exports.add_view(VIEW_FIBONACCI, view_fibonacci_thunk); - exports.add_view(VIEW_GET_COUNTER, view_get_counter_thunk); - exports.add_view(VIEW_GET_INT, view_get_int_thunk); - exports.add_view(VIEW_GET_STRING_VALUE, view_get_string_value_thunk); - exports.add_view(VIEW_JUST_VIEW, view_just_view_thunk); - exports.add_view(VIEW_PASS_TYPES_VIEW, view_pass_types_view_thunk); - exports.add_view(VIEW_TEST_CALL_PANIC_VIEW_EP_FROM_VIEW, view_test_call_panic_view_ep_from_view_thunk); - exports.add_view(VIEW_TEST_CHAIN_OWNER_ID_VIEW, view_test_chain_owner_id_view_thunk); - exports.add_view(VIEW_TEST_PANIC_VIEW_EP, view_test_panic_view_ep_thunk); - exports.add_view(VIEW_TEST_SANDBOX_CALL, view_test_sandbox_call_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct CallOnChainContext { @@ -78,18 +116,13 @@ pub struct CallOnChainContext { fn func_call_on_chain_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcCallOnChain"); let f = CallOnChainContext { - params: ImmutableCallOnChainParams { - id: OBJ_ID_PARAMS, - }, - results: MutableCallOnChainResults { - id: OBJ_ID_RESULTS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableCallOnChainParams { proxy: params_proxy() }, + results: MutableCallOnChainResults { proxy: results_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.int_value().exists(), "missing mandatory intValue"); func_call_on_chain(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.funcCallOnChain ok"); } @@ -101,12 +134,8 @@ pub struct CheckContextFromFullEPContext { fn func_check_context_from_full_ep_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcCheckContextFromFullEP"); let f = CheckContextFromFullEPContext { - params: ImmutableCheckContextFromFullEPParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableCheckContextFromFullEPParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.agent_id().exists(), "missing mandatory agentID"); ctx.require(f.params.caller().exists(), "missing mandatory caller"); @@ -124,9 +153,7 @@ pub struct DoNothingContext { fn func_do_nothing_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcDoNothing"); let f = DoNothingContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_do_nothing(ctx, &f); ctx.log("testcore.funcDoNothing ok"); @@ -140,14 +167,11 @@ pub struct GetMintedSupplyContext { fn func_get_minted_supply_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcGetMintedSupply"); let f = GetMintedSupplyContext { - results: MutableGetMintedSupplyResults { - id: OBJ_ID_RESULTS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + results: MutableGetMintedSupplyResults { proxy: results_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_get_minted_supply(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.funcGetMintedSupply ok"); } @@ -158,9 +182,7 @@ pub struct IncCounterContext { fn func_inc_counter_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcIncCounter"); let f = IncCounterContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_inc_counter(ctx, &f); ctx.log("testcore.funcIncCounter ok"); @@ -174,12 +196,8 @@ pub struct InitContext { fn func_init_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcInit"); let f = InitContext { - params: ImmutableInitParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableInitParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_init(ctx, &f); ctx.log("testcore.funcInit ok"); @@ -193,12 +211,8 @@ pub struct PassTypesFullContext { fn func_pass_types_full_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcPassTypesFull"); let f = PassTypesFullContext { - params: ImmutablePassTypesFullParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutablePassTypesFullParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.agent_id().exists(), "missing mandatory agentID"); @@ -224,18 +238,13 @@ pub struct RunRecursionContext { fn func_run_recursion_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcRunRecursion"); let f = RunRecursionContext { - params: ImmutableRunRecursionParams { - id: OBJ_ID_PARAMS, - }, - results: MutableRunRecursionResults { - id: OBJ_ID_RESULTS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableRunRecursionParams { proxy: params_proxy() }, + results: MutableRunRecursionResults { proxy: results_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.int_value().exists(), "missing mandatory intValue"); func_run_recursion(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.funcRunRecursion ok"); } @@ -246,16 +255,12 @@ pub struct SendToAddressContext { fn func_send_to_address_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcSendToAddress"); - ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = SendToAddressContext { - params: ImmutableSendToAddressParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableSendToAddressParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; + ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); + ctx.require(f.params.address().exists(), "missing mandatory address"); func_send_to_address(ctx, &f); ctx.log("testcore.funcSendToAddress ok"); @@ -269,12 +274,8 @@ pub struct SetIntContext { fn func_set_int_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcSetInt"); let f = SetIntContext { - params: ImmutableSetIntParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableSetIntParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.int_value().exists(), "missing mandatory intValue"); ctx.require(f.params.name().exists(), "missing mandatory name"); @@ -290,12 +291,8 @@ pub struct SpawnContext { fn func_spawn_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcSpawn"); let f = SpawnContext { - params: ImmutableSpawnParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableSpawnParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.prog_hash().exists(), "missing mandatory progHash"); func_spawn(ctx, &f); @@ -309,9 +306,7 @@ pub struct TestBlockContext1Context { fn func_test_block_context1_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestBlockContext1"); let f = TestBlockContext1Context { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_block_context1(ctx, &f); ctx.log("testcore.funcTestBlockContext1 ok"); @@ -324,9 +319,7 @@ pub struct TestBlockContext2Context { fn func_test_block_context2_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestBlockContext2"); let f = TestBlockContext2Context { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_block_context2(ctx, &f); ctx.log("testcore.funcTestBlockContext2 ok"); @@ -339,9 +332,7 @@ pub struct TestCallPanicFullEPContext { fn func_test_call_panic_full_ep_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestCallPanicFullEP"); let f = TestCallPanicFullEPContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_call_panic_full_ep(ctx, &f); ctx.log("testcore.funcTestCallPanicFullEP ok"); @@ -354,9 +345,7 @@ pub struct TestCallPanicViewEPFromFullContext { fn func_test_call_panic_view_ep_from_full_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestCallPanicViewEPFromFull"); let f = TestCallPanicViewEPFromFullContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_call_panic_view_ep_from_full(ctx, &f); ctx.log("testcore.funcTestCallPanicViewEPFromFull ok"); @@ -370,14 +359,11 @@ pub struct TestChainOwnerIDFullContext { fn func_test_chain_owner_id_full_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestChainOwnerIDFull"); let f = TestChainOwnerIDFullContext { - results: MutableTestChainOwnerIDFullResults { - id: OBJ_ID_RESULTS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + results: MutableTestChainOwnerIDFullResults { proxy: results_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_chain_owner_id_full(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.funcTestChainOwnerIDFull ok"); } @@ -388,9 +374,7 @@ pub struct TestEventLogDeployContext { fn func_test_event_log_deploy_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestEventLogDeploy"); let f = TestEventLogDeployContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_event_log_deploy(ctx, &f); ctx.log("testcore.funcTestEventLogDeploy ok"); @@ -403,9 +387,7 @@ pub struct TestEventLogEventDataContext { fn func_test_event_log_event_data_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestEventLogEventData"); let f = TestEventLogEventDataContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_event_log_event_data(ctx, &f); ctx.log("testcore.funcTestEventLogEventData ok"); @@ -419,12 +401,8 @@ pub struct TestEventLogGenericDataContext { fn func_test_event_log_generic_data_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestEventLogGenericData"); let f = TestEventLogGenericDataContext { - params: ImmutableTestEventLogGenericDataParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableTestEventLogGenericDataParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.counter().exists(), "missing mandatory counter"); func_test_event_log_generic_data(ctx, &f); @@ -438,9 +416,7 @@ pub struct TestPanicFullEPContext { fn func_test_panic_full_ep_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcTestPanicFullEP"); let f = TestPanicFullEPContext { - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: MutableTestCoreState { proxy: state_proxy() }, }; func_test_panic_full_ep(ctx, &f); ctx.log("testcore.funcTestPanicFullEP ok"); @@ -454,12 +430,8 @@ pub struct WithdrawToChainContext { fn func_withdraw_to_chain_thunk(ctx: &ScFuncContext) { ctx.log("testcore.funcWithdrawToChain"); let f = WithdrawToChainContext { - params: ImmutableWithdrawToChainParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableWithdrawToChainParams { proxy: params_proxy() }, + state: MutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.chain_id().exists(), "missing mandatory chainID"); func_withdraw_to_chain(ctx, &f); @@ -474,12 +446,8 @@ pub struct CheckContextFromViewEPContext { fn view_check_context_from_view_ep_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewCheckContextFromViewEP"); let f = CheckContextFromViewEPContext { - params: ImmutableCheckContextFromViewEPParams { - id: OBJ_ID_PARAMS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableCheckContextFromViewEPParams { proxy: params_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.agent_id().exists(), "missing mandatory agentID"); ctx.require(f.params.chain_id().exists(), "missing mandatory chainID"); @@ -498,18 +466,13 @@ pub struct FibonacciContext { fn view_fibonacci_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewFibonacci"); let f = FibonacciContext { - params: ImmutableFibonacciParams { - id: OBJ_ID_PARAMS, - }, - results: MutableFibonacciResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableFibonacciParams { proxy: params_proxy() }, + results: MutableFibonacciResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.int_value().exists(), "missing mandatory intValue"); view_fibonacci(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewFibonacci ok"); } @@ -521,14 +484,11 @@ pub struct GetCounterContext { fn view_get_counter_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewGetCounter"); let f = GetCounterContext { - results: MutableGetCounterResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + results: MutableGetCounterResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_get_counter(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewGetCounter ok"); } @@ -541,18 +501,13 @@ pub struct GetIntContext { fn view_get_int_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewGetInt"); let f = GetIntContext { - params: ImmutableGetIntParams { - id: OBJ_ID_PARAMS, - }, - results: MutableGetIntResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableGetIntParams { proxy: params_proxy() }, + results: MutableGetIntResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); view_get_int(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewGetInt ok"); } @@ -565,18 +520,13 @@ pub struct GetStringValueContext { fn view_get_string_value_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewGetStringValue"); let f = GetStringValueContext { - params: ImmutableGetStringValueParams { - id: OBJ_ID_PARAMS, - }, - results: MutableGetStringValueResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutableGetStringValueParams { proxy: params_proxy() }, + results: MutableGetStringValueResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.var_name().exists(), "missing mandatory varName"); view_get_string_value(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewGetStringValue ok"); } @@ -587,9 +537,7 @@ pub struct JustViewContext { fn view_just_view_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewJustView"); let f = JustViewContext { - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_just_view(ctx, &f); ctx.log("testcore.viewJustView ok"); @@ -603,12 +551,8 @@ pub struct PassTypesViewContext { fn view_pass_types_view_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewPassTypesView"); let f = PassTypesViewContext { - params: ImmutablePassTypesViewParams { - id: OBJ_ID_PARAMS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + params: ImmutablePassTypesViewParams { proxy: params_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.agent_id().exists(), "missing mandatory agentID"); @@ -632,9 +576,7 @@ pub struct TestCallPanicViewEPFromViewContext { fn view_test_call_panic_view_ep_from_view_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewTestCallPanicViewEPFromView"); let f = TestCallPanicViewEPFromViewContext { - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_test_call_panic_view_ep_from_view(ctx, &f); ctx.log("testcore.viewTestCallPanicViewEPFromView ok"); @@ -648,14 +590,11 @@ pub struct TestChainOwnerIDViewContext { fn view_test_chain_owner_id_view_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewTestChainOwnerIDView"); let f = TestChainOwnerIDViewContext { - results: MutableTestChainOwnerIDViewResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + results: MutableTestChainOwnerIDViewResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_test_chain_owner_id_view(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewTestChainOwnerIDView ok"); } @@ -666,9 +605,7 @@ pub struct TestPanicViewEPContext { fn view_test_panic_view_ep_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewTestPanicViewEP"); let f = TestPanicViewEPContext { - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_test_panic_view_ep(ctx, &f); ctx.log("testcore.viewTestPanicViewEP ok"); @@ -682,13 +619,10 @@ pub struct TestSandboxCallContext { fn view_test_sandbox_call_thunk(ctx: &ScViewContext) { ctx.log("testcore.viewTestSandboxCall"); let f = TestSandboxCallContext { - results: MutableTestSandboxCallResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestCoreState { - id: OBJ_ID_STATE, - }, + results: MutableTestSandboxCallResults { proxy: results_proxy() }, + state: ImmutableTestCoreState { proxy: state_proxy() }, }; view_test_sandbox_call(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testcore.viewTestSandboxCall ok"); } diff --git a/contracts/wasm/testcore/src/params.rs b/contracts/wasm/testcore/src/params.rs index 50c879a7fc..99cf759fd5 100644 --- a/contracts/wasm/testcore/src/params.rs +++ b/contracts/wasm/testcore/src/params.rs @@ -9,577 +9,574 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableCallOnChainParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableCallOnChainParams { pub fn hname_contract(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME_CONTRACT.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME_CONTRACT)) } pub fn hname_ep(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME_EP.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME_EP)) } pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableCallOnChainParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableCallOnChainParams { pub fn hname_contract(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME_CONTRACT.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME_CONTRACT)) } pub fn hname_ep(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME_EP.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME_EP)) } pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableCheckContextFromFullEPParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableCheckContextFromFullEPParams { pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn caller(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CALLER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CALLER)) } pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn chain_owner_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CHAIN_OWNER_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER_ID)) } pub fn contract_creator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CONTRACT_CREATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CONTRACT_CREATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableCheckContextFromFullEPParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableCheckContextFromFullEPParams { pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn caller(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CALLER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CALLER)) } pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn chain_owner_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CHAIN_OWNER_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER_ID)) } pub fn contract_creator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CONTRACT_CREATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CONTRACT_CREATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableInitParams { pub fn fail(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, idx_map(IDX_PARAM_FAIL)) + ScImmutableInt64::new(self.proxy.root(PARAM_FAIL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableInitParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableInitParams { pub fn fail(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, idx_map(IDX_PARAM_FAIL)) + ScMutableInt64::new(self.proxy.root(PARAM_FAIL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutablePassTypesFullParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutablePassTypesFullParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn contract_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CONTRACT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CONTRACT_ID)) } pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn hname_zero(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME_ZERO.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME_ZERO)) } pub fn int64(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int64_zero(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT64_ZERO.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT64_ZERO)) } pub fn string(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_STRING.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_STRING)) } pub fn string_zero(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_STRING_ZERO.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_STRING_ZERO)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutablePassTypesFullParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutablePassTypesFullParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn contract_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CONTRACT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CONTRACT_ID)) } pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn hname_zero(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME_ZERO.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME_ZERO)) } pub fn int64(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int64_zero(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT64_ZERO.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT64_ZERO)) } pub fn string(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_STRING.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_STRING)) } pub fn string_zero(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_STRING_ZERO.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_STRING_ZERO)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRunRecursionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRunRecursionParams { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRunRecursionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRunRecursionParams { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSendToAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSendToAddressParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSendToAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSendToAddressParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetIntParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetIntParams { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetIntParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetIntParams { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSpawnParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSpawnParams { pub fn prog_hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_PROG_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_PROG_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSpawnParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSpawnParams { pub fn prog_hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_PROG_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_PROG_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestEventLogGenericDataParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestEventLogGenericDataParams { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_COUNTER.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestEventLogGenericDataParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestEventLogGenericDataParams { pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_COUNTER.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableWithdrawToChainParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableWithdrawToChainParams { pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableWithdrawToChainParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableWithdrawToChainParams { pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableCheckContextFromViewEPParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableCheckContextFromViewEPParams { pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn chain_owner_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CHAIN_OWNER_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER_ID)) } pub fn contract_creator(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CONTRACT_CREATOR.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CONTRACT_CREATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableCheckContextFromViewEPParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableCheckContextFromViewEPParams { pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn chain_owner_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CHAIN_OWNER_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER_ID)) } pub fn contract_creator(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CONTRACT_CREATOR.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CONTRACT_CREATOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFibonacciParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFibonacciParams { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFibonacciParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFibonacciParams { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetIntParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetIntParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetIntParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetIntParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetStringValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetStringValueParams { pub fn var_name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_VAR_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_VAR_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetStringValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetStringValueParams { pub fn var_name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_VAR_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_VAR_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutablePassTypesViewParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutablePassTypesViewParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn contract_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CONTRACT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CONTRACT_ID)) } pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn hname_zero(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME_ZERO.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME_ZERO)) } pub fn int64(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int64_zero(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT64_ZERO.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT64_ZERO)) } pub fn string(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_STRING.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_STRING)) } pub fn string_zero(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_STRING_ZERO.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_STRING_ZERO)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutablePassTypesViewParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutablePassTypesViewParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn contract_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CONTRACT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CONTRACT_ID)) } pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn hname_zero(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME_ZERO.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME_ZERO)) } pub fn int64(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int64_zero(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT64_ZERO.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT64_ZERO)) } pub fn string(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_STRING.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_STRING)) } pub fn string_zero(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_STRING_ZERO.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_STRING_ZERO)) } } diff --git a/contracts/wasm/testcore/src/results.rs b/contracts/wasm/testcore/src/results.rs index a0380fbbfa..9beefe60d0 100644 --- a/contracts/wasm/testcore/src/results.rs +++ b/contracts/wasm/testcore/src/results.rs @@ -9,287 +9,284 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableCallOnChainResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableCallOnChainResults { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableCallOnChainResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableCallOnChainResults { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetMintedSupplyResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetMintedSupplyResults { pub fn minted_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, RESULT_MINTED_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(RESULT_MINTED_COLOR)) } - pub fn minted_supply(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_MINTED_SUPPLY.get_key_id()) + pub fn minted_supply(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_MINTED_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetMintedSupplyResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetMintedSupplyResults { pub fn minted_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, RESULT_MINTED_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(RESULT_MINTED_COLOR)) } - pub fn minted_supply(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_MINTED_SUPPLY.get_key_id()) + pub fn minted_supply(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_MINTED_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRunRecursionResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRunRecursionResults { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRunRecursionResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRunRecursionResults { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestChainOwnerIDFullResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestChainOwnerIDFullResults { pub fn chain_owner_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestChainOwnerIDFullResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestChainOwnerIDFullResults { pub fn chain_owner_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFibonacciResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFibonacciResults { pub fn int_value(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFibonacciResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFibonacciResults { pub fn int_value(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_INT_VALUE.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_INT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetCounterResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetCounterResults { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_COUNTER.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetCounterResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetCounterResults { pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_COUNTER.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_COUNTER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableInt64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableInt64 { pub fn get_int64(&self, key: &str) -> ScImmutableInt64 { - ScImmutableInt64::new(self.obj_id, key.get_key_id()) + ScImmutableInt64::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetIntResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetIntResults { pub fn values(&self) -> MapStringToImmutableInt64 { - MapStringToImmutableInt64 { obj_id: self.id } + MapStringToImmutableInt64 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableInt64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableInt64 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_int64(&self, key: &str) -> ScMutableInt64 { - ScMutableInt64::new(self.obj_id, key.get_key_id()) + ScMutableInt64::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetIntResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetIntResults { pub fn values(&self) -> MapStringToMutableInt64 { - MapStringToMutableInt64 { obj_id: self.id } + MapStringToMutableInt64 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableString { pub fn get_string(&self, key: &str) -> ScImmutableString { - ScImmutableString::new(self.obj_id, key.get_key_id()) + ScImmutableString::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetStringValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetStringValueResults { pub fn vars(&self) -> MapStringToImmutableString { - MapStringToImmutableString { obj_id: self.id } + MapStringToImmutableString { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableString { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_string(&self, key: &str) -> ScMutableString { - ScMutableString::new(self.obj_id, key.get_key_id()) + ScMutableString::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetStringValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetStringValueResults { pub fn vars(&self) -> MapStringToMutableString { - MapStringToMutableString { obj_id: self.id } + MapStringToMutableString { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestChainOwnerIDViewResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestChainOwnerIDViewResults { pub fn chain_owner_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestChainOwnerIDViewResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestChainOwnerIDViewResults { pub fn chain_owner_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestSandboxCallResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestSandboxCallResults { pub fn sandbox_call(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_SANDBOX_CALL.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_SANDBOX_CALL)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestSandboxCallResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestSandboxCallResults { pub fn sandbox_call(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_SANDBOX_CALL.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_SANDBOX_CALL)) } } diff --git a/contracts/wasm/testcore/src/state.rs b/contracts/wasm/testcore/src/state.rs index 464c4e0aa9..2322594c6c 100644 --- a/contracts/wasm/testcore/src/state.rs +++ b/contracts/wasm/testcore/src/state.rs @@ -9,67 +9,63 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestCoreState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestCoreState { pub fn counter(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_COUNTER.get_key_id()) + ScImmutableInt64::new(self.proxy.root(STATE_COUNTER)) } pub fn hname_ep(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, STATE_HNAME_EP.get_key_id()) + ScImmutableHname::new(self.proxy.root(STATE_HNAME_EP)) } pub fn ints(&self) -> MapStringToImmutableInt64 { - let map_id = get_object_id(self.id, STATE_INTS.get_key_id(), TYPE_MAP); - MapStringToImmutableInt64 { obj_id: map_id } + MapStringToImmutableInt64 { proxy: self.proxy.root(STATE_INTS) } } pub fn minted_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, STATE_MINTED_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(STATE_MINTED_COLOR)) } - pub fn minted_supply(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_MINTED_SUPPLY.get_key_id()) + pub fn minted_supply(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_MINTED_SUPPLY)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestCoreState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestCoreState { pub fn as_immutable(&self) -> ImmutableTestCoreState { - ImmutableTestCoreState { id: self.id } + ImmutableTestCoreState { proxy: self.proxy.root("") } } pub fn counter(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_COUNTER.get_key_id()) + ScMutableInt64::new(self.proxy.root(STATE_COUNTER)) } pub fn hname_ep(&self) -> ScMutableHname { - ScMutableHname::new(self.id, STATE_HNAME_EP.get_key_id()) + ScMutableHname::new(self.proxy.root(STATE_HNAME_EP)) } pub fn ints(&self) -> MapStringToMutableInt64 { - let map_id = get_object_id(self.id, STATE_INTS.get_key_id(), TYPE_MAP); - MapStringToMutableInt64 { obj_id: map_id } + MapStringToMutableInt64 { proxy: self.proxy.root(STATE_INTS) } } pub fn minted_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, STATE_MINTED_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(STATE_MINTED_COLOR)) } - pub fn minted_supply(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_MINTED_SUPPLY.get_key_id()) + pub fn minted_supply(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_MINTED_SUPPLY)) } } diff --git a/contracts/wasm/testcore/src/testcore.rs b/contracts/wasm/testcore/src/testcore.rs index 645f8fd803..aacb6bb788 100644 --- a/contracts/wasm/testcore/src/testcore.rs +++ b/contracts/wasm/testcore/src/testcore.rs @@ -33,11 +33,12 @@ pub fn func_call_on_chain(ctx: &ScFuncContext, f: &CallOnChainContext) { counter.set_value(counter.value() + 1); - let parms = ScMutableMap::new(); - parms.get_int64(PARAM_INT_VALUE).set_value(param_int); + let parms = ScDict::new(&[]); + let key = string_to_bytes(PARAM_INT_VALUE); + parms.set(&key, &int64_to_bytes(param_int)); let ret = ctx.call(hname_contract, hname_ep, Some(parms), None); - let ret_val = ret.get_int64(RESULT_INT_VALUE); - f.results.int_value().set_value(ret_val.value()); + let ret_val = int64_from_bytes(&ret.get(&key)); + f.results.int_value().set_value(ret_val); } pub fn func_check_context_from_full_ep(ctx: &ScFuncContext, f: &CheckContextFromFullEPContext) { @@ -55,8 +56,8 @@ pub fn func_do_nothing(ctx: &ScFuncContext, _f: &DoNothingContext) { pub fn func_get_minted_supply(ctx: &ScFuncContext, f: &GetMintedSupplyContext) { let minted = ctx.minted(); let minted_colors = minted.colors(); - ctx.require(minted_colors.length() == 1, "test only supports one minted color"); - let color = minted_colors.get_color(0).value(); + ctx.require(minted_colors.len() == 1, "test only supports one minted color"); + let color = minted_colors.get(0).unwrap(); let amount = minted.balance(&color); f.results.minted_supply().set_value(amount); f.results.minted_color().set_value(&color); @@ -80,7 +81,7 @@ pub fn func_pass_types_full(ctx: &ScFuncContext, f: &PassTypesFullContext) { ctx.require(f.params.int64_zero().value() == 0, "int64-0 wrong"); ctx.require(f.params.string().value() == PARAM_STRING, "string wrong"); ctx.require(f.params.string_zero().value() == "", "string-0 wrong"); - ctx.require(f.params.hname().value() == ScHname::new(PARAM_HNAME), "Hname wrong"); + ctx.require(f.params.hname().value() == ctx.utility().hash_name(PARAM_HNAME), "Hname wrong"); ctx.require(f.params.hname_zero().value() == ScHname(0), "Hname-0 wrong"); } @@ -110,9 +111,9 @@ pub fn func_set_int(_ctx: &ScFuncContext, f: &SetIntContext) { pub fn func_spawn(ctx: &ScFuncContext, f: &SpawnContext) { let spawn_name = SC_NAME.to_string() + "_spawned"; let spawn_descr = "spawned contract description"; - ctx.deploy(&f.params.prog_hash().value(), &spawn_name, spawn_descr, None); + ctx.deploy_contract(&f.params.prog_hash().value(), &spawn_name, spawn_descr, None); - let spawn_hname = ScHname::new(&spawn_name); + let spawn_hname = ctx.utility().hash_name(&spawn_name); for _i in 0..5 { ctx.call(spawn_hname, HFUNC_INC_COUNTER, None, None); } @@ -141,7 +142,7 @@ pub fn func_test_chain_owner_id_full(ctx: &ScFuncContext, f: &TestChainOwnerIDFu pub fn func_test_event_log_deploy(ctx: &ScFuncContext, _f: &TestEventLogDeployContext) { // deploy the same contract with another name let program_hash = ctx.utility().hash_blake2b("testcore".as_bytes()); - ctx.deploy(&program_hash, CONTRACT_NAME_DEPLOYED, "test contract deploy log", None); + ctx.deploy_contract(&program_hash, CONTRACT_NAME_DEPLOYED, "test contract deploy log", None); } pub fn func_test_event_log_event_data(ctx: &ScFuncContext, _f: &TestEventLogEventDataContext) { @@ -159,7 +160,7 @@ pub fn func_test_panic_full_ep(ctx: &ScFuncContext, _f: &TestPanicFullEPContext) pub fn func_withdraw_to_chain(ctx: &ScFuncContext, f: &WithdrawToChainContext) { let xx = coreaccounts::ScFuncs::withdraw(ctx); - xx.func.transfer_iotas(1).post_to_chain(f.params.chain_id().value()); + xx.func.post_to_chain(f.params.chain_id().value()); } pub fn view_check_context_from_view_ep(ctx: &ScViewContext, f: &CheckContextFromViewEPContext) { @@ -214,7 +215,7 @@ pub fn view_pass_types_view(ctx: &ScViewContext, f: &PassTypesViewContext) { ctx.require(f.params.int64_zero().value() == 0, "int64-0 wrong"); ctx.require(f.params.string().value() == PARAM_STRING, "string wrong"); ctx.require(f.params.string_zero().value() == "", "string-0 wrong"); - ctx.require(f.params.hname().value() == ScHname::new(PARAM_HNAME), "Hname wrong"); + ctx.require(f.params.hname().value() == ctx.utility().hash_name(PARAM_HNAME), "Hname wrong"); ctx.require(f.params.hname_zero().value() == ScHname(0), "Hname-0 wrong"); } diff --git a/contracts/wasm/testcore/test/2chains_test.go b/contracts/wasm/testcore/test/2chains_test.go index 633808182a..957fc83cf2 100644 --- a/contracts/wasm/testcore/test/2chains_test.go +++ b/contracts/wasm/testcore/test/2chains_test.go @@ -6,7 +6,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" "github.com/iotaledger/wasp/packages/solo" "github.com/iotaledger/wasp/packages/vm/core" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -14,7 +14,10 @@ func Test2Chains(t *testing.T) { run2(t, func(t *testing.T, w bool) { core.PrintWellKnownHnames() + save := wasmsolo.SoloSeed + wasmsolo.SoloSeed = nil chain1 := wasmsolo.StartChain(t, "chain1") + wasmsolo.SoloSeed = save chain1.CheckAccountLedger() chain2 := wasmsolo.StartChain(t, "chain2", chain1.Env) @@ -53,7 +56,7 @@ func Test2Chains(t *testing.T) { f := testcore.ScFuncs.WithdrawToChain(ctx2.Sign(user)) f.Params.ChainID().SetValue(ctx1.ChainID()) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx2.Err) require.True(t, ctx1.WaitForPendingRequests(1)) diff --git a/contracts/wasm/testcore/test/block_context_test.go b/contracts/wasm/testcore/test/block_context_test.go index 277f65d7d5..61bd696f45 100644 --- a/contracts/wasm/testcore/test/block_context_test.go +++ b/contracts/wasm/testcore/test/block_context_test.go @@ -11,7 +11,7 @@ func TestBasicBlockContext1(t *testing.T) { ctx := deployTestCore(t, false) f := testcore.ScFuncs.TestBlockContext1(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) } @@ -19,7 +19,7 @@ func TestBasicBlockContext2(t *testing.T) { ctx := deployTestCore(t, false) f := testcore.ScFuncs.TestBlockContext2(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) v := testcore.ScFuncs.GetStringValue(ctx) diff --git a/contracts/wasm/testcore/test/call_test.go b/contracts/wasm/testcore/test/call_test.go index 3221726f21..eadda8bbc8 100644 --- a/contracts/wasm/testcore/test/call_test.go +++ b/contracts/wasm/testcore/test/call_test.go @@ -38,7 +38,7 @@ func TestCallFibonacciIndirect(t *testing.T) { f.Params.IntValue().SetValue(fiboN) f.Params.HnameContract().SetValue(testcore.HScName) f.Params.HnameEP().SetValue(testcore.HViewFibonacci) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) result := f.Results.IntValue() require.True(t, result.Exists()) @@ -61,7 +61,7 @@ func TestCallRecursive(t *testing.T) { f.Params.IntValue().SetValue(31) f.Params.HnameContract().SetValue(testcore.HScName) f.Params.HnameEP().SetValue(testcore.HFuncRunRecursion) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) v := testcore.ScFuncs.GetCounter(ctx) @@ -80,7 +80,7 @@ func TestGetSet(t *testing.T) { f := testcore.ScFuncs.SetInt(ctx) f.Params.Name().SetValue("ppp") f.Params.IntValue().SetValue(314) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) v := testcore.ScFuncs.GetInt(ctx) diff --git a/contracts/wasm/testcore/test/check_ctx_test.go b/contracts/wasm/testcore/test/check_ctx_test.go index e16cff74de..acf21aefbb 100644 --- a/contracts/wasm/testcore/test/check_ctx_test.go +++ b/contracts/wasm/testcore/test/check_ctx_test.go @@ -19,7 +19,7 @@ func TestMainCallsFromFullEP(t *testing.T) { f.Params.Caller().SetValue(user.ScAgentID()) f.Params.ChainOwnerID().SetValue(ctx.Originator().ScAgentID()) f.Params.ContractCreator().SetValue(user.ScAgentID()) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) }) } @@ -45,7 +45,7 @@ func TestMintedSupplyOk(t *testing.T) { user := ctx.Creator() f := testcore.ScFuncs.GetMintedSupply(ctx.Sign(user, 42)) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) mintedColor, mintedAmount := ctx.Minted() diff --git a/contracts/wasm/testcore/test/concurrency_test.go b/contracts/wasm/testcore/test/concurrency_test.go index 2d410b19ab..a8d3442b32 100644 --- a/contracts/wasm/testcore/test/concurrency_test.go +++ b/contracts/wasm/testcore/test/concurrency_test.go @@ -8,7 +8,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" "github.com/iotaledger/wasp/packages/kv/codec" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -17,7 +17,6 @@ func TestCounter(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.IncCounter(ctx) - f.Func.TransferIotas(1) for i := 0; i < 33; i++ { f.Func.Post() require.NoError(t, ctx.Err) @@ -32,14 +31,12 @@ func TestCounter(t *testing.T) { func TestSynchronous(t *testing.T) { run2(t, func(t *testing.T, w bool) { + ctx := deployTestCore(t, w) + // TODO fails with 999 instead of 1000 at WaitForPendingRequests - if *wasmsolo.GoDebug || *wasmsolo.GoWasmEdge { + if !ctx.IsWasm || *wasmsolo.UseWasmEdge { t.SkipNow() } - ctx := deployTestCore(t, w) - - f := testcore.ScFuncs.IncCounter(ctx) - f.Func.TransferIotas(1) repeats := []int{300, 100, 100, 100, 200, 100, 100} if wasmsolo.SoloDebug { @@ -53,6 +50,7 @@ func TestSynchronous(t *testing.T) { sum += n } + f := testcore.ScFuncs.IncCounter(ctx) for _, n := range repeats { for i := 0; i < n; i++ { ctx.EnqueueRequest() @@ -82,8 +80,7 @@ func TestConcurrency(t *testing.T) { // note that because SoloContext is not thread-safe we cannot use // the following in parallel go-routines - f := testcore.ScFuncs.IncCounter(ctx) - f.Func.TransferIotas(1) + // f := testcore.ScFuncs.IncCounter(ctx) req := solo.NewCallParams(testcore.ScName, testcore.FuncIncCounter). WithIotas(1) @@ -128,8 +125,7 @@ func TestConcurrency2(t *testing.T) { // note that because SoloContext is not thread-safe we cannot use // the following in parallel go-routines - f := testcore.ScFuncs.IncCounter(ctx) - f.Func.TransferIotas(1) + // f := testcore.ScFuncs.IncCounter(ctx) req := solo.NewCallParams(testcore.ScName, testcore.FuncIncCounter). WithIotas(1) @@ -182,7 +178,7 @@ func TestViewConcurrency(t *testing.T) { ctx := deployTestCore(t, false) f := testcore.ScFuncs.IncCounter(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() times := 2000 if wasmsolo.SoloDebug { diff --git a/contracts/wasm/testcore/test/init_fail_test.go b/contracts/wasm/testcore/test/init_fail_test.go index a39fdfcffa..03b543baad 100644 --- a/contracts/wasm/testcore/test/init_fail_test.go +++ b/contracts/wasm/testcore/test/init_fail_test.go @@ -5,7 +5,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" "github.com/iotaledger/wasp/packages/vm/core" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) diff --git a/contracts/wasm/testcore/test/misc_call_test.go b/contracts/wasm/testcore/test/misc_call_test.go index 95ad9c205f..9554c3b355 100644 --- a/contracts/wasm/testcore/test/misc_call_test.go +++ b/contracts/wasm/testcore/test/misc_call_test.go @@ -23,7 +23,7 @@ func TestChainOwnerIDFull(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.TestChainOwnerIDFull(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) require.EqualValues(t, ctx.Originator().ScAgentID(), f.Results.ChainOwnerID().Value()) }) diff --git a/contracts/wasm/testcore/test/sandbox_panic_test.go b/contracts/wasm/testcore/test/sandbox_panic_test.go index 53208ffe5d..a8a029677a 100644 --- a/contracts/wasm/testcore/test/sandbox_panic_test.go +++ b/contracts/wasm/testcore/test/sandbox_panic_test.go @@ -6,7 +6,7 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" "github.com/iotaledger/wasp/packages/vm/core/testcore/sbtests/sbtestsc" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -27,7 +27,7 @@ func TestPanicFull(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.TestPanicFullEP(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.Error(t, ctx.Err) require.Contains(t, ctx.Err.Error(), sbtestsc.MsgFullPanic) @@ -53,7 +53,7 @@ func TestCallPanicFull(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.TestCallPanicFullEP(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.Error(t, ctx.Err) require.Contains(t, ctx.Err.Error(), sbtestsc.MsgFullPanic) @@ -66,7 +66,7 @@ func TestCallPanicViewFromFull(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.TestCallPanicViewEPFromFull(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.Error(t, ctx.Err) require.Contains(t, ctx.Err.Error(), sbtestsc.MsgViewPanic) diff --git a/contracts/wasm/testcore/test/spawn_test.go b/contracts/wasm/testcore/test/spawn_test.go index 7be97ab57e..dd43db735c 100644 --- a/contracts/wasm/testcore/test/spawn_test.go +++ b/contracts/wasm/testcore/test/spawn_test.go @@ -14,10 +14,11 @@ func TestSpawn(t *testing.T) { f := testcore.ScFuncs.Spawn(ctx) f.Params.ProgHash().SetValue(ctx.Convertor.ScHash(ctx.Hprog)) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) - ctxSpawn := ctx.SoloContextForCore(t, testcore.ScName+"_spawned", testcore.OnLoad) + spawnedName := testcore.ScName + "_spawned" + ctxSpawn := ctx.SoloContextForCore(t, spawnedName, testcore.OnLoad) require.NoError(t, ctxSpawn.Err) v := testcore.ScFuncs.GetCounter(ctxSpawn) v.Func.Call() diff --git a/contracts/wasm/testcore/test/testcore_bg.wasm b/contracts/wasm/testcore/test/testcore_bg.wasm index 4c5b2af584..354d8cdd06 100644 Binary files a/contracts/wasm/testcore/test/testcore_bg.wasm and b/contracts/wasm/testcore/test/testcore_bg.wasm differ diff --git a/contracts/wasm/testcore/test/testcore_test.go b/contracts/wasm/testcore/test/testcore_test.go index 9ca6847fbd..c64c87aedc 100644 --- a/contracts/wasm/testcore/test/testcore_test.go +++ b/contracts/wasm/testcore/test/testcore_test.go @@ -8,11 +8,11 @@ import ( "github.com/iotaledger/wasp/packages/solo" "github.com/iotaledger/wasp/packages/util" "github.com/iotaledger/wasp/packages/vm/core/testcore/sbtests/sbtestsc" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coreaccounts" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coregovernance" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coreroot" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coregovernance" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coreroot" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -38,39 +38,44 @@ func deployTestCoreOnChain(t *testing.T, runWasm bool, chain *solo.Chain, creato return wasmsolo.NewSoloContextForNative(t, chain, creator, testcore.ScName, testcore.OnLoad, sbtestsc.Processor, init...) } -func run2(t *testing.T, test func(*testing.T, bool), skipWasm ...bool) { +func run2(t *testing.T, test func(*testing.T, bool)) { t.Run(fmt.Sprintf("run CORE version of %s", t.Name()), func(t *testing.T) { test(t, false) }) - if len(skipWasm) != 0 && skipWasm[0] { - t.Logf("skipped Wasm versions of '%s'", t.Name()) - return - } - - saveGoDebug := *wasmsolo.GoDebug saveGoWasm := *wasmsolo.GoWasm + saveRsWasm := *wasmsolo.RsWasm saveTsWasm := *wasmsolo.TsWasm - *wasmsolo.GoDebug = false *wasmsolo.GoWasm = false + *wasmsolo.RsWasm = false *wasmsolo.TsWasm = false - exists, _ := util.ExistsFilePath("../pkg/testcore_bg.wasm") + wasmlib.ConnectHost(nil) + t.Run(fmt.Sprintf("run GOVM version of %s", t.Name()), func(t *testing.T) { + test(t, true) + }) + + exists, _ := util.ExistsFilePath("../go/pkg/testcore_go.wasm") if exists { + *wasmsolo.GoWasm = true wasmlib.ConnectHost(nil) - t.Run(fmt.Sprintf("run RUST version of %s", t.Name()), func(t *testing.T) { + t.Run(fmt.Sprintf("run GO version of %s", t.Name()), func(t *testing.T) { test(t, true) }) + *wasmsolo.GoWasm = false } - exists, _ = util.ExistsFilePath("../go/pkg/testcore_go.wasm") + exists, _ = util.ExistsFilePath("../pkg/testcore_bg.wasm") + if !exists { + exists, _ = util.ExistsFilePath("testcore_bg.wasm") + } if exists { - *wasmsolo.GoWasm = true + *wasmsolo.RsWasm = true wasmlib.ConnectHost(nil) - t.Run(fmt.Sprintf("run GO version of %s", t.Name()), func(t *testing.T) { + t.Run(fmt.Sprintf("run RUST version of %s", t.Name()), func(t *testing.T) { test(t, true) }) - *wasmsolo.GoWasm = false + *wasmsolo.RsWasm = false } exists, _ = util.ExistsFilePath("../ts/pkg/testcore_ts.wasm") @@ -83,14 +88,8 @@ func run2(t *testing.T, test func(*testing.T, bool), skipWasm ...bool) { *wasmsolo.TsWasm = false } - *wasmsolo.GoDebug = true - wasmlib.ConnectHost(nil) - t.Run(fmt.Sprintf("run GOVM version of %s", t.Name()), func(t *testing.T) { - test(t, true) - }) - - *wasmsolo.GoDebug = saveGoDebug *wasmsolo.GoWasm = saveGoWasm + *wasmsolo.RsWasm = saveRsWasm *wasmsolo.TsWasm = saveTsWasm } @@ -130,7 +129,7 @@ func originatorBalanceReducedBy(ctx *wasmsolo.SoloContext, w bool, minus uint64) ctx.Chain.Env.AssertAddressIotas(ctx.Chain.OriginatorAddress, solo.Saldo-solo.ChainDustThreshold-minus) } -func deposit(t *testing.T, ctx *wasmsolo.SoloContext, user, target *wasmsolo.SoloAgent, amount int64) { +func deposit(t *testing.T, ctx *wasmsolo.SoloContext, user, target *wasmsolo.SoloAgent, amount uint64) { ctxAcc := ctx.SoloContextForCore(t, coreaccounts.ScName, coreaccounts.OnLoad) f := coreaccounts.ScFuncs.Deposit(ctxAcc.Sign(user)) if target != nil { @@ -144,7 +143,7 @@ func setDeployer(t *testing.T, ctx *wasmsolo.SoloContext, deployer *wasmsolo.Sol ctxRoot := ctx.SoloContextForCore(t, coreroot.ScName, coreroot.OnLoad) f := coreroot.ScFuncs.GrantDeployPermission(ctxRoot) f.Params.Deployer().SetValue(deployer.ScAgentID()) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctxRoot.Err) } @@ -153,13 +152,13 @@ func setOwnerFee(t *testing.T, ctx *wasmsolo.SoloContext, amount int64) { f := coregovernance.ScFuncs.SetContractFee(ctxGov) f.Params.Hname().SetValue(testcore.HScName) f.Params.OwnerFee().SetValue(amount) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctxGov.Err) } func withdraw(t *testing.T, ctx *wasmsolo.SoloContext, user *wasmsolo.SoloAgent) { ctxAcc := ctx.SoloContextForCore(t, coreaccounts.ScName, coreaccounts.OnLoad) f := coreaccounts.ScFuncs.Withdraw(ctxAcc.Sign(user)) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctxAcc.Err) } diff --git a/contracts/wasm/testcore/test/transfer_test.go b/contracts/wasm/testcore/test/transfer_test.go index 54401de8f8..23395e3c2f 100644 --- a/contracts/wasm/testcore/test/transfer_test.go +++ b/contracts/wasm/testcore/test/transfer_test.go @@ -64,7 +64,7 @@ func TestWithdrawToAddress(t *testing.T) { // note that that includes the token that we transfer here xfer := testcore.ScFuncs.SendToAddress(ctx.Sign(ctx.Originator())) xfer.Params.Address().SetValue(user.ScAddress()) - xfer.Func.TransferIotas(1).Post() + xfer.Func.Post() require.NoError(t, ctx.Err) t.Logf("dump accounts:\n%s", ctx.Chain.DumpAccounts()) diff --git a/contracts/wasm/testcore/test/types_test.go b/contracts/wasm/testcore/test/types_test.go index 1ba4b9f23c..e95571724d 100644 --- a/contracts/wasm/testcore/test/types_test.go +++ b/contracts/wasm/testcore/test/types_test.go @@ -5,10 +5,11 @@ import ( "github.com/iotaledger/wasp/contracts/wasm/testcore/go/testcore" "github.com/iotaledger/wasp/packages/hashing" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/iscp" "github.com/stretchr/testify/require" ) +//nolint:dupl func TestTypesFull(t *testing.T) { run2(t, func(t *testing.T, w bool) { ctx := deployTestCore(t, w) @@ -18,18 +19,20 @@ func TestTypesFull(t *testing.T) { f.Params.AgentID().SetValue(ctx.Originator().ScAgentID()) f.Params.ChainID().SetValue(ctx.ChainID()) f.Params.ContractID().SetValue(ctx.AccountID()) - f.Params.Hash().SetValue(ctx.Convertor.ScHash(hashing.HashStrings("Hash"))) - f.Params.Hname().SetValue(wasmlib.NewScHname("Hname")) - f.Params.HnameZero().SetValue(wasmlib.ScHname(0)) + hashValue := hashing.HashStrings("Hash") + f.Params.Hash().SetValue(ctx.Convertor.ScHash(hashValue)) + f.Params.Hname().SetValue(ctx.Convertor.ScHname(iscp.Hn("Hname"))) + f.Params.HnameZero().SetValue(0) f.Params.Int64().SetValue(42) f.Params.Int64Zero().SetValue(0) f.Params.String().SetValue("string") f.Params.StringZero().SetValue("") - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) }) } +//nolint:dupl func TestTypesView(t *testing.T) { run2(t, func(t *testing.T, w bool) { ctx := deployTestCore(t, w) @@ -39,9 +42,10 @@ func TestTypesView(t *testing.T) { v.Params.AgentID().SetValue(ctx.Originator().ScAgentID()) v.Params.ChainID().SetValue(ctx.ChainID()) v.Params.ContractID().SetValue(ctx.AccountID()) - v.Params.Hash().SetValue(ctx.Convertor.ScHash(hashing.HashStrings("Hash"))) - v.Params.Hname().SetValue(wasmlib.NewScHname("Hname")) - v.Params.HnameZero().SetValue(wasmlib.ScHname(0)) + hashValue := hashing.HashStrings("Hash") + v.Params.Hash().SetValue(ctx.Convertor.ScHash(hashValue)) + v.Params.Hname().SetValue(ctx.Convertor.ScHname(iscp.Hn("Hname"))) + v.Params.HnameZero().SetValue(0) v.Params.Int64().SetValue(42) v.Params.Int64Zero().SetValue(0) v.Params.String().SetValue("string") diff --git a/contracts/wasm/testcore/ts/testcore/consts.ts b/contracts/wasm/testcore/ts/testcore/consts.ts index 9800e419f1..5604fa9874 100644 --- a/contracts/wasm/testcore/ts/testcore/consts.ts +++ b/contracts/wasm/testcore/ts/testcore/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "testcore"; export const ScDescription = "Core test for ISCP wasmlib Rust/Wasm library"; -export const HScName = new wasmlib.ScHname(0x370d33ad); +export const HScName = new wasmtypes.ScHname(0x370d33ad); export const ParamAddress = "address"; export const ParamAgentID = "agentID"; @@ -82,35 +82,35 @@ export const ViewTestChainOwnerIDView = "testChainOwnerIDView"; export const ViewTestPanicViewEP = "testPanicViewEP"; export const ViewTestSandboxCall = "testSandboxCall"; -export const HFuncCallOnChain = new wasmlib.ScHname(0x95a3d123); -export const HFuncCheckContextFromFullEP = new wasmlib.ScHname(0xa56c24ba); -export const HFuncDoNothing = new wasmlib.ScHname(0xdda4a6de); -export const HFuncGetMintedSupply = new wasmlib.ScHname(0x0c2d113c); -export const HFuncIncCounter = new wasmlib.ScHname(0x7b287419); -export const HFuncInit = new wasmlib.ScHname(0x1f44d644); -export const HFuncPassTypesFull = new wasmlib.ScHname(0x733ea0ea); -export const HFuncRunRecursion = new wasmlib.ScHname(0x833425fd); -export const HFuncSendToAddress = new wasmlib.ScHname(0x63ce4634); -export const HFuncSetInt = new wasmlib.ScHname(0x62056f74); -export const HFuncSpawn = new wasmlib.ScHname(0xec929d12); -export const HFuncTestBlockContext1 = new wasmlib.ScHname(0x796d4136); -export const HFuncTestBlockContext2 = new wasmlib.ScHname(0x758b0452); -export const HFuncTestCallPanicFullEP = new wasmlib.ScHname(0x4c878834); -export const HFuncTestCallPanicViewEPFromFull = new wasmlib.ScHname(0xfd7e8c1d); -export const HFuncTestChainOwnerIDFull = new wasmlib.ScHname(0x2aff1167); -export const HFuncTestEventLogDeploy = new wasmlib.ScHname(0x96ff760a); -export const HFuncTestEventLogEventData = new wasmlib.ScHname(0x0efcf939); -export const HFuncTestEventLogGenericData = new wasmlib.ScHname(0x6a16629d); -export const HFuncTestPanicFullEP = new wasmlib.ScHname(0x24fdef07); -export const HFuncWithdrawToChain = new wasmlib.ScHname(0x437bc026); -export const HViewCheckContextFromViewEP = new wasmlib.ScHname(0x88ff0167); -export const HViewFibonacci = new wasmlib.ScHname(0x7940873c); -export const HViewGetCounter = new wasmlib.ScHname(0xb423e607); -export const HViewGetInt = new wasmlib.ScHname(0x1887e5ef); -export const HViewGetStringValue = new wasmlib.ScHname(0xcf0a4d32); -export const HViewJustView = new wasmlib.ScHname(0x33b8972e); -export const HViewPassTypesView = new wasmlib.ScHname(0x1a5b87ea); -export const HViewTestCallPanicViewEPFromView = new wasmlib.ScHname(0x91b10c99); -export const HViewTestChainOwnerIDView = new wasmlib.ScHname(0x26586c33); -export const HViewTestPanicViewEP = new wasmlib.ScHname(0x22bc4d72); -export const HViewTestSandboxCall = new wasmlib.ScHname(0x42d72b63); +export const HFuncCallOnChain = new wasmtypes.ScHname(0x95a3d123); +export const HFuncCheckContextFromFullEP = new wasmtypes.ScHname(0xa56c24ba); +export const HFuncDoNothing = new wasmtypes.ScHname(0xdda4a6de); +export const HFuncGetMintedSupply = new wasmtypes.ScHname(0x0c2d113c); +export const HFuncIncCounter = new wasmtypes.ScHname(0x7b287419); +export const HFuncInit = new wasmtypes.ScHname(0x1f44d644); +export const HFuncPassTypesFull = new wasmtypes.ScHname(0x733ea0ea); +export const HFuncRunRecursion = new wasmtypes.ScHname(0x833425fd); +export const HFuncSendToAddress = new wasmtypes.ScHname(0x63ce4634); +export const HFuncSetInt = new wasmtypes.ScHname(0x62056f74); +export const HFuncSpawn = new wasmtypes.ScHname(0xec929d12); +export const HFuncTestBlockContext1 = new wasmtypes.ScHname(0x796d4136); +export const HFuncTestBlockContext2 = new wasmtypes.ScHname(0x758b0452); +export const HFuncTestCallPanicFullEP = new wasmtypes.ScHname(0x4c878834); +export const HFuncTestCallPanicViewEPFromFull = new wasmtypes.ScHname(0xfd7e8c1d); +export const HFuncTestChainOwnerIDFull = new wasmtypes.ScHname(0x2aff1167); +export const HFuncTestEventLogDeploy = new wasmtypes.ScHname(0x96ff760a); +export const HFuncTestEventLogEventData = new wasmtypes.ScHname(0x0efcf939); +export const HFuncTestEventLogGenericData = new wasmtypes.ScHname(0x6a16629d); +export const HFuncTestPanicFullEP = new wasmtypes.ScHname(0x24fdef07); +export const HFuncWithdrawToChain = new wasmtypes.ScHname(0x437bc026); +export const HViewCheckContextFromViewEP = new wasmtypes.ScHname(0x88ff0167); +export const HViewFibonacci = new wasmtypes.ScHname(0x7940873c); +export const HViewGetCounter = new wasmtypes.ScHname(0xb423e607); +export const HViewGetInt = new wasmtypes.ScHname(0x1887e5ef); +export const HViewGetStringValue = new wasmtypes.ScHname(0xcf0a4d32); +export const HViewJustView = new wasmtypes.ScHname(0x33b8972e); +export const HViewPassTypesView = new wasmtypes.ScHname(0x1a5b87ea); +export const HViewTestCallPanicViewEPFromView = new wasmtypes.ScHname(0x91b10c99); +export const HViewTestChainOwnerIDView = new wasmtypes.ScHname(0x26586c33); +export const HViewTestPanicViewEP = new wasmtypes.ScHname(0x22bc4d72); +export const HViewTestSandboxCall = new wasmtypes.ScHname(0x42d72b63); diff --git a/contracts/wasm/testcore/ts/testcore/contract.ts b/contracts/wasm/testcore/ts/testcore/contract.ts index 8c45bf2c57..af6954d1c1 100644 --- a/contracts/wasm/testcore/ts/testcore/contract.ts +++ b/contracts/wasm/testcore/ts/testcore/contract.ts @@ -10,24 +10,24 @@ import * as sc from "./index"; export class CallOnChainCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncCallOnChain); - params: sc.MutableCallOnChainParams = new sc.MutableCallOnChainParams(); - results: sc.ImmutableCallOnChainResults = new sc.ImmutableCallOnChainResults(); + params: sc.MutableCallOnChainParams = new sc.MutableCallOnChainParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableCallOnChainResults = new sc.ImmutableCallOnChainResults(wasmlib.ScView.nilProxy); } export class CallOnChainContext { - params: sc.ImmutableCallOnChainParams = new sc.ImmutableCallOnChainParams(); - results: sc.MutableCallOnChainResults = new sc.MutableCallOnChainResults(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableCallOnChainParams = new sc.ImmutableCallOnChainParams(wasmlib.paramsProxy()); + results: sc.MutableCallOnChainResults = new sc.MutableCallOnChainResults(wasmlib.ScView.nilProxy); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class CheckContextFromFullEPCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncCheckContextFromFullEP); - params: sc.MutableCheckContextFromFullEPParams = new sc.MutableCheckContextFromFullEPParams(); + params: sc.MutableCheckContextFromFullEPParams = new sc.MutableCheckContextFromFullEPParams(wasmlib.ScView.nilProxy); } export class CheckContextFromFullEPContext { - params: sc.ImmutableCheckContextFromFullEPParams = new sc.ImmutableCheckContextFromFullEPParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableCheckContextFromFullEPParams = new sc.ImmutableCheckContextFromFullEPParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class DoNothingCall { @@ -35,17 +35,17 @@ export class DoNothingCall { } export class DoNothingContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class GetMintedSupplyCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncGetMintedSupply); - results: sc.ImmutableGetMintedSupplyResults = new sc.ImmutableGetMintedSupplyResults(); + results: sc.ImmutableGetMintedSupplyResults = new sc.ImmutableGetMintedSupplyResults(wasmlib.ScView.nilProxy); } export class GetMintedSupplyContext { - results: sc.MutableGetMintedSupplyResults = new sc.MutableGetMintedSupplyResults(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + results: sc.MutableGetMintedSupplyResults = new sc.MutableGetMintedSupplyResults(wasmlib.ScView.nilProxy); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class IncCounterCall { @@ -53,69 +53,69 @@ export class IncCounterCall { } export class IncCounterContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); - params: sc.MutableInitParams = new sc.MutableInitParams(); + params: sc.MutableInitParams = new sc.MutableInitParams(wasmlib.ScView.nilProxy); } export class InitContext { - params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableInitParams = new sc.ImmutableInitParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class PassTypesFullCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncPassTypesFull); - params: sc.MutablePassTypesFullParams = new sc.MutablePassTypesFullParams(); + params: sc.MutablePassTypesFullParams = new sc.MutablePassTypesFullParams(wasmlib.ScView.nilProxy); } export class PassTypesFullContext { - params: sc.ImmutablePassTypesFullParams = new sc.ImmutablePassTypesFullParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutablePassTypesFullParams = new sc.ImmutablePassTypesFullParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class RunRecursionCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRunRecursion); - params: sc.MutableRunRecursionParams = new sc.MutableRunRecursionParams(); - results: sc.ImmutableRunRecursionResults = new sc.ImmutableRunRecursionResults(); + params: sc.MutableRunRecursionParams = new sc.MutableRunRecursionParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableRunRecursionResults = new sc.ImmutableRunRecursionResults(wasmlib.ScView.nilProxy); } export class RunRecursionContext { - params: sc.ImmutableRunRecursionParams = new sc.ImmutableRunRecursionParams(); - results: sc.MutableRunRecursionResults = new sc.MutableRunRecursionResults(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableRunRecursionParams = new sc.ImmutableRunRecursionParams(wasmlib.paramsProxy()); + results: sc.MutableRunRecursionResults = new sc.MutableRunRecursionResults(wasmlib.ScView.nilProxy); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class SendToAddressCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSendToAddress); - params: sc.MutableSendToAddressParams = new sc.MutableSendToAddressParams(); + params: sc.MutableSendToAddressParams = new sc.MutableSendToAddressParams(wasmlib.ScView.nilProxy); } export class SendToAddressContext { - params: sc.ImmutableSendToAddressParams = new sc.ImmutableSendToAddressParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableSendToAddressParams = new sc.ImmutableSendToAddressParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class SetIntCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetInt); - params: sc.MutableSetIntParams = new sc.MutableSetIntParams(); + params: sc.MutableSetIntParams = new sc.MutableSetIntParams(wasmlib.ScView.nilProxy); } export class SetIntContext { - params: sc.ImmutableSetIntParams = new sc.ImmutableSetIntParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableSetIntParams = new sc.ImmutableSetIntParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class SpawnCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSpawn); - params: sc.MutableSpawnParams = new sc.MutableSpawnParams(); + params: sc.MutableSpawnParams = new sc.MutableSpawnParams(wasmlib.ScView.nilProxy); } export class SpawnContext { - params: sc.ImmutableSpawnParams = new sc.ImmutableSpawnParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableSpawnParams = new sc.ImmutableSpawnParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestBlockContext1Call { @@ -123,7 +123,7 @@ export class TestBlockContext1Call { } export class TestBlockContext1Context { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestBlockContext2Call { @@ -131,7 +131,7 @@ export class TestBlockContext2Call { } export class TestBlockContext2Context { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestCallPanicFullEPCall { @@ -139,7 +139,7 @@ export class TestCallPanicFullEPCall { } export class TestCallPanicFullEPContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestCallPanicViewEPFromFullCall { @@ -147,17 +147,17 @@ export class TestCallPanicViewEPFromFullCall { } export class TestCallPanicViewEPFromFullContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestChainOwnerIDFullCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestChainOwnerIDFull); - results: sc.ImmutableTestChainOwnerIDFullResults = new sc.ImmutableTestChainOwnerIDFullResults(); + results: sc.ImmutableTestChainOwnerIDFullResults = new sc.ImmutableTestChainOwnerIDFullResults(wasmlib.ScView.nilProxy); } export class TestChainOwnerIDFullContext { - results: sc.MutableTestChainOwnerIDFullResults = new sc.MutableTestChainOwnerIDFullResults(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + results: sc.MutableTestChainOwnerIDFullResults = new sc.MutableTestChainOwnerIDFullResults(wasmlib.ScView.nilProxy); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestEventLogDeployCall { @@ -165,7 +165,7 @@ export class TestEventLogDeployCall { } export class TestEventLogDeployContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestEventLogEventDataCall { @@ -173,17 +173,17 @@ export class TestEventLogEventDataCall { } export class TestEventLogEventDataContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestEventLogGenericDataCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestEventLogGenericData); - params: sc.MutableTestEventLogGenericDataParams = new sc.MutableTestEventLogGenericDataParams(); + params: sc.MutableTestEventLogGenericDataParams = new sc.MutableTestEventLogGenericDataParams(wasmlib.ScView.nilProxy); } export class TestEventLogGenericDataContext { - params: sc.ImmutableTestEventLogGenericDataParams = new sc.ImmutableTestEventLogGenericDataParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableTestEventLogGenericDataParams = new sc.ImmutableTestEventLogGenericDataParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class TestPanicFullEPCall { @@ -191,73 +191,73 @@ export class TestPanicFullEPCall { } export class TestPanicFullEPContext { - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class WithdrawToChainCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWithdrawToChain); - params: sc.MutableWithdrawToChainParams = new sc.MutableWithdrawToChainParams(); + params: sc.MutableWithdrawToChainParams = new sc.MutableWithdrawToChainParams(wasmlib.ScView.nilProxy); } export class WithdrawToChainContext { - params: sc.ImmutableWithdrawToChainParams = new sc.ImmutableWithdrawToChainParams(); - state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); + params: sc.ImmutableWithdrawToChainParams = new sc.ImmutableWithdrawToChainParams(wasmlib.paramsProxy()); + state: sc.MutableTestCoreState = new sc.MutableTestCoreState(wasmlib.ScState.proxy()); } export class CheckContextFromViewEPCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewCheckContextFromViewEP); - params: sc.MutableCheckContextFromViewEPParams = new sc.MutableCheckContextFromViewEPParams(); + params: sc.MutableCheckContextFromViewEPParams = new sc.MutableCheckContextFromViewEPParams(wasmlib.ScView.nilProxy); } export class CheckContextFromViewEPContext { - params: sc.ImmutableCheckContextFromViewEPParams = new sc.ImmutableCheckContextFromViewEPParams(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + params: sc.ImmutableCheckContextFromViewEPParams = new sc.ImmutableCheckContextFromViewEPParams(wasmlib.paramsProxy()); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class FibonacciCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewFibonacci); - params: sc.MutableFibonacciParams = new sc.MutableFibonacciParams(); - results: sc.ImmutableFibonacciResults = new sc.ImmutableFibonacciResults(); + params: sc.MutableFibonacciParams = new sc.MutableFibonacciParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableFibonacciResults = new sc.ImmutableFibonacciResults(wasmlib.ScView.nilProxy); } export class FibonacciContext { - params: sc.ImmutableFibonacciParams = new sc.ImmutableFibonacciParams(); - results: sc.MutableFibonacciResults = new sc.MutableFibonacciResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + params: sc.ImmutableFibonacciParams = new sc.ImmutableFibonacciParams(wasmlib.paramsProxy()); + results: sc.MutableFibonacciResults = new sc.MutableFibonacciResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class GetCounterCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetCounter); - results: sc.ImmutableGetCounterResults = new sc.ImmutableGetCounterResults(); + results: sc.ImmutableGetCounterResults = new sc.ImmutableGetCounterResults(wasmlib.ScView.nilProxy); } export class GetCounterContext { - results: sc.MutableGetCounterResults = new sc.MutableGetCounterResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + results: sc.MutableGetCounterResults = new sc.MutableGetCounterResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class GetIntCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetInt); - params: sc.MutableGetIntParams = new sc.MutableGetIntParams(); - results: sc.ImmutableGetIntResults = new sc.ImmutableGetIntResults(); + params: sc.MutableGetIntParams = new sc.MutableGetIntParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetIntResults = new sc.ImmutableGetIntResults(wasmlib.ScView.nilProxy); } export class GetIntContext { - params: sc.ImmutableGetIntParams = new sc.ImmutableGetIntParams(); - results: sc.MutableGetIntResults = new sc.MutableGetIntResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + params: sc.ImmutableGetIntParams = new sc.ImmutableGetIntParams(wasmlib.paramsProxy()); + results: sc.MutableGetIntResults = new sc.MutableGetIntResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class GetStringValueCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetStringValue); - params: sc.MutableGetStringValueParams = new sc.MutableGetStringValueParams(); - results: sc.ImmutableGetStringValueResults = new sc.ImmutableGetStringValueResults(); + params: sc.MutableGetStringValueParams = new sc.MutableGetStringValueParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetStringValueResults = new sc.ImmutableGetStringValueResults(wasmlib.ScView.nilProxy); } export class GetStringValueContext { - params: sc.ImmutableGetStringValueParams = new sc.ImmutableGetStringValueParams(); - results: sc.MutableGetStringValueResults = new sc.MutableGetStringValueResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + params: sc.ImmutableGetStringValueParams = new sc.ImmutableGetStringValueParams(wasmlib.paramsProxy()); + results: sc.MutableGetStringValueResults = new sc.MutableGetStringValueResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class JustViewCall { @@ -265,17 +265,17 @@ export class JustViewCall { } export class JustViewContext { - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class PassTypesViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewPassTypesView); - params: sc.MutablePassTypesViewParams = new sc.MutablePassTypesViewParams(); + params: sc.MutablePassTypesViewParams = new sc.MutablePassTypesViewParams(wasmlib.ScView.nilProxy); } export class PassTypesViewContext { - params: sc.ImmutablePassTypesViewParams = new sc.ImmutablePassTypesViewParams(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + params: sc.ImmutablePassTypesViewParams = new sc.ImmutablePassTypesViewParams(wasmlib.paramsProxy()); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class TestCallPanicViewEPFromViewCall { @@ -283,17 +283,17 @@ export class TestCallPanicViewEPFromViewCall { } export class TestCallPanicViewEPFromViewContext { - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class TestChainOwnerIDViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestChainOwnerIDView); - results: sc.ImmutableTestChainOwnerIDViewResults = new sc.ImmutableTestChainOwnerIDViewResults(); + results: sc.ImmutableTestChainOwnerIDViewResults = new sc.ImmutableTestChainOwnerIDViewResults(wasmlib.ScView.nilProxy); } export class TestChainOwnerIDViewContext { - results: sc.MutableTestChainOwnerIDViewResults = new sc.MutableTestChainOwnerIDViewResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + results: sc.MutableTestChainOwnerIDViewResults = new sc.MutableTestChainOwnerIDViewResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class TestPanicViewEPCall { @@ -301,185 +301,190 @@ export class TestPanicViewEPCall { } export class TestPanicViewEPContext { - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class TestSandboxCallCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestSandboxCall); - results: sc.ImmutableTestSandboxCallResults = new sc.ImmutableTestSandboxCallResults(); + results: sc.ImmutableTestSandboxCallResults = new sc.ImmutableTestSandboxCallResults(wasmlib.ScView.nilProxy); } export class TestSandboxCallContext { - results: sc.MutableTestSandboxCallResults = new sc.MutableTestSandboxCallResults(); - state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); + results: sc.MutableTestSandboxCallResults = new sc.MutableTestSandboxCallResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(wasmlib.ScState.proxy()); } export class ScFuncs { - static callOnChain(ctx: wasmlib.ScFuncCallContext): CallOnChainCall { - let f = new CallOnChainCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static checkContextFromFullEP(ctx: wasmlib.ScFuncCallContext): CheckContextFromFullEPCall { - let f = new CheckContextFromFullEPCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static doNothing(ctx: wasmlib.ScFuncCallContext): DoNothingCall { - return new DoNothingCall(); - } - - static getMintedSupply(ctx: wasmlib.ScFuncCallContext): GetMintedSupplyCall { - let f = new GetMintedSupplyCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static incCounter(ctx: wasmlib.ScFuncCallContext): IncCounterCall { - return new IncCounterCall(); - } - - static init(ctx: wasmlib.ScFuncCallContext): InitCall { - let f = new InitCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static passTypesFull(ctx: wasmlib.ScFuncCallContext): PassTypesFullCall { - let f = new PassTypesFullCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static runRecursion(ctx: wasmlib.ScFuncCallContext): RunRecursionCall { - let f = new RunRecursionCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static sendToAddress(ctx: wasmlib.ScFuncCallContext): SendToAddressCall { - let f = new SendToAddressCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setInt(ctx: wasmlib.ScFuncCallContext): SetIntCall { - let f = new SetIntCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static spawn(ctx: wasmlib.ScFuncCallContext): SpawnCall { - let f = new SpawnCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static testBlockContext1(ctx: wasmlib.ScFuncCallContext): TestBlockContext1Call { - return new TestBlockContext1Call(); - } - - static testBlockContext2(ctx: wasmlib.ScFuncCallContext): TestBlockContext2Call { - return new TestBlockContext2Call(); - } - - static testCallPanicFullEP(ctx: wasmlib.ScFuncCallContext): TestCallPanicFullEPCall { - return new TestCallPanicFullEPCall(); - } - - static testCallPanicViewEPFromFull(ctx: wasmlib.ScFuncCallContext): TestCallPanicViewEPFromFullCall { - return new TestCallPanicViewEPFromFullCall(); - } - - static testChainOwnerIDFull(ctx: wasmlib.ScFuncCallContext): TestChainOwnerIDFullCall { - let f = new TestChainOwnerIDFullCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static testEventLogDeploy(ctx: wasmlib.ScFuncCallContext): TestEventLogDeployCall { - return new TestEventLogDeployCall(); - } - - static testEventLogEventData(ctx: wasmlib.ScFuncCallContext): TestEventLogEventDataCall { - return new TestEventLogEventDataCall(); - } - - static testEventLogGenericData(ctx: wasmlib.ScFuncCallContext): TestEventLogGenericDataCall { - let f = new TestEventLogGenericDataCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static testPanicFullEP(ctx: wasmlib.ScFuncCallContext): TestPanicFullEPCall { - return new TestPanicFullEPCall(); - } - - static withdrawToChain(ctx: wasmlib.ScFuncCallContext): WithdrawToChainCall { - let f = new WithdrawToChainCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static checkContextFromViewEP(ctx: wasmlib.ScViewCallContext): CheckContextFromViewEPCall { - let f = new CheckContextFromViewEPCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static fibonacci(ctx: wasmlib.ScViewCallContext): FibonacciCall { - let f = new FibonacciCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getCounter(ctx: wasmlib.ScViewCallContext): GetCounterCall { - let f = new GetCounterCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static getInt(ctx: wasmlib.ScViewCallContext): GetIntCall { - let f = new GetIntCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getStringValue(ctx: wasmlib.ScViewCallContext): GetStringValueCall { - let f = new GetStringValueCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static justView(ctx: wasmlib.ScViewCallContext): JustViewCall { - return new JustViewCall(); - } - - static passTypesView(ctx: wasmlib.ScViewCallContext): PassTypesViewCall { - let f = new PassTypesViewCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static testCallPanicViewEPFromView(ctx: wasmlib.ScViewCallContext): TestCallPanicViewEPFromViewCall { - return new TestCallPanicViewEPFromViewCall(); - } - - static testChainOwnerIDView(ctx: wasmlib.ScViewCallContext): TestChainOwnerIDViewCall { - let f = new TestChainOwnerIDViewCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static testPanicViewEP(ctx: wasmlib.ScViewCallContext): TestPanicViewEPCall { - return new TestPanicViewEPCall(); - } - - static testSandboxCall(ctx: wasmlib.ScViewCallContext): TestSandboxCallCall { - let f = new TestSandboxCallCall(); - f.func.setPtrs(null, f.results); - return f; - } + static callOnChain(_ctx: wasmlib.ScFuncCallContext): CallOnChainCall { + const f = new CallOnChainCall(); + f.params = new sc.MutableCallOnChainParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableCallOnChainResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static checkContextFromFullEP(_ctx: wasmlib.ScFuncCallContext): CheckContextFromFullEPCall { + const f = new CheckContextFromFullEPCall(); + f.params = new sc.MutableCheckContextFromFullEPParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static doNothing(_ctx: wasmlib.ScFuncCallContext): DoNothingCall { + return new DoNothingCall(); + } + + static getMintedSupply(_ctx: wasmlib.ScFuncCallContext): GetMintedSupplyCall { + const f = new GetMintedSupplyCall(); + f.results = new sc.ImmutableGetMintedSupplyResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static incCounter(_ctx: wasmlib.ScFuncCallContext): IncCounterCall { + return new IncCounterCall(); + } + + static init(_ctx: wasmlib.ScFuncCallContext): InitCall { + const f = new InitCall(); + f.params = new sc.MutableInitParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static passTypesFull(_ctx: wasmlib.ScFuncCallContext): PassTypesFullCall { + const f = new PassTypesFullCall(); + f.params = new sc.MutablePassTypesFullParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static runRecursion(_ctx: wasmlib.ScFuncCallContext): RunRecursionCall { + const f = new RunRecursionCall(); + f.params = new sc.MutableRunRecursionParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableRunRecursionResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static sendToAddress(_ctx: wasmlib.ScFuncCallContext): SendToAddressCall { + const f = new SendToAddressCall(); + f.params = new sc.MutableSendToAddressParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setInt(_ctx: wasmlib.ScFuncCallContext): SetIntCall { + const f = new SetIntCall(); + f.params = new sc.MutableSetIntParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static spawn(_ctx: wasmlib.ScFuncCallContext): SpawnCall { + const f = new SpawnCall(); + f.params = new sc.MutableSpawnParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static testBlockContext1(_ctx: wasmlib.ScFuncCallContext): TestBlockContext1Call { + return new TestBlockContext1Call(); + } + + static testBlockContext2(_ctx: wasmlib.ScFuncCallContext): TestBlockContext2Call { + return new TestBlockContext2Call(); + } + + static testCallPanicFullEP(_ctx: wasmlib.ScFuncCallContext): TestCallPanicFullEPCall { + return new TestCallPanicFullEPCall(); + } + + static testCallPanicViewEPFromFull(_ctx: wasmlib.ScFuncCallContext): TestCallPanicViewEPFromFullCall { + return new TestCallPanicViewEPFromFullCall(); + } + + static testChainOwnerIDFull(_ctx: wasmlib.ScFuncCallContext): TestChainOwnerIDFullCall { + const f = new TestChainOwnerIDFullCall(); + f.results = new sc.ImmutableTestChainOwnerIDFullResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static testEventLogDeploy(_ctx: wasmlib.ScFuncCallContext): TestEventLogDeployCall { + return new TestEventLogDeployCall(); + } + + static testEventLogEventData(_ctx: wasmlib.ScFuncCallContext): TestEventLogEventDataCall { + return new TestEventLogEventDataCall(); + } + + static testEventLogGenericData(_ctx: wasmlib.ScFuncCallContext): TestEventLogGenericDataCall { + const f = new TestEventLogGenericDataCall(); + f.params = new sc.MutableTestEventLogGenericDataParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static testPanicFullEP(_ctx: wasmlib.ScFuncCallContext): TestPanicFullEPCall { + return new TestPanicFullEPCall(); + } + + static withdrawToChain(_ctx: wasmlib.ScFuncCallContext): WithdrawToChainCall { + const f = new WithdrawToChainCall(); + f.params = new sc.MutableWithdrawToChainParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static checkContextFromViewEP(_ctx: wasmlib.ScViewCallContext): CheckContextFromViewEPCall { + const f = new CheckContextFromViewEPCall(); + f.params = new sc.MutableCheckContextFromViewEPParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static fibonacci(_ctx: wasmlib.ScViewCallContext): FibonacciCall { + const f = new FibonacciCall(); + f.params = new sc.MutableFibonacciParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableFibonacciResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getCounter(_ctx: wasmlib.ScViewCallContext): GetCounterCall { + const f = new GetCounterCall(); + f.results = new sc.ImmutableGetCounterResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getInt(_ctx: wasmlib.ScViewCallContext): GetIntCall { + const f = new GetIntCall(); + f.params = new sc.MutableGetIntParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetIntResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getStringValue(_ctx: wasmlib.ScViewCallContext): GetStringValueCall { + const f = new GetStringValueCall(); + f.params = new sc.MutableGetStringValueParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetStringValueResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static justView(_ctx: wasmlib.ScViewCallContext): JustViewCall { + return new JustViewCall(); + } + + static passTypesView(_ctx: wasmlib.ScViewCallContext): PassTypesViewCall { + const f = new PassTypesViewCall(); + f.params = new sc.MutablePassTypesViewParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static testCallPanicViewEPFromView(_ctx: wasmlib.ScViewCallContext): TestCallPanicViewEPFromViewCall { + return new TestCallPanicViewEPFromViewCall(); + } + + static testChainOwnerIDView(_ctx: wasmlib.ScViewCallContext): TestChainOwnerIDViewCall { + const f = new TestChainOwnerIDViewCall(); + f.results = new sc.ImmutableTestChainOwnerIDViewResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static testPanicViewEP(_ctx: wasmlib.ScViewCallContext): TestPanicViewEPCall { + return new TestPanicViewEPCall(); + } + + static testSandboxCall(_ctx: wasmlib.ScViewCallContext): TestSandboxCallCall { + const f = new TestSandboxCallCall(); + f.results = new sc.ImmutableTestSandboxCallResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/testcore/ts/testcore/index.ts b/contracts/wasm/testcore/ts/testcore/index.ts index 02a05c8ac8..0fef884c82 100644 --- a/contracts/wasm/testcore/ts/testcore/index.ts +++ b/contracts/wasm/testcore/ts/testcore/index.ts @@ -9,7 +9,6 @@ export * from "./testcore"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/testcore/ts/testcore/keys.ts b/contracts/wasm/testcore/ts/testcore/keys.ts deleted file mode 100644 index f1fdbcb9fb..0000000000 --- a/contracts/wasm/testcore/ts/testcore/keys.ts +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamAddress = 0; -export const IdxParamAgentID = 1; -export const IdxParamCaller = 2; -export const IdxParamChainID = 3; -export const IdxParamChainOwnerID = 4; -export const IdxParamContractCreator = 5; -export const IdxParamContractID = 6; -export const IdxParamCounter = 7; -export const IdxParamFail = 8; -export const IdxParamHash = 9; -export const IdxParamHname = 10; -export const IdxParamHnameContract = 11; -export const IdxParamHnameEP = 12; -export const IdxParamHnameZero = 13; -export const IdxParamInt64 = 14; -export const IdxParamInt64Zero = 15; -export const IdxParamIntValue = 16; -export const IdxParamName = 17; -export const IdxParamProgHash = 18; -export const IdxParamString = 19; -export const IdxParamStringZero = 20; -export const IdxParamVarName = 21; - -export const IdxResultChainOwnerID = 22; -export const IdxResultCounter = 23; -export const IdxResultIntValue = 24; -export const IdxResultMintedColor = 25; -export const IdxResultMintedSupply = 26; -export const IdxResultSandboxCall = 27; -export const IdxResultValues = 28; -export const IdxResultVars = 29; - -export const IdxStateCounter = 30; -export const IdxStateHnameEP = 31; -export const IdxStateInts = 32; -export const IdxStateMintedColor = 33; -export const IdxStateMintedSupply = 34; - -export let keyMap: string[] = [ - sc.ParamAddress, - sc.ParamAgentID, - sc.ParamCaller, - sc.ParamChainID, - sc.ParamChainOwnerID, - sc.ParamContractCreator, - sc.ParamContractID, - sc.ParamCounter, - sc.ParamFail, - sc.ParamHash, - sc.ParamHname, - sc.ParamHnameContract, - sc.ParamHnameEP, - sc.ParamHnameZero, - sc.ParamInt64, - sc.ParamInt64Zero, - sc.ParamIntValue, - sc.ParamName, - sc.ParamProgHash, - sc.ParamString, - sc.ParamStringZero, - sc.ParamVarName, - sc.ResultChainOwnerID, - sc.ResultCounter, - sc.ResultIntValue, - sc.ResultMintedColor, - sc.ResultMintedSupply, - sc.ResultSandboxCall, - sc.ResultValues, - sc.ResultVars, - sc.StateCounter, - sc.StateHnameEP, - sc.StateInts, - sc.StateMintedColor, - sc.StateMintedSupply, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/testcore/ts/testcore/lib.ts b/contracts/wasm/testcore/ts/testcore/lib.ts index 2ff3e7d18e..04200af4ad 100644 --- a/contracts/wasm/testcore/ts/testcore/lib.ts +++ b/contracts/wasm/testcore/ts/testcore/lib.ts @@ -8,66 +8,101 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncCallOnChain, + sc.FuncCheckContextFromFullEP, + sc.FuncDoNothing, + sc.FuncGetMintedSupply, + sc.FuncIncCounter, + sc.FuncInit, + sc.FuncPassTypesFull, + sc.FuncRunRecursion, + sc.FuncSendToAddress, + sc.FuncSetInt, + sc.FuncSpawn, + sc.FuncTestBlockContext1, + sc.FuncTestBlockContext2, + sc.FuncTestCallPanicFullEP, + sc.FuncTestCallPanicViewEPFromFull, + sc.FuncTestChainOwnerIDFull, + sc.FuncTestEventLogDeploy, + sc.FuncTestEventLogEventData, + sc.FuncTestEventLogGenericData, + sc.FuncTestPanicFullEP, + sc.FuncWithdrawToChain, + sc.ViewCheckContextFromViewEP, + sc.ViewFibonacci, + sc.ViewGetCounter, + sc.ViewGetInt, + sc.ViewGetStringValue, + sc.ViewJustView, + sc.ViewPassTypesView, + sc.ViewTestCallPanicViewEPFromView, + sc.ViewTestChainOwnerIDView, + sc.ViewTestPanicViewEP, + sc.ViewTestSandboxCall, + ], + funcs: [ + funcCallOnChainThunk, + funcCheckContextFromFullEPThunk, + funcDoNothingThunk, + funcGetMintedSupplyThunk, + funcIncCounterThunk, + funcInitThunk, + funcPassTypesFullThunk, + funcRunRecursionThunk, + funcSendToAddressThunk, + funcSetIntThunk, + funcSpawnThunk, + funcTestBlockContext1Thunk, + funcTestBlockContext2Thunk, + funcTestCallPanicFullEPThunk, + funcTestCallPanicViewEPFromFullThunk, + funcTestChainOwnerIDFullThunk, + funcTestEventLogDeployThunk, + funcTestEventLogEventDataThunk, + funcTestEventLogGenericDataThunk, + funcTestPanicFullEPThunk, + funcWithdrawToChainThunk, + ], + views: [ + viewCheckContextFromViewEPThunk, + viewFibonacciThunk, + viewGetCounterThunk, + viewGetIntThunk, + viewGetStringValueThunk, + viewJustViewThunk, + viewPassTypesViewThunk, + viewTestCallPanicViewEPFromViewThunk, + viewTestChainOwnerIDViewThunk, + viewTestPanicViewEPThunk, + viewTestSandboxCallThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncCallOnChain, funcCallOnChainThunk); - exports.addFunc(sc.FuncCheckContextFromFullEP, funcCheckContextFromFullEPThunk); - exports.addFunc(sc.FuncDoNothing, funcDoNothingThunk); - exports.addFunc(sc.FuncGetMintedSupply, funcGetMintedSupplyThunk); - exports.addFunc(sc.FuncIncCounter, funcIncCounterThunk); - exports.addFunc(sc.FuncInit, funcInitThunk); - exports.addFunc(sc.FuncPassTypesFull, funcPassTypesFullThunk); - exports.addFunc(sc.FuncRunRecursion, funcRunRecursionThunk); - exports.addFunc(sc.FuncSendToAddress, funcSendToAddressThunk); - exports.addFunc(sc.FuncSetInt, funcSetIntThunk); - exports.addFunc(sc.FuncSpawn, funcSpawnThunk); - exports.addFunc(sc.FuncTestBlockContext1, funcTestBlockContext1Thunk); - exports.addFunc(sc.FuncTestBlockContext2, funcTestBlockContext2Thunk); - exports.addFunc(sc.FuncTestCallPanicFullEP, funcTestCallPanicFullEPThunk); - exports.addFunc(sc.FuncTestCallPanicViewEPFromFull, funcTestCallPanicViewEPFromFullThunk); - exports.addFunc(sc.FuncTestChainOwnerIDFull, funcTestChainOwnerIDFullThunk); - exports.addFunc(sc.FuncTestEventLogDeploy, funcTestEventLogDeployThunk); - exports.addFunc(sc.FuncTestEventLogEventData, funcTestEventLogEventDataThunk); - exports.addFunc(sc.FuncTestEventLogGenericData, funcTestEventLogGenericDataThunk); - exports.addFunc(sc.FuncTestPanicFullEP, funcTestPanicFullEPThunk); - exports.addFunc(sc.FuncWithdrawToChain, funcWithdrawToChainThunk); - exports.addView(sc.ViewCheckContextFromViewEP, viewCheckContextFromViewEPThunk); - exports.addView(sc.ViewFibonacci, viewFibonacciThunk); - exports.addView(sc.ViewGetCounter, viewGetCounterThunk); - exports.addView(sc.ViewGetInt, viewGetIntThunk); - exports.addView(sc.ViewGetStringValue, viewGetStringValueThunk); - exports.addView(sc.ViewJustView, viewJustViewThunk); - exports.addView(sc.ViewPassTypesView, viewPassTypesViewThunk); - exports.addView(sc.ViewTestCallPanicViewEPFromView, viewTestCallPanicViewEPFromViewThunk); - exports.addView(sc.ViewTestChainOwnerIDView, viewTestChainOwnerIDViewThunk); - exports.addView(sc.ViewTestPanicViewEP, viewTestPanicViewEPThunk); - exports.addView(sc.ViewTestSandboxCall, viewTestSandboxCallThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcCallOnChainThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcCallOnChain"); let f = new sc.CallOnChainContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableCallOnChainResults(results.asProxy()); ctx.require(f.params.intValue().exists(), "missing mandatory intValue"); sc.funcCallOnChain(ctx, f); + ctx.results(results); ctx.log("testcore.funcCallOnChain ok"); } function funcCheckContextFromFullEPThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcCheckContextFromFullEP"); let f = new sc.CheckContextFromFullEPContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.agentID().exists(), "missing mandatory agentID"); ctx.require(f.params.caller().exists(), "missing mandatory caller"); ctx.require(f.params.chainID().exists(), "missing mandatory chainID"); @@ -80,7 +115,6 @@ function funcCheckContextFromFullEPThunk(ctx: wasmlib.ScFuncContext): void { function funcDoNothingThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcDoNothing"); let f = new sc.DoNothingContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcDoNothing(ctx, f); ctx.log("testcore.funcDoNothing ok"); } @@ -88,16 +122,16 @@ function funcDoNothingThunk(ctx: wasmlib.ScFuncContext): void { function funcGetMintedSupplyThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcGetMintedSupply"); let f = new sc.GetMintedSupplyContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetMintedSupplyResults(results.asProxy()); sc.funcGetMintedSupply(ctx, f); + ctx.results(results); ctx.log("testcore.funcGetMintedSupply ok"); } function funcIncCounterThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcIncCounter"); let f = new sc.IncCounterContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcIncCounter(ctx, f); ctx.log("testcore.funcIncCounter ok"); } @@ -105,8 +139,6 @@ function funcIncCounterThunk(ctx: wasmlib.ScFuncContext): void { function funcInitThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcInit"); let f = new sc.InitContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcInit(ctx, f); ctx.log("testcore.funcInit ok"); } @@ -114,8 +146,6 @@ function funcInitThunk(ctx: wasmlib.ScFuncContext): void { function funcPassTypesFullThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcPassTypesFull"); let f = new sc.PassTypesFullContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.agentID().exists(), "missing mandatory agentID"); ctx.require(f.params.chainID().exists(), "missing mandatory chainID"); @@ -134,21 +164,19 @@ function funcPassTypesFullThunk(ctx: wasmlib.ScFuncContext): void { function funcRunRecursionThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcRunRecursion"); let f = new sc.RunRecursionContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableRunRecursionResults(results.asProxy()); ctx.require(f.params.intValue().exists(), "missing mandatory intValue"); sc.funcRunRecursion(ctx, f); + ctx.results(results); ctx.log("testcore.funcRunRecursion ok"); } function funcSendToAddressThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcSendToAddress"); + let f = new sc.SendToAddressContext(); ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.SendToAddressContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.address().exists(), "missing mandatory address"); sc.funcSendToAddress(ctx, f); ctx.log("testcore.funcSendToAddress ok"); @@ -157,8 +185,6 @@ function funcSendToAddressThunk(ctx: wasmlib.ScFuncContext): void { function funcSetIntThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcSetInt"); let f = new sc.SetIntContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.intValue().exists(), "missing mandatory intValue"); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.funcSetInt(ctx, f); @@ -168,8 +194,6 @@ function funcSetIntThunk(ctx: wasmlib.ScFuncContext): void { function funcSpawnThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcSpawn"); let f = new sc.SpawnContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.progHash().exists(), "missing mandatory progHash"); sc.funcSpawn(ctx, f); ctx.log("testcore.funcSpawn ok"); @@ -178,7 +202,6 @@ function funcSpawnThunk(ctx: wasmlib.ScFuncContext): void { function funcTestBlockContext1Thunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestBlockContext1"); let f = new sc.TestBlockContext1Context(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestBlockContext1(ctx, f); ctx.log("testcore.funcTestBlockContext1 ok"); } @@ -186,7 +209,6 @@ function funcTestBlockContext1Thunk(ctx: wasmlib.ScFuncContext): void { function funcTestBlockContext2Thunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestBlockContext2"); let f = new sc.TestBlockContext2Context(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestBlockContext2(ctx, f); ctx.log("testcore.funcTestBlockContext2 ok"); } @@ -194,7 +216,6 @@ function funcTestBlockContext2Thunk(ctx: wasmlib.ScFuncContext): void { function funcTestCallPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestCallPanicFullEP"); let f = new sc.TestCallPanicFullEPContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestCallPanicFullEP(ctx, f); ctx.log("testcore.funcTestCallPanicFullEP ok"); } @@ -202,7 +223,6 @@ function funcTestCallPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void { function funcTestCallPanicViewEPFromFullThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestCallPanicViewEPFromFull"); let f = new sc.TestCallPanicViewEPFromFullContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestCallPanicViewEPFromFull(ctx, f); ctx.log("testcore.funcTestCallPanicViewEPFromFull ok"); } @@ -210,16 +230,16 @@ function funcTestCallPanicViewEPFromFullThunk(ctx: wasmlib.ScFuncContext): void function funcTestChainOwnerIDFullThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestChainOwnerIDFull"); let f = new sc.TestChainOwnerIDFullContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableTestChainOwnerIDFullResults(results.asProxy()); sc.funcTestChainOwnerIDFull(ctx, f); + ctx.results(results); ctx.log("testcore.funcTestChainOwnerIDFull ok"); } function funcTestEventLogDeployThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestEventLogDeploy"); let f = new sc.TestEventLogDeployContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestEventLogDeploy(ctx, f); ctx.log("testcore.funcTestEventLogDeploy ok"); } @@ -227,7 +247,6 @@ function funcTestEventLogDeployThunk(ctx: wasmlib.ScFuncContext): void { function funcTestEventLogEventDataThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestEventLogEventData"); let f = new sc.TestEventLogEventDataContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestEventLogEventData(ctx, f); ctx.log("testcore.funcTestEventLogEventData ok"); } @@ -235,8 +254,6 @@ function funcTestEventLogEventDataThunk(ctx: wasmlib.ScFuncContext): void { function funcTestEventLogGenericDataThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestEventLogGenericData"); let f = new sc.TestEventLogGenericDataContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.counter().exists(), "missing mandatory counter"); sc.funcTestEventLogGenericData(ctx, f); ctx.log("testcore.funcTestEventLogGenericData ok"); @@ -245,7 +262,6 @@ function funcTestEventLogGenericDataThunk(ctx: wasmlib.ScFuncContext): void { function funcTestPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcTestPanicFullEP"); let f = new sc.TestPanicFullEPContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcTestPanicFullEP(ctx, f); ctx.log("testcore.funcTestPanicFullEP ok"); } @@ -253,8 +269,6 @@ function funcTestPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void { function funcWithdrawToChainThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testcore.funcWithdrawToChain"); let f = new sc.WithdrawToChainContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.chainID().exists(), "missing mandatory chainID"); sc.funcWithdrawToChain(ctx, f); ctx.log("testcore.funcWithdrawToChain ok"); @@ -263,8 +277,6 @@ function funcWithdrawToChainThunk(ctx: wasmlib.ScFuncContext): void { function viewCheckContextFromViewEPThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewCheckContextFromViewEP"); let f = new sc.CheckContextFromViewEPContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.agentID().exists(), "missing mandatory agentID"); ctx.require(f.params.chainID().exists(), "missing mandatory chainID"); ctx.require(f.params.chainOwnerID().exists(), "missing mandatory chainOwnerID"); @@ -276,49 +288,49 @@ function viewCheckContextFromViewEPThunk(ctx: wasmlib.ScViewContext): void { function viewFibonacciThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewFibonacci"); let f = new sc.FibonacciContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableFibonacciResults(results.asProxy()); ctx.require(f.params.intValue().exists(), "missing mandatory intValue"); sc.viewFibonacci(ctx, f); + ctx.results(results); ctx.log("testcore.viewFibonacci ok"); } function viewGetCounterThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewGetCounter"); let f = new sc.GetCounterContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetCounterResults(results.asProxy()); sc.viewGetCounter(ctx, f); + ctx.results(results); ctx.log("testcore.viewGetCounter ok"); } function viewGetIntThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewGetInt"); let f = new sc.GetIntContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetIntResults(results.asProxy()); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.viewGetInt(ctx, f); + ctx.results(results); ctx.log("testcore.viewGetInt ok"); } function viewGetStringValueThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewGetStringValue"); let f = new sc.GetStringValueContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetStringValueResults(results.asProxy()); ctx.require(f.params.varName().exists(), "missing mandatory varName"); sc.viewGetStringValue(ctx, f); + ctx.results(results); ctx.log("testcore.viewGetStringValue ok"); } function viewJustViewThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewJustView"); let f = new sc.JustViewContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.viewJustView(ctx, f); ctx.log("testcore.viewJustView ok"); } @@ -326,8 +338,6 @@ function viewJustViewThunk(ctx: wasmlib.ScViewContext): void { function viewPassTypesViewThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewPassTypesView"); let f = new sc.PassTypesViewContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.agentID().exists(), "missing mandatory agentID"); ctx.require(f.params.chainID().exists(), "missing mandatory chainID"); @@ -346,7 +356,6 @@ function viewPassTypesViewThunk(ctx: wasmlib.ScViewContext): void { function viewTestCallPanicViewEPFromViewThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewTestCallPanicViewEPFromView"); let f = new sc.TestCallPanicViewEPFromViewContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.viewTestCallPanicViewEPFromView(ctx, f); ctx.log("testcore.viewTestCallPanicViewEPFromView ok"); } @@ -354,16 +363,16 @@ function viewTestCallPanicViewEPFromViewThunk(ctx: wasmlib.ScViewContext): void function viewTestChainOwnerIDViewThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewTestChainOwnerIDView"); let f = new sc.TestChainOwnerIDViewContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableTestChainOwnerIDViewResults(results.asProxy()); sc.viewTestChainOwnerIDView(ctx, f); + ctx.results(results); ctx.log("testcore.viewTestChainOwnerIDView ok"); } function viewTestPanicViewEPThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewTestPanicViewEP"); let f = new sc.TestPanicViewEPContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.viewTestPanicViewEP(ctx, f); ctx.log("testcore.viewTestPanicViewEP ok"); } @@ -371,8 +380,9 @@ function viewTestPanicViewEPThunk(ctx: wasmlib.ScViewContext): void { function viewTestSandboxCallThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testcore.viewTestSandboxCall"); let f = new sc.TestSandboxCallContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableTestSandboxCallResults(results.asProxy()); sc.viewTestSandboxCall(ctx, f); + ctx.results(results); ctx.log("testcore.viewTestSandboxCall ok"); } diff --git a/contracts/wasm/testcore/ts/testcore/params.ts b/contracts/wasm/testcore/ts/testcore/params.ts index 6736de4bd6..3174829902 100644 --- a/contracts/wasm/testcore/ts/testcore/params.ts +++ b/contracts/wasm/testcore/ts/testcore/params.ts @@ -5,425 +5,425 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableCallOnChainParams extends wasmlib.ScMapID { - hnameContract(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameContract)); +export class ImmutableCallOnChainParams extends wasmtypes.ScProxy { + hnameContract(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHnameContract)); } - hnameEP(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameEP)); + hnameEP(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHnameEP)); } - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class MutableCallOnChainParams extends wasmlib.ScMapID { - hnameContract(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameContract)); +export class MutableCallOnChainParams extends wasmtypes.ScProxy { + hnameContract(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHnameContract)); } - hnameEP(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameEP)); + hnameEP(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHnameEP)); } - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class ImmutableCheckContextFromFullEPParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); +export class ImmutableCheckContextFromFullEPParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); } - caller(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamCaller)); + caller(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamCaller)); } - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } - chainOwnerID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwnerID)); + chainOwnerID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamChainOwnerID)); } - contractCreator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractCreator)); + contractCreator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamContractCreator)); } } -export class MutableCheckContextFromFullEPParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); +export class MutableCheckContextFromFullEPParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); } - caller(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamCaller)); + caller(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamCaller)); } - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } - chainOwnerID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwnerID)); + chainOwnerID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamChainOwnerID)); } - contractCreator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractCreator)); + contractCreator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamContractCreator)); } } -export class ImmutableInitParams extends wasmlib.ScMapID { - fail(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, sc.idxMap[sc.IdxParamFail]); +export class ImmutableInitParams extends wasmtypes.ScProxy { + fail(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamFail)); } } -export class MutableInitParams extends wasmlib.ScMapID { - fail(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, sc.idxMap[sc.IdxParamFail]); +export class MutableInitParams extends wasmtypes.ScProxy { + fail(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamFail)); } } -export class ImmutablePassTypesFullParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutablePassTypesFullParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } - contractID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractID)); + contractID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamContractID)); } - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); } - hnameZero(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameZero)); + hnameZero(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHnameZero)); } - int64(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamInt64)); } - int64Zero(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64Zero)); + int64Zero(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamInt64Zero)); } - string(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamString)); } - stringZero(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamStringZero)); + stringZero(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamStringZero)); } } -export class MutablePassTypesFullParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutablePassTypesFullParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } - contractID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractID)); + contractID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamContractID)); } - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); } - hnameZero(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameZero)); + hnameZero(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHnameZero)); } - int64(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamInt64)); } - int64Zero(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64Zero)); + int64Zero(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamInt64Zero)); } - string(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamString)); } - stringZero(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamStringZero)); + stringZero(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamStringZero)); } } -export class ImmutableRunRecursionParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class ImmutableRunRecursionParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class MutableRunRecursionParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class MutableRunRecursionParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class ImmutableSendToAddressParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutableSendToAddressParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } } -export class MutableSendToAddressParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutableSendToAddressParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } } -export class ImmutableSetIntParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class ImmutableSetIntParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamIntValue)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableSetIntParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class MutableSetIntParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamIntValue)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableSpawnParams extends wasmlib.ScMapID { - progHash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamProgHash)); +export class ImmutableSpawnParams extends wasmtypes.ScProxy { + progHash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamProgHash)); } } -export class MutableSpawnParams extends wasmlib.ScMapID { - progHash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamProgHash)); +export class MutableSpawnParams extends wasmtypes.ScProxy { + progHash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamProgHash)); } } -export class ImmutableTestEventLogGenericDataParams extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamCounter)); +export class ImmutableTestEventLogGenericDataParams extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamCounter)); } } -export class MutableTestEventLogGenericDataParams extends wasmlib.ScMapID { - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamCounter)); +export class MutableTestEventLogGenericDataParams extends wasmtypes.ScProxy { + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamCounter)); } } -export class ImmutableWithdrawToChainParams extends wasmlib.ScMapID { - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); +export class ImmutableWithdrawToChainParams extends wasmtypes.ScProxy { + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } } -export class MutableWithdrawToChainParams extends wasmlib.ScMapID { - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); +export class MutableWithdrawToChainParams extends wasmtypes.ScProxy { + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } } -export class ImmutableCheckContextFromViewEPParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); +export class ImmutableCheckContextFromViewEPParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } - chainOwnerID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwnerID)); + chainOwnerID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamChainOwnerID)); } - contractCreator(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractCreator)); + contractCreator(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamContractCreator)); } } -export class MutableCheckContextFromViewEPParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); +export class MutableCheckContextFromViewEPParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } - chainOwnerID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwnerID)); + chainOwnerID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamChainOwnerID)); } - contractCreator(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractCreator)); + contractCreator(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamContractCreator)); } } -export class ImmutableFibonacciParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class ImmutableFibonacciParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class MutableFibonacciParams extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamIntValue)); +export class MutableFibonacciParams extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamIntValue)); } } -export class ImmutableGetIntParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class ImmutableGetIntParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableGetIntParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class MutableGetIntParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableGetStringValueParams extends wasmlib.ScMapID { - varName(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamVarName)); +export class ImmutableGetStringValueParams extends wasmtypes.ScProxy { + varName(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamVarName)); } } -export class MutableGetStringValueParams extends wasmlib.ScMapID { - varName(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamVarName)); +export class MutableGetStringValueParams extends wasmtypes.ScProxy { + varName(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamVarName)); } } -export class ImmutablePassTypesViewParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutablePassTypesViewParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } - contractID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractID)); + contractID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamContractID)); } - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); } - hnameZero(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameZero)); + hnameZero(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHnameZero)); } - int64(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamInt64)); } - int64Zero(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64Zero)); + int64Zero(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamInt64Zero)); } - string(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamString)); } - stringZero(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamStringZero)); + stringZero(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamStringZero)); } } -export class MutablePassTypesViewParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutablePassTypesViewParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); } - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } - contractID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamContractID)); + contractID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamContractID)); } - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); } - hnameZero(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHnameZero)); + hnameZero(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHnameZero)); } - int64(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamInt64)); } - int64Zero(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64Zero)); + int64Zero(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamInt64Zero)); } - string(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamString)); } - stringZero(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamStringZero)); + stringZero(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamStringZero)); } } diff --git a/contracts/wasm/testcore/ts/testcore/results.ts b/contracts/wasm/testcore/ts/testcore/results.ts index 1a4abc5abf..97c1016750 100644 --- a/contracts/wasm/testcore/ts/testcore/results.ts +++ b/contracts/wasm/testcore/ts/testcore/results.ts @@ -5,189 +5,169 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableCallOnChainResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class ImmutableCallOnChainResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class MutableCallOnChainResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class MutableCallOnChainResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class ImmutableGetMintedSupplyResults extends wasmlib.ScMapID { - mintedColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultMintedColor)); +export class ImmutableGetMintedSupplyResults extends wasmtypes.ScProxy { + mintedColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ResultMintedColor)); } - mintedSupply(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMintedSupply)); + mintedSupply(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultMintedSupply)); } } -export class MutableGetMintedSupplyResults extends wasmlib.ScMapID { - mintedColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultMintedColor)); +export class MutableGetMintedSupplyResults extends wasmtypes.ScProxy { + mintedColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ResultMintedColor)); } - mintedSupply(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultMintedSupply)); + mintedSupply(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultMintedSupply)); } } -export class ImmutableRunRecursionResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class ImmutableRunRecursionResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class MutableRunRecursionResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class MutableRunRecursionResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class ImmutableTestChainOwnerIDFullResults extends wasmlib.ScMapID { - chainOwnerID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); +export class ImmutableTestChainOwnerIDFullResults extends wasmtypes.ScProxy { + chainOwnerID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); } } -export class MutableTestChainOwnerIDFullResults extends wasmlib.ScMapID { - chainOwnerID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); +export class MutableTestChainOwnerIDFullResults extends wasmtypes.ScProxy { + chainOwnerID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); } } -export class ImmutableFibonacciResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class ImmutableFibonacciResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class MutableFibonacciResults extends wasmlib.ScMapID { - intValue(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIntValue)); +export class MutableFibonacciResults extends wasmtypes.ScProxy { + intValue(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultIntValue)); } } -export class ImmutableGetCounterResults extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCounter)); +export class ImmutableGetCounterResults extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultCounter)); } } -export class MutableGetCounterResults extends wasmlib.ScMapID { - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultCounter)); +export class MutableGetCounterResults extends wasmtypes.ScProxy { + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultCounter)); } } -export class MapStringToImmutableInt64 { - objID: i32; +export class MapStringToImmutableInt64 extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getInt64(key: string): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.objID, wasmlib.Key32.fromString(key)); - } + getInt64(key: string): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class ImmutableGetIntResults extends wasmlib.ScMapID { - values(): sc.MapStringToImmutableInt64 { - return new sc.MapStringToImmutableInt64(this.mapID); +export class ImmutableGetIntResults extends wasmtypes.ScProxy { + values(): sc.MapStringToImmutableInt64 { + return new sc.MapStringToImmutableInt64(this.proxy); } } -export class MapStringToMutableInt64 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToMutableInt64 extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getInt64(key: string): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.objID, wasmlib.Key32.fromString(key)); - } + getInt64(key: string): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MutableGetIntResults extends wasmlib.ScMapID { - values(): sc.MapStringToMutableInt64 { - return new sc.MapStringToMutableInt64(this.mapID); +export class MutableGetIntResults extends wasmtypes.ScProxy { + values(): sc.MapStringToMutableInt64 { + return new sc.MapStringToMutableInt64(this.proxy); } } -export class MapStringToImmutableString { - objID: i32; +export class MapStringToImmutableString extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getString(key: string): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.objID, wasmlib.Key32.fromString(key)); - } + getString(key: string): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class ImmutableGetStringValueResults extends wasmlib.ScMapID { - vars(): sc.MapStringToImmutableString { - return new sc.MapStringToImmutableString(this.mapID); +export class ImmutableGetStringValueResults extends wasmtypes.ScProxy { + vars(): sc.MapStringToImmutableString { + return new sc.MapStringToImmutableString(this.proxy); } } -export class MapStringToMutableString { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToMutableString extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getString(key: string): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.objID, wasmlib.Key32.fromString(key)); - } + getString(key: string): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MutableGetStringValueResults extends wasmlib.ScMapID { - vars(): sc.MapStringToMutableString { - return new sc.MapStringToMutableString(this.mapID); +export class MutableGetStringValueResults extends wasmtypes.ScProxy { + vars(): sc.MapStringToMutableString { + return new sc.MapStringToMutableString(this.proxy); } } -export class ImmutableTestChainOwnerIDViewResults extends wasmlib.ScMapID { - chainOwnerID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); +export class ImmutableTestChainOwnerIDViewResults extends wasmtypes.ScProxy { + chainOwnerID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); } } -export class MutableTestChainOwnerIDViewResults extends wasmlib.ScMapID { - chainOwnerID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); +export class MutableTestChainOwnerIDViewResults extends wasmtypes.ScProxy { + chainOwnerID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); } } -export class ImmutableTestSandboxCallResults extends wasmlib.ScMapID { - sandboxCall(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultSandboxCall)); +export class ImmutableTestSandboxCallResults extends wasmtypes.ScProxy { + sandboxCall(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultSandboxCall)); } } -export class MutableTestSandboxCallResults extends wasmlib.ScMapID { - sandboxCall(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultSandboxCall)); +export class MutableTestSandboxCallResults extends wasmtypes.ScProxy { + sandboxCall(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultSandboxCall)); } } diff --git a/contracts/wasm/testcore/ts/testcore/state.ts b/contracts/wasm/testcore/ts/testcore/state.ts index 549c82f010..094f62726e 100644 --- a/contracts/wasm/testcore/ts/testcore/state.ts +++ b/contracts/wasm/testcore/ts/testcore/state.ts @@ -5,57 +5,53 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableTestCoreState extends wasmlib.ScMapID { - counter(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateCounter)); +export class ImmutableTestCoreState extends wasmtypes.ScProxy { + counter(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.StateCounter)); } - hnameEP(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.StateHnameEP)); + hnameEP(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.StateHnameEP)); } - ints(): sc.MapStringToImmutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateInts), wasmlib.TYPE_MAP); - return new sc.MapStringToImmutableInt64(mapID); + ints(): sc.MapStringToImmutableInt64 { + return new sc.MapStringToImmutableInt64(this.proxy.root(sc.StateInts)); } - mintedColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.StateMintedColor)); + mintedColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.StateMintedColor)); } - mintedSupply(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateMintedSupply)); + mintedSupply(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateMintedSupply)); } } -export class MutableTestCoreState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableTestCoreState { - const imm = new sc.ImmutableTestCoreState(); - imm.mapID = this.mapID; - return imm; +export class MutableTestCoreState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableTestCoreState { + return new sc.ImmutableTestCoreState(this.proxy); } - counter(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateCounter)); + counter(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.StateCounter)); } - hnameEP(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.StateHnameEP)); + hnameEP(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.StateHnameEP)); } - ints(): sc.MapStringToMutableInt64 { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateInts), wasmlib.TYPE_MAP); - return new sc.MapStringToMutableInt64(mapID); + ints(): sc.MapStringToMutableInt64 { + return new sc.MapStringToMutableInt64(this.proxy.root(sc.StateInts)); } - mintedColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.StateMintedColor)); + mintedColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.StateMintedColor)); } - mintedSupply(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateMintedSupply)); + mintedSupply(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateMintedSupply)); } } diff --git a/contracts/wasm/testcore/ts/testcore/testcore.ts b/contracts/wasm/testcore/ts/testcore/testcore.ts index 58e7e960ed..e50a7631ae 100644 --- a/contracts/wasm/testcore/ts/testcore/testcore.ts +++ b/contracts/wasm/testcore/ts/testcore/testcore.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes"; import * as coreaccounts from "wasmlib/coreaccounts" import * as coregovernance from "wasmlib/coregovernance" import * as sc from "./index"; @@ -32,11 +33,12 @@ export function funcCallOnChain(ctx: wasmlib.ScFuncContext, f: sc.CallOnChainCon counter.setValue(counter.value() + 1); - let parms = wasmlib.ScMutableMap.create(); - parms.getInt64(wasmlib.Key32.fromString(sc.ParamIntValue)).setValue(paramInt); - let ret = ctx.call(hnameContract, hnameEP, parms, null); - let retVal = ret.getInt64(wasmlib.Key32.fromString(sc.ResultIntValue)); - f.results.intValue().setValue(retVal.value()); + let params = new wasmlib.ScDict([]); + const key = wasmtypes.stringToBytes(sc.ParamIntValue); + params.set(key, wasmtypes.int64ToBytes(paramInt)) + let ret = ctx.call(hnameContract, hnameEP, params, null); + let retVal = wasmtypes.int64FromBytes(ret.get(key)); + f.results.intValue().setValue(retVal); } export function funcCheckContextFromFullEP(ctx: wasmlib.ScFuncContext, f: sc.CheckContextFromFullEPContext): void { @@ -54,8 +56,8 @@ export function funcDoNothing(ctx: wasmlib.ScFuncContext, f: sc.DoNothingContext export function funcGetMintedSupply(ctx: wasmlib.ScFuncContext, f: sc.GetMintedSupplyContext): void { let minted = ctx.minted(); let mintedColors = minted.colors(); - ctx.require(mintedColors.length() == 1, "test only supports one minted color"); - let color = mintedColors.getColor(0).value(); + ctx.require(mintedColors.length == 1, "test only supports one minted color"); + let color = mintedColors[0]; let amount = minted.balance(color); f.results.mintedSupply().setValue(amount); f.results.mintedColor().setValue(color); @@ -73,14 +75,14 @@ export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void { } export function funcPassTypesFull(ctx: wasmlib.ScFuncContext, f: sc.PassTypesFullContext): void { - let hash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString(sc.ParamHash)); + let hash = ctx.utility().hashBlake2b(wasmtypes.stringToBytes(sc.ParamHash)); ctx.require(f.params.hash().value().equals(hash), "Hash wrong"); ctx.require(f.params.int64().value() == 42, "int64 wrong"); ctx.require(f.params.int64Zero().value() == 0, "int64-0 wrong"); ctx.require(f.params.string().value() == sc.ParamString, "string wrong"); ctx.require(f.params.stringZero().value() == "", "string-0 wrong"); - ctx.require(f.params.hname().value().equals(wasmlib.ScHname.fromName(sc.ParamHname)), "Hname wrong"); - ctx.require(f.params.hnameZero().value().equals(new wasmlib.ScHname(0)), "Hname-0 wrong"); + ctx.require(f.params.hname().value().equals(ctx.utility().hname(sc.ParamHname)), "Hname wrong"); + ctx.require(f.params.hnameZero().value().equals(new wasmtypes.ScHname(0)), "Hname-0 wrong"); } export function funcRunRecursion(ctx: wasmlib.ScFuncContext, f: sc.RunRecursionContext): void { @@ -98,8 +100,8 @@ export function funcRunRecursion(ctx: wasmlib.ScFuncContext, f: sc.RunRecursionC } export function funcSendToAddress(ctx: wasmlib.ScFuncContext, f: sc.SendToAddressContext): void { - let balances = wasmlib.ScTransfers.fromBalances(ctx.balances()); - ctx.transferToAddress(f.params.address().value(), balances); + let transfer = wasmlib.ScTransfers.fromBalances(ctx.balances()); + ctx.transferToAddress(f.params.address().value(), transfer); } export function funcSetInt(ctx: wasmlib.ScFuncContext, f: sc.SetIntContext): void { @@ -109,9 +111,9 @@ export function funcSetInt(ctx: wasmlib.ScFuncContext, f: sc.SetIntContext): voi export function funcSpawn(ctx: wasmlib.ScFuncContext, f: sc.SpawnContext): void { let spawnName = sc.ScName + "_spawned"; let spawnDescr = "spawned contract description"; - ctx.deploy(f.params.progHash().value(), spawnName, spawnDescr, null); + ctx.deployContract(f.params.progHash().value(), spawnName, spawnDescr, null); - let spawnHname = wasmlib.ScHname.fromName(spawnName); + let spawnHname = ctx.utility().hname(spawnName); for (let i = 0; i < 5; i++) { ctx.call(spawnHname, sc.HFuncIncCounter, null, null); } @@ -139,8 +141,8 @@ export function funcTestChainOwnerIDFull(ctx: wasmlib.ScFuncContext, f: sc.TestC export function funcTestEventLogDeploy(ctx: wasmlib.ScFuncContext, f: sc.TestEventLogDeployContext): void { // deploy the same contract with another name - let programHash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString("testcore")); - ctx.deploy(programHash, CONTRACT_NAME_DEPLOYED, "test contract deploy log", null); + let programHash = ctx.utility().hashBlake2b(wasmtypes.stringToBytes("testcore")); + ctx.deployContract(programHash, CONTRACT_NAME_DEPLOYED, "test contract deploy log", null); } export function funcTestEventLogEventData(ctx: wasmlib.ScFuncContext, f: sc.TestEventLogEventDataContext): void { @@ -158,7 +160,7 @@ export function funcTestPanicFullEP(ctx: wasmlib.ScFuncContext, f: sc.TestPanicF export function funcWithdrawToChain(ctx: wasmlib.ScFuncContext, f: sc.WithdrawToChainContext): void { let xx = coreaccounts.ScFuncs.withdraw(ctx); - xx.func.transferIotas(1).postToChain(f.params.chainID().value()); + xx.func.postToChain(f.params.chainID().value()); } export function viewCheckContextFromViewEP(ctx: wasmlib.ScViewContext, f: sc.CheckContextFromViewEPContext): void { @@ -207,14 +209,14 @@ export function viewJustView(ctx: wasmlib.ScViewContext, f: sc.JustViewContext): } export function viewPassTypesView(ctx: wasmlib.ScViewContext, f: sc.PassTypesViewContext): void { - let hash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString(sc.ParamHash)); + let hash = ctx.utility().hashBlake2b(wasmtypes.stringToBytes(sc.ParamHash)); ctx.require(f.params.hash().value().equals(hash), "Hash wrong"); ctx.require(f.params.int64().value() == 42, "int64 wrong"); ctx.require(f.params.int64Zero().value() == 0, "int64-0 wrong"); ctx.require(f.params.string().value() == sc.ParamString, "string wrong"); ctx.require(f.params.stringZero().value() == "", "string-0 wrong"); - ctx.require(f.params.hname().value().equals(wasmlib.ScHname.fromName(sc.ParamHname)), "Hname wrong"); - ctx.require(f.params.hnameZero().value().equals(new wasmlib.ScHname(0)), "Hname-0 wrong"); + ctx.require(f.params.hname().value().equals(ctx.utility().hname(sc.ParamHname)), "Hname wrong"); + ctx.require(f.params.hnameZero().value().equals(new wasmtypes.ScHname(0)), "Hname-0 wrong"); } export function viewTestCallPanicViewEPFromView(ctx: wasmlib.ScViewContext, f: sc.TestCallPanicViewEPFromViewContext): void { diff --git a/contracts/wasm/testwasmlib/Cargo.toml b/contracts/wasm/testwasmlib/Cargo.toml index e789cadf3e..58941f66a4 100644 --- a/contracts/wasm/testwasmlib/Cargo.toml +++ b/contracts/wasm/testwasmlib/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } console_error_panic_hook = { version = "0.1.6", optional = true } wee_alloc = { version = "0.4.5", optional = true } diff --git a/contracts/wasm/testwasmlib/go/main.go b/contracts/wasm/testwasmlib/go/main.go index 5138f55c33..ea02e20cdb 100644 --- a/contracts/wasm/testwasmlib/go/main.go +++ b/contracts/wasm/testwasmlib/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/testwasmlib/go/testwasmlib" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + testwasmlib.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - testwasmlib.OnLoad() + testwasmlib.OnLoad(-1) } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/consts.go b/contracts/wasm/testwasmlib/go/testwasmlib/consts.go index 7b8cefa6f3..6c695be6f5 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/consts.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/consts.go @@ -7,12 +7,12 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "testwasmlib" ScDescription = "Exercise several aspects of WasmLib" - HScName = wasmlib.ScHname(0x89703a45) + HScName = wasmtypes.ScHname(0x89703a45) ) const ( @@ -59,11 +59,10 @@ const ( ) const ( + FuncArrayAppend = "arrayAppend" FuncArrayClear = "arrayClear" - FuncArrayCreate = "arrayCreate" FuncArraySet = "arraySet" FuncMapClear = "mapClear" - FuncMapCreate = "mapCreate" FuncMapSet = "mapSet" FuncParamTypes = "paramTypes" FuncRandom = "random" @@ -78,20 +77,19 @@ const ( ) const ( - HFuncArrayClear = wasmlib.ScHname(0x88021821) - HFuncArrayCreate = wasmlib.ScHname(0x1ed5b23b) - HFuncArraySet = wasmlib.ScHname(0x2c4150b3) - HFuncMapClear = wasmlib.ScHname(0x027f215a) - HFuncMapCreate = wasmlib.ScHname(0x6295d599) - HFuncMapSet = wasmlib.ScHname(0xf2260404) - HFuncParamTypes = wasmlib.ScHname(0x6921c4cd) - HFuncRandom = wasmlib.ScHname(0xe86c97ca) - HFuncTriggerEvent = wasmlib.ScHname(0xd5438ac6) - HViewArrayLength = wasmlib.ScHname(0x3a831021) - HViewArrayValue = wasmlib.ScHname(0x662dbd81) - HViewBlockRecord = wasmlib.ScHname(0xad13b2f8) - HViewBlockRecords = wasmlib.ScHname(0x16e249ea) - HViewGetRandom = wasmlib.ScHname(0x46263045) - HViewIotaBalance = wasmlib.ScHname(0x9d3920bd) - HViewMapValue = wasmlib.ScHname(0x23149bef) + HFuncArrayAppend = wasmtypes.ScHname(0x612f835f) + HFuncArrayClear = wasmtypes.ScHname(0x88021821) + HFuncArraySet = wasmtypes.ScHname(0x2c4150b3) + HFuncMapClear = wasmtypes.ScHname(0x027f215a) + HFuncMapSet = wasmtypes.ScHname(0xf2260404) + HFuncParamTypes = wasmtypes.ScHname(0x6921c4cd) + HFuncRandom = wasmtypes.ScHname(0xe86c97ca) + HFuncTriggerEvent = wasmtypes.ScHname(0xd5438ac6) + HViewArrayLength = wasmtypes.ScHname(0x3a831021) + HViewArrayValue = wasmtypes.ScHname(0x662dbd81) + HViewBlockRecord = wasmtypes.ScHname(0xad13b2f8) + HViewBlockRecords = wasmtypes.ScHname(0x16e249ea) + HViewGetRandom = wasmtypes.ScHname(0x46263045) + HViewIotaBalance = wasmtypes.ScHname(0x9d3920bd) + HViewMapValue = wasmtypes.ScHname(0x23149bef) ) diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/contract.go b/contracts/wasm/testwasmlib/go/testwasmlib/contract.go index 87309712b0..5e8887a985 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/contract.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/contract.go @@ -7,16 +7,16 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" -type ArrayClearCall struct { +type ArrayAppendCall struct { Func *wasmlib.ScFunc - Params MutableArrayClearParams + Params MutableArrayAppendParams } -type ArrayCreateCall struct { +type ArrayClearCall struct { Func *wasmlib.ScFunc - Params MutableArrayCreateParams + Params MutableArrayClearParams } type ArraySetCall struct { @@ -29,11 +29,6 @@ type MapClearCall struct { Params MutableMapClearParams } -type MapCreateCall struct { - Func *wasmlib.ScFunc - Params MutableMapCreateParams -} - type MapSetCall struct { Func *wasmlib.ScFunc Params MutableMapSetParams @@ -97,45 +92,39 @@ type Funcs struct{} var ScFuncs Funcs -func (sc Funcs) ArrayClear(ctx wasmlib.ScFuncCallContext) *ArrayClearCall { - f := &ArrayClearCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncArrayClear)} - f.Func.SetPtrs(&f.Params.id, nil) +func (sc Funcs) ArrayAppend(ctx wasmlib.ScFuncCallContext) *ArrayAppendCall { + f := &ArrayAppendCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncArrayAppend)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } -func (sc Funcs) ArrayCreate(ctx wasmlib.ScFuncCallContext) *ArrayCreateCall { - f := &ArrayCreateCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncArrayCreate)} - f.Func.SetPtrs(&f.Params.id, nil) +func (sc Funcs) ArrayClear(ctx wasmlib.ScFuncCallContext) *ArrayClearCall { + f := &ArrayClearCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncArrayClear)} + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) ArraySet(ctx wasmlib.ScFuncCallContext) *ArraySetCall { f := &ArraySetCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncArraySet)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) MapClear(ctx wasmlib.ScFuncCallContext) *MapClearCall { f := &MapClearCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMapClear)} - f.Func.SetPtrs(&f.Params.id, nil) - return f -} - -func (sc Funcs) MapCreate(ctx wasmlib.ScFuncCallContext) *MapCreateCall { - f := &MapCreateCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMapCreate)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) MapSet(ctx wasmlib.ScFuncCallContext) *MapSetCall { f := &MapSetCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMapSet)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) ParamTypes(ctx wasmlib.ScFuncCallContext) *ParamTypesCall { f := &ParamTypesCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncParamTypes)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -145,48 +134,53 @@ func (sc Funcs) Random(ctx wasmlib.ScFuncCallContext) *RandomCall { func (sc Funcs) TriggerEvent(ctx wasmlib.ScFuncCallContext) *TriggerEventCall { f := &TriggerEventCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTriggerEvent)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) ArrayLength(ctx wasmlib.ScViewCallContext) *ArrayLengthCall { f := &ArrayLengthCall{Func: wasmlib.NewScView(ctx, HScName, HViewArrayLength)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) ArrayValue(ctx wasmlib.ScViewCallContext) *ArrayValueCall { f := &ArrayValueCall{Func: wasmlib.NewScView(ctx, HScName, HViewArrayValue)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) BlockRecord(ctx wasmlib.ScViewCallContext) *BlockRecordCall { f := &BlockRecordCall{Func: wasmlib.NewScView(ctx, HScName, HViewBlockRecord)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) BlockRecords(ctx wasmlib.ScViewCallContext) *BlockRecordsCall { f := &BlockRecordsCall{Func: wasmlib.NewScView(ctx, HScName, HViewBlockRecords)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetRandom(ctx wasmlib.ScViewCallContext) *GetRandomCall { f := &GetRandomCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetRandom)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) IotaBalance(ctx wasmlib.ScViewCallContext) *IotaBalanceCall { f := &IotaBalanceCall{Func: wasmlib.NewScView(ctx, HScName, HViewIotaBalance)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) MapValue(ctx wasmlib.ScViewCallContext) *MapValueCall { f := &MapValueCall{Func: wasmlib.NewScView(ctx, HScName, HViewMapValue)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/events.go b/contracts/wasm/testwasmlib/go/testwasmlib/events.go index eb9574346e..2890f88e8e 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/events.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/events.go @@ -7,13 +7,16 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) type TestWasmLibEvents struct{} -func (e TestWasmLibEvents) Test(address wasmlib.ScAddress, name string) { - wasmlib.NewEventEncoder("testwasmlib.test"). - Address(address). - String(name). - Emit() +func (e TestWasmLibEvents) Test(address wasmtypes.ScAddress, name string) { + evt := wasmlib.NewEventEncoder("testwasmlib.test") + evt.Encode(wasmtypes.AddressToString(address)) + evt.Encode(wasmtypes.StringToString(name)) + evt.Emit() } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/keys.go b/contracts/wasm/testwasmlib/go/testwasmlib/keys.go deleted file mode 100644 index 9b5e7ac61f..0000000000 --- a/contracts/wasm/testwasmlib/go/testwasmlib/keys.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package testwasmlib - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamAddress = 0 - IdxParamAgentID = 1 - IdxParamBlockIndex = 2 - IdxParamBool = 3 - IdxParamBytes = 4 - IdxParamChainID = 5 - IdxParamColor = 6 - IdxParamHash = 7 - IdxParamHname = 8 - IdxParamIndex = 9 - IdxParamInt16 = 10 - IdxParamInt32 = 11 - IdxParamInt64 = 12 - IdxParamInt8 = 13 - IdxParamKey = 14 - IdxParamName = 15 - IdxParamParam = 16 - IdxParamRecordIndex = 17 - IdxParamRequestID = 18 - IdxParamString = 19 - IdxParamUint16 = 20 - IdxParamUint32 = 21 - IdxParamUint64 = 22 - IdxParamUint8 = 23 - IdxParamValue = 24 - - IdxResultCount = 25 - IdxResultIotas = 26 - IdxResultLength = 27 - IdxResultRandom = 28 - IdxResultRecord = 29 - IdxResultValue = 30 - - IdxStateArrays = 31 - IdxStateMaps = 32 - IdxStateRandom = 33 -) - -const keyMapLen = 34 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamAddress, - ParamAgentID, - ParamBlockIndex, - ParamBool, - ParamBytes, - ParamChainID, - ParamColor, - ParamHash, - ParamHname, - ParamIndex, - ParamInt16, - ParamInt32, - ParamInt64, - ParamInt8, - ParamKey, - ParamName, - ParamParam, - ParamRecordIndex, - ParamRequestID, - ParamString, - ParamUint16, - ParamUint32, - ParamUint64, - ParamUint8, - ParamValue, - ResultCount, - ResultIotas, - ResultLength, - ResultRandom, - ResultRecord, - ResultValue, - StateArrays, - StateMaps, - StateRandom, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/lib.go b/contracts/wasm/testwasmlib/go/testwasmlib/lib.go index 1356e5135a..47d0612fc1 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/lib.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/lib.go @@ -7,72 +7,97 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncArrayClear, funcArrayClearThunk) - exports.AddFunc(FuncArrayCreate, funcArrayCreateThunk) - exports.AddFunc(FuncArraySet, funcArraySetThunk) - exports.AddFunc(FuncMapClear, funcMapClearThunk) - exports.AddFunc(FuncMapCreate, funcMapCreateThunk) - exports.AddFunc(FuncMapSet, funcMapSetThunk) - exports.AddFunc(FuncParamTypes, funcParamTypesThunk) - exports.AddFunc(FuncRandom, funcRandomThunk) - exports.AddFunc(FuncTriggerEvent, funcTriggerEventThunk) - exports.AddView(ViewArrayLength, viewArrayLengthThunk) - exports.AddView(ViewArrayValue, viewArrayValueThunk) - exports.AddView(ViewBlockRecord, viewBlockRecordThunk) - exports.AddView(ViewBlockRecords, viewBlockRecordsThunk) - exports.AddView(ViewGetRandom, viewGetRandomThunk) - exports.AddView(ViewIotaBalance, viewIotaBalanceThunk) - exports.AddView(ViewMapValue, viewMapValueThunk) - - for i, key := range keyMap { - idxMap[i] = key.KeyID() +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncArrayAppend, + FuncArrayClear, + FuncArraySet, + FuncMapClear, + FuncMapSet, + FuncParamTypes, + FuncRandom, + FuncTriggerEvent, + ViewArrayLength, + ViewArrayValue, + ViewBlockRecord, + ViewBlockRecords, + ViewGetRandom, + ViewIotaBalance, + ViewMapValue, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcArrayAppendThunk, + funcArrayClearThunk, + funcArraySetThunk, + funcMapClearThunk, + funcMapSetThunk, + funcParamTypesThunk, + funcRandomThunk, + funcTriggerEventThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewArrayLengthThunk, + viewArrayValueThunk, + viewBlockRecordThunk, + viewBlockRecordsThunk, + viewGetRandomThunk, + viewIotaBalanceThunk, + viewMapValueThunk, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } -type ArrayClearContext struct { +type ArrayAppendContext struct { Events TestWasmLibEvents - Params ImmutableArrayClearParams + Params ImmutableArrayAppendParams State MutableTestWasmLibState } -func funcArrayClearThunk(ctx wasmlib.ScFuncContext) { - ctx.Log("testwasmlib.funcArrayClear") - f := &ArrayClearContext{ - Params: ImmutableArrayClearParams{ - id: wasmlib.OBJ_ID_PARAMS, +func funcArrayAppendThunk(ctx wasmlib.ScFuncContext) { + ctx.Log("testwasmlib.funcArrayAppend") + f := &ArrayAppendContext{ + Params: ImmutableArrayAppendParams{ + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") - funcArrayClear(ctx, f) - ctx.Log("testwasmlib.funcArrayClear ok") + ctx.Require(f.Params.Value().Exists(), "missing mandatory value") + funcArrayAppend(ctx, f) + ctx.Log("testwasmlib.funcArrayAppend ok") } -type ArrayCreateContext struct { +type ArrayClearContext struct { Events TestWasmLibEvents - Params ImmutableArrayCreateParams + Params ImmutableArrayClearParams State MutableTestWasmLibState } -func funcArrayCreateThunk(ctx wasmlib.ScFuncContext) { - ctx.Log("testwasmlib.funcArrayCreate") - f := &ArrayCreateContext{ - Params: ImmutableArrayCreateParams{ - id: wasmlib.OBJ_ID_PARAMS, +func funcArrayClearThunk(ctx wasmlib.ScFuncContext) { + ctx.Log("testwasmlib.funcArrayClear") + f := &ArrayClearContext{ + Params: ImmutableArrayClearParams{ + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") - funcArrayCreate(ctx, f) - ctx.Log("testwasmlib.funcArrayCreate ok") + funcArrayClear(ctx, f) + ctx.Log("testwasmlib.funcArrayClear ok") } type ArraySetContext struct { @@ -85,10 +110,10 @@ func funcArraySetThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcArraySet") f := &ArraySetContext{ Params: ImmutableArraySetParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Index().Exists(), "missing mandatory index") @@ -108,10 +133,10 @@ func funcMapClearThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcMapClear") f := &MapClearContext{ Params: ImmutableMapClearParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") @@ -119,27 +144,6 @@ func funcMapClearThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcMapClear ok") } -type MapCreateContext struct { - Events TestWasmLibEvents - Params ImmutableMapCreateParams - State MutableTestWasmLibState -} - -func funcMapCreateThunk(ctx wasmlib.ScFuncContext) { - ctx.Log("testwasmlib.funcMapCreate") - f := &MapCreateContext{ - Params: ImmutableMapCreateParams{ - id: wasmlib.OBJ_ID_PARAMS, - }, - State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, - }, - } - ctx.Require(f.Params.Name().Exists(), "missing mandatory name") - funcMapCreate(ctx, f) - ctx.Log("testwasmlib.funcMapCreate ok") -} - type MapSetContext struct { Events TestWasmLibEvents Params ImmutableMapSetParams @@ -150,10 +154,10 @@ func funcMapSetThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcMapSet") f := &MapSetContext{ Params: ImmutableMapSetParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Key().Exists(), "missing mandatory key") @@ -173,10 +177,10 @@ func funcParamTypesThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcParamTypes") f := &ParamTypesContext{ Params: ImmutableParamTypesParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcParamTypes(ctx, f) @@ -192,7 +196,7 @@ func funcRandomThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcRandom") f := &RandomContext{ State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcRandom(ctx, f) @@ -209,10 +213,10 @@ func funcTriggerEventThunk(ctx wasmlib.ScFuncContext) { ctx.Log("testwasmlib.funcTriggerEvent") f := &TriggerEventContext{ Params: ImmutableTriggerEventParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Address().Exists(), "missing mandatory address") @@ -229,19 +233,21 @@ type ArrayLengthContext struct { func viewArrayLengthThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewArrayLength") + results := wasmlib.NewScDict() f := &ArrayLengthContext{ Params: ImmutableArrayLengthParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableArrayLengthResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Name().Exists(), "missing mandatory name") viewArrayLength(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewArrayLength ok") } @@ -253,20 +259,22 @@ type ArrayValueContext struct { func viewArrayValueThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewArrayValue") + results := wasmlib.NewScDict() f := &ArrayValueContext{ Params: ImmutableArrayValueParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableArrayValueResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Index().Exists(), "missing mandatory index") ctx.Require(f.Params.Name().Exists(), "missing mandatory name") viewArrayValue(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewArrayValue ok") } @@ -278,20 +286,22 @@ type BlockRecordContext struct { func viewBlockRecordThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewBlockRecord") + results := wasmlib.NewScDict() f := &BlockRecordContext{ Params: ImmutableBlockRecordParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableBlockRecordResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.BlockIndex().Exists(), "missing mandatory blockIndex") ctx.Require(f.Params.RecordIndex().Exists(), "missing mandatory recordIndex") viewBlockRecord(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewBlockRecord ok") } @@ -303,19 +313,21 @@ type BlockRecordsContext struct { func viewBlockRecordsThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewBlockRecords") + results := wasmlib.NewScDict() f := &BlockRecordsContext{ Params: ImmutableBlockRecordsParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableBlockRecordsResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.BlockIndex().Exists(), "missing mandatory blockIndex") viewBlockRecords(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewBlockRecords ok") } @@ -326,15 +338,17 @@ type GetRandomContext struct { func viewGetRandomThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewGetRandom") + results := wasmlib.NewScDict() f := &GetRandomContext{ Results: MutableGetRandomResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetRandom(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewGetRandom ok") } @@ -345,15 +359,17 @@ type IotaBalanceContext struct { func viewIotaBalanceThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewIotaBalance") + results := wasmlib.NewScDict() f := &IotaBalanceContext{ Results: MutableIotaBalanceResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewIotaBalance(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewIotaBalance ok") } @@ -365,19 +381,21 @@ type MapValueContext struct { func viewMapValueThunk(ctx wasmlib.ScViewContext) { ctx.Log("testwasmlib.viewMapValue") + results := wasmlib.NewScDict() f := &MapValueContext{ Params: ImmutableMapValueParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, Results: MutableMapValueResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutableTestWasmLibState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Key().Exists(), "missing mandatory key") ctx.Require(f.Params.Name().Exists(), "missing mandatory name") viewMapValue(ctx, f) + ctx.Results(results) ctx.Log("testwasmlib.viewMapValue ok") } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/params.go b/contracts/wasm/testwasmlib/go/testwasmlib/params.go index dd89b42103..46d7b5e5a7 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/params.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/params.go @@ -7,440 +7,434 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" -type ImmutableArrayClearParams struct { - id int32 -} - -func (s ImmutableArrayClearParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) -} - -type MutableArrayClearParams struct { - id int32 +type ImmutableArrayAppendParams struct { + proxy wasmtypes.Proxy } -func (s MutableArrayClearParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableArrayAppendParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -type ImmutableArrayCreateParams struct { - id int32 +func (s ImmutableArrayAppendParams) Value() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamValue)) } -func (s ImmutableArrayCreateParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +type MutableArrayAppendParams struct { + proxy wasmtypes.Proxy } -type MutableArrayCreateParams struct { - id int32 +func (s MutableArrayAppendParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } -func (s MutableArrayCreateParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableArrayAppendParams) Value() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamValue)) } -type ImmutableArraySetParams struct { - id int32 +type ImmutableArrayClearParams struct { + proxy wasmtypes.Proxy } -func (s ImmutableArraySetParams) Index() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamIndex)) +func (s ImmutableArrayClearParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -func (s ImmutableArraySetParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +type MutableArrayClearParams struct { + proxy wasmtypes.Proxy } -func (s ImmutableArraySetParams) Value() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamValue)) +func (s MutableArrayClearParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } -type MutableArraySetParams struct { - id int32 +type ImmutableArraySetParams struct { + proxy wasmtypes.Proxy } -func (s MutableArraySetParams) Index() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamIndex)) +func (s ImmutableArraySetParams) Index() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamIndex)) } -func (s MutableArraySetParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableArraySetParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -func (s MutableArraySetParams) Value() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamValue)) +func (s ImmutableArraySetParams) Value() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamValue)) } -type ImmutableMapClearParams struct { - id int32 +type MutableArraySetParams struct { + proxy wasmtypes.Proxy } -func (s ImmutableMapClearParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableArraySetParams) Index() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamIndex)) } -type MutableMapClearParams struct { - id int32 +func (s MutableArraySetParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } -func (s MutableMapClearParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableArraySetParams) Value() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamValue)) } -type ImmutableMapCreateParams struct { - id int32 +type ImmutableMapClearParams struct { + proxy wasmtypes.Proxy } -func (s ImmutableMapCreateParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableMapClearParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -type MutableMapCreateParams struct { - id int32 +type MutableMapClearParams struct { + proxy wasmtypes.Proxy } -func (s MutableMapCreateParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableMapClearParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableMapSetParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMapSetParams) Key() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamKey)) +func (s ImmutableMapSetParams) Key() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamKey)) } -func (s ImmutableMapSetParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableMapSetParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } -func (s ImmutableMapSetParams) Value() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamValue)) +func (s ImmutableMapSetParams) Value() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamValue)) } type MutableMapSetParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMapSetParams) Key() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamKey)) +func (s MutableMapSetParams) Key() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamKey)) } -func (s MutableMapSetParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableMapSetParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } -func (s MutableMapSetParams) Value() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamValue)) +func (s MutableMapSetParams) Value() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamValue)) } type MapStringToImmutableBytes struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapStringToImmutableBytes) GetBytes(key string) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToImmutableBytes) GetBytes(key string) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(m.proxy.Key(wasmtypes.StringToBytes(key))) } type ImmutableParamTypesParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableParamTypesParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutableParamTypesParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } -func (s ImmutableParamTypesParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s ImmutableParamTypesParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s ImmutableParamTypesParams) Bool() wasmlib.ScImmutableBool { - return wasmlib.NewScImmutableBool(s.id, wasmlib.KeyID(ParamBool)) +func (s ImmutableParamTypesParams) Bool() wasmtypes.ScImmutableBool { + return wasmtypes.NewScImmutableBool(s.proxy.Root(ParamBool)) } -func (s ImmutableParamTypesParams) Bytes() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ParamBytes)) +func (s ImmutableParamTypesParams) Bytes() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ParamBytes)) } -func (s ImmutableParamTypesParams) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s ImmutableParamTypesParams) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ParamChainID)) } -func (s ImmutableParamTypesParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableParamTypesParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } -func (s ImmutableParamTypesParams) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s ImmutableParamTypesParams) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamHash)) } -func (s ImmutableParamTypesParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s ImmutableParamTypesParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) } -func (s ImmutableParamTypesParams) Int16() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ParamInt16)) +func (s ImmutableParamTypesParams) Int16() wasmtypes.ScImmutableInt16 { + return wasmtypes.NewScImmutableInt16(s.proxy.Root(ParamInt16)) } -func (s ImmutableParamTypesParams) Int32() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamInt32)) +func (s ImmutableParamTypesParams) Int32() wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(s.proxy.Root(ParamInt32)) } -func (s ImmutableParamTypesParams) Int64() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s ImmutableParamTypesParams) Int64() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamInt64)) } -func (s ImmutableParamTypesParams) Int8() wasmlib.ScImmutableInt8 { - return wasmlib.NewScImmutableInt8(s.id, wasmlib.KeyID(ParamInt8)) +func (s ImmutableParamTypesParams) Int8() wasmtypes.ScImmutableInt8 { + return wasmtypes.NewScImmutableInt8(s.proxy.Root(ParamInt8)) } func (s ImmutableParamTypesParams) Param() MapStringToImmutableBytes { - return MapStringToImmutableBytes{objID: s.id} + //nolint:gosimple + return MapStringToImmutableBytes{proxy: s.proxy} } -func (s ImmutableParamTypesParams) RequestID() wasmlib.ScImmutableRequestID { - return wasmlib.NewScImmutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) +func (s ImmutableParamTypesParams) RequestID() wasmtypes.ScImmutableRequestID { + return wasmtypes.NewScImmutableRequestID(s.proxy.Root(ParamRequestID)) } -func (s ImmutableParamTypesParams) String() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamString)) +func (s ImmutableParamTypesParams) String() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamString)) } -func (s ImmutableParamTypesParams) Uint16() wasmlib.ScImmutableUint16 { - return wasmlib.NewScImmutableUint16(s.id, wasmlib.KeyID(ParamUint16)) +func (s ImmutableParamTypesParams) Uint16() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(ParamUint16)) } -func (s ImmutableParamTypesParams) Uint32() wasmlib.ScImmutableUint32 { - return wasmlib.NewScImmutableUint32(s.id, wasmlib.KeyID(ParamUint32)) +func (s ImmutableParamTypesParams) Uint32() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamUint32)) } -func (s ImmutableParamTypesParams) Uint64() wasmlib.ScImmutableUint64 { - return wasmlib.NewScImmutableUint64(s.id, wasmlib.KeyID(ParamUint64)) +func (s ImmutableParamTypesParams) Uint64() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ParamUint64)) } -func (s ImmutableParamTypesParams) Uint8() wasmlib.ScImmutableUint8 { - return wasmlib.NewScImmutableUint8(s.id, wasmlib.KeyID(ParamUint8)) +func (s ImmutableParamTypesParams) Uint8() wasmtypes.ScImmutableUint8 { + return wasmtypes.NewScImmutableUint8(s.proxy.Root(ParamUint8)) } type MapStringToMutableBytes struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableBytes) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapStringToMutableBytes) GetBytes(key string) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToMutableBytes) GetBytes(key string) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(m.proxy.Key(wasmtypes.StringToBytes(key))) } type MutableParamTypesParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableParamTypesParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutableParamTypesParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } -func (s MutableParamTypesParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) +func (s MutableParamTypesParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) } -func (s MutableParamTypesParams) Bool() wasmlib.ScMutableBool { - return wasmlib.NewScMutableBool(s.id, wasmlib.KeyID(ParamBool)) +func (s MutableParamTypesParams) Bool() wasmtypes.ScMutableBool { + return wasmtypes.NewScMutableBool(s.proxy.Root(ParamBool)) } -func (s MutableParamTypesParams) Bytes() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ParamBytes)) +func (s MutableParamTypesParams) Bytes() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ParamBytes)) } -func (s MutableParamTypesParams) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ParamChainID)) +func (s MutableParamTypesParams) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ParamChainID)) } -func (s MutableParamTypesParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableParamTypesParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } -func (s MutableParamTypesParams) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamHash)) +func (s MutableParamTypesParams) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamHash)) } -func (s MutableParamTypesParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) +func (s MutableParamTypesParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) } -func (s MutableParamTypesParams) Int16() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ParamInt16)) +func (s MutableParamTypesParams) Int16() wasmtypes.ScMutableInt16 { + return wasmtypes.NewScMutableInt16(s.proxy.Root(ParamInt16)) } -func (s MutableParamTypesParams) Int32() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamInt32)) +func (s MutableParamTypesParams) Int32() wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(s.proxy.Root(ParamInt32)) } -func (s MutableParamTypesParams) Int64() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamInt64)) +func (s MutableParamTypesParams) Int64() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamInt64)) } -func (s MutableParamTypesParams) Int8() wasmlib.ScMutableInt8 { - return wasmlib.NewScMutableInt8(s.id, wasmlib.KeyID(ParamInt8)) +func (s MutableParamTypesParams) Int8() wasmtypes.ScMutableInt8 { + return wasmtypes.NewScMutableInt8(s.proxy.Root(ParamInt8)) } func (s MutableParamTypesParams) Param() MapStringToMutableBytes { - return MapStringToMutableBytes{objID: s.id} + //nolint:gosimple + return MapStringToMutableBytes{proxy: s.proxy} } -func (s MutableParamTypesParams) RequestID() wasmlib.ScMutableRequestID { - return wasmlib.NewScMutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) +func (s MutableParamTypesParams) RequestID() wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(s.proxy.Root(ParamRequestID)) } -func (s MutableParamTypesParams) String() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamString)) +func (s MutableParamTypesParams) String() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamString)) } -func (s MutableParamTypesParams) Uint16() wasmlib.ScMutableUint16 { - return wasmlib.NewScMutableUint16(s.id, wasmlib.KeyID(ParamUint16)) +func (s MutableParamTypesParams) Uint16() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(ParamUint16)) } -func (s MutableParamTypesParams) Uint32() wasmlib.ScMutableUint32 { - return wasmlib.NewScMutableUint32(s.id, wasmlib.KeyID(ParamUint32)) +func (s MutableParamTypesParams) Uint32() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamUint32)) } -func (s MutableParamTypesParams) Uint64() wasmlib.ScMutableUint64 { - return wasmlib.NewScMutableUint64(s.id, wasmlib.KeyID(ParamUint64)) +func (s MutableParamTypesParams) Uint64() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ParamUint64)) } -func (s MutableParamTypesParams) Uint8() wasmlib.ScMutableUint8 { - return wasmlib.NewScMutableUint8(s.id, wasmlib.KeyID(ParamUint8)) +func (s MutableParamTypesParams) Uint8() wasmtypes.ScMutableUint8 { + return wasmtypes.NewScMutableUint8(s.proxy.Root(ParamUint8)) } type ImmutableTriggerEventParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTriggerEventParams) Address() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s ImmutableTriggerEventParams) Address() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamAddress)) } -func (s ImmutableTriggerEventParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableTriggerEventParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableTriggerEventParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTriggerEventParams) Address() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamAddress)) +func (s MutableTriggerEventParams) Address() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamAddress)) } -func (s MutableTriggerEventParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableTriggerEventParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableArrayLengthParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableArrayLengthParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableArrayLengthParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableArrayLengthParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableArrayLengthParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableArrayLengthParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableArrayValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableArrayValueParams) Index() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamIndex)) +func (s ImmutableArrayValueParams) Index() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamIndex)) } -func (s ImmutableArrayValueParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableArrayValueParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableArrayValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableArrayValueParams) Index() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamIndex)) +func (s MutableArrayValueParams) Index() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamIndex)) } -func (s MutableArrayValueParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableArrayValueParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } type ImmutableBlockRecordParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBlockRecordParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) +func (s ImmutableBlockRecordParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) } -func (s ImmutableBlockRecordParams) RecordIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamRecordIndex)) +func (s ImmutableBlockRecordParams) RecordIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamRecordIndex)) } type MutableBlockRecordParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBlockRecordParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) +func (s MutableBlockRecordParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) } -func (s MutableBlockRecordParams) RecordIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamRecordIndex)) +func (s MutableBlockRecordParams) RecordIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamRecordIndex)) } type ImmutableBlockRecordsParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBlockRecordsParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) +func (s ImmutableBlockRecordsParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) } type MutableBlockRecordsParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBlockRecordsParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) +func (s MutableBlockRecordsParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) } type ImmutableMapValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMapValueParams) Key() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamKey)) +func (s ImmutableMapValueParams) Key() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamKey)) } -func (s ImmutableMapValueParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) +func (s ImmutableMapValueParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) } type MutableMapValueParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMapValueParams) Key() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamKey)) +func (s MutableMapValueParams) Key() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamKey)) } -func (s MutableMapValueParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) +func (s MutableMapValueParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/results.go b/contracts/wasm/testwasmlib/go/testwasmlib/results.go index 4426bd9cea..aaf0db60a1 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/results.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/results.go @@ -7,116 +7,116 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableArrayLengthResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableArrayLengthResults) Length() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultLength)) +func (s ImmutableArrayLengthResults) Length() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultLength)) } type MutableArrayLengthResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableArrayLengthResults) Length() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultLength)) +func (s MutableArrayLengthResults) Length() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultLength)) } type ImmutableArrayValueResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableArrayValueResults) Value() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultValue)) +func (s ImmutableArrayValueResults) Value() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultValue)) } type MutableArrayValueResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableArrayValueResults) Value() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultValue)) +func (s MutableArrayValueResults) Value() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultValue)) } type ImmutableBlockRecordResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBlockRecordResults) Record() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultRecord)) +func (s ImmutableBlockRecordResults) Record() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultRecord)) } type MutableBlockRecordResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBlockRecordResults) Record() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultRecord)) +func (s MutableBlockRecordResults) Record() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultRecord)) } type ImmutableBlockRecordsResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableBlockRecordsResults) Count() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultCount)) +func (s ImmutableBlockRecordsResults) Count() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultCount)) } type MutableBlockRecordsResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableBlockRecordsResults) Count() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultCount)) +func (s MutableBlockRecordsResults) Count() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultCount)) } type ImmutableGetRandomResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetRandomResults) Random() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultRandom)) +func (s ImmutableGetRandomResults) Random() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultRandom)) } type MutableGetRandomResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetRandomResults) Random() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultRandom)) +func (s MutableGetRandomResults) Random() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultRandom)) } type ImmutableIotaBalanceResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableIotaBalanceResults) Iotas() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultIotas)) +func (s ImmutableIotaBalanceResults) Iotas() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultIotas)) } type MutableIotaBalanceResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableIotaBalanceResults) Iotas() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultIotas)) +func (s MutableIotaBalanceResults) Iotas() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultIotas)) } type ImmutableMapValueResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMapValueResults) Value() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultValue)) +func (s ImmutableMapValueResults) Value() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultValue)) } type MutableMapValueResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMapValueResults) Value() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultValue)) +func (s MutableMapValueResults) Value() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultValue)) } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/state.go b/contracts/wasm/testwasmlib/go/testwasmlib/state.go index 47bd6093a9..8b5a08bca6 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/state.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/state.go @@ -7,72 +7,66 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type MapStringToImmutableStringArray struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToImmutableStringArray) GetStringArray(key string) ImmutableStringArray { - subID := wasmlib.GetObjectID(m.objID, wasmlib.Key(key).KeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_STRING) - return ImmutableStringArray{objID: subID} + return ImmutableStringArray{proxy: m.proxy.Key(wasmtypes.StringToBytes(key))} } type MapStringToImmutableStringMap struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToImmutableStringMap) GetStringMap(key string) ImmutableStringMap { - subID := wasmlib.GetObjectID(m.objID, wasmlib.Key(key).KeyID(), wasmlib.TYPE_MAP) - return ImmutableStringMap{objID: subID} + return ImmutableStringMap{proxy: m.proxy.Key(wasmtypes.StringToBytes(key))} } type ImmutableTestWasmLibState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableTestWasmLibState) Arrays() MapStringToImmutableStringArray { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateArrays), wasmlib.TYPE_MAP) - return MapStringToImmutableStringArray{objID: mapID} + return MapStringToImmutableStringArray{proxy: s.proxy.Root(StateArrays)} } func (s ImmutableTestWasmLibState) Maps() MapStringToImmutableStringMap { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMaps), wasmlib.TYPE_MAP) - return MapStringToImmutableStringMap{objID: mapID} + return MapStringToImmutableStringMap{proxy: s.proxy.Root(StateMaps)} } -func (s ImmutableTestWasmLibState) Random() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateRandom)) +func (s ImmutableTestWasmLibState) Random() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateRandom)) } type MapStringToMutableStringArray struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableStringArray) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } func (m MapStringToMutableStringArray) GetStringArray(key string) MutableStringArray { - subID := wasmlib.GetObjectID(m.objID, wasmlib.Key(key).KeyID(), wasmlib.TYPE_ARRAY|wasmlib.TYPE_STRING) - return MutableStringArray{objID: subID} + return MutableStringArray{proxy: m.proxy.Key(wasmtypes.StringToBytes(key))} } type MapStringToMutableStringMap struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableStringMap) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } func (m MapStringToMutableStringMap) GetStringMap(key string) MutableStringMap { - subID := wasmlib.GetObjectID(m.objID, wasmlib.Key(key).KeyID(), wasmlib.TYPE_MAP) - return MutableStringMap{objID: subID} + return MutableStringMap{proxy: m.proxy.Key(wasmtypes.StringToBytes(key))} } type MutableTestWasmLibState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableTestWasmLibState) AsImmutable() ImmutableTestWasmLibState { @@ -80,15 +74,13 @@ func (s MutableTestWasmLibState) AsImmutable() ImmutableTestWasmLibState { } func (s MutableTestWasmLibState) Arrays() MapStringToMutableStringArray { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateArrays), wasmlib.TYPE_MAP) - return MapStringToMutableStringArray{objID: mapID} + return MapStringToMutableStringArray{proxy: s.proxy.Root(StateArrays)} } func (s MutableTestWasmLibState) Maps() MapStringToMutableStringMap { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateMaps), wasmlib.TYPE_MAP) - return MapStringToMutableStringMap{objID: mapID} + return MapStringToMutableStringMap{proxy: s.proxy.Root(StateMaps)} } -func (s MutableTestWasmLibState) Random() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateRandom)) +func (s MutableTestWasmLibState) Random() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(StateRandom)) } diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/structs.go b/contracts/wasm/testwasmlib/go/testwasmlib/structs.go deleted file mode 100644 index f57de29a9d..0000000000 --- a/contracts/wasm/testwasmlib/go/testwasmlib/structs.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package testwasmlib - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type Location struct { - X int32 - Y int32 -} - -func NewLocationFromBytes(bytes []byte) *Location { - decode := wasmlib.NewBytesDecoder(bytes) - data := &Location{} - data.X = decode.Int32() - data.Y = decode.Int32() - decode.Close() - return data -} - -func (o *Location) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Int32(o.X). - Int32(o.Y). - Data() -} - -type ImmutableLocation struct { - objID int32 - keyID wasmlib.Key32 -} - -func (o ImmutableLocation) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) -} - -func (o ImmutableLocation) Value() *Location { - return NewLocationFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) -} - -type MutableLocation struct { - objID int32 - keyID wasmlib.Key32 -} - -func (o MutableLocation) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) -} - -func (o MutableLocation) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) -} - -func (o MutableLocation) SetValue(value *Location) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) -} - -func (o MutableLocation) Value() *Location { - return NewLocationFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) -} diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/testwasmlib.go b/contracts/wasm/testwasmlib/go/testwasmlib/testwasmlib.go index 8efb37d99e..c6f169f044 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/testwasmlib.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/testwasmlib.go @@ -6,10 +6,46 @@ package testwasmlib import ( "bytes" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib/coreblocklog" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) +func funcArrayAppend(ctx wasmlib.ScFuncContext, f *ArrayAppendContext) { + name := f.Params.Name().Value() + array := f.State.Arrays().GetStringArray(name) + value := f.Params.Value().Value() + array.AppendString().SetValue(value) +} + +func funcArrayClear(ctx wasmlib.ScFuncContext, f *ArrayClearContext) { + name := f.Params.Name().Value() + array := f.State.Arrays().GetStringArray(name) + array.Clear() +} + +func funcArraySet(ctx wasmlib.ScFuncContext, f *ArraySetContext) { + name := f.Params.Name().Value() + array := f.State.Arrays().GetStringArray(name) + index := f.Params.Index().Value() + value := f.Params.Value().Value() + array.GetString(index).SetValue(value) +} + +func funcMapClear(ctx wasmlib.ScFuncContext, f *MapClearContext) { + name := f.Params.Name().Value() + myMap := f.State.Maps().GetStringMap(name) + myMap.Clear() +} + +func funcMapSet(ctx wasmlib.ScFuncContext, f *MapSetContext) { + name := f.Params.Name().Value() + myMap := f.State.Maps().GetStringMap(name) + key := f.Params.Key().Value() + value := f.Params.Value().Value() + myMap.GetString(key).SetValue(value) +} + func funcParamTypes(ctx wasmlib.ScFuncContext, f *ParamTypesContext) { if f.Params.Address().Exists() { ctx.Require(f.Params.Address().Value() == ctx.AccountID().Address(), "mismatch: Address") @@ -28,11 +64,11 @@ func funcParamTypes(ctx wasmlib.ScFuncContext, f *ParamTypesContext) { ctx.Require(f.Params.ChainID().Value() == ctx.ChainID(), "mismatch: ChainID") } if f.Params.Color().Exists() { - color := wasmlib.NewScColorFromBytes([]byte("RedGreenBlueYellowCyanBlackWhite")) + color := wasmtypes.ColorFromBytes([]byte("RedGreenBlueYellowCyanBlackWhite")) ctx.Require(f.Params.Color().Value() == color, "mismatch: Color") } if f.Params.Hash().Exists() { - hash := wasmlib.NewScHashFromBytes([]byte("0123456789abcdeffedcba9876543210")) + hash := wasmtypes.HashFromBytes([]byte("0123456789abcdeffedcba9876543210")) ctx.Require(f.Params.Hash().Value() == hash, "mismatch: Hash") } if f.Params.Hname().Exists() { @@ -51,7 +87,7 @@ func funcParamTypes(ctx wasmlib.ScFuncContext, f *ParamTypesContext) { ctx.Require(f.Params.Int64().Value() == -1234567890123456789, "mismatch: Int64") } if f.Params.RequestID().Exists() { - requestID := wasmlib.NewScRequestIDFromBytes([]byte("abcdefghijklmnopqrstuvwxyz123456\x00\x00")) + requestID := wasmtypes.RequestIDFromBytes([]byte("abcdefghijklmnopqrstuvwxyz123456\x00\x00")) ctx.Require(f.Params.RequestID().Value() == requestID, "mismatch: RequestID") } if f.Params.String().Exists() { @@ -71,40 +107,20 @@ func funcParamTypes(ctx wasmlib.ScFuncContext, f *ParamTypesContext) { } } -func viewBlockRecord(ctx wasmlib.ScViewContext, f *BlockRecordContext) { - records := coreblocklog.ScFuncs.GetRequestReceiptsForBlock(ctx) - records.Params.BlockIndex().SetValue(f.Params.BlockIndex().Value()) - records.Func.Call() - recordIndex := f.Params.RecordIndex().Value() - ctx.Require(recordIndex < records.Results.RequestRecord().Length(), "invalid recordIndex") - f.Results.Record().SetValue(records.Results.RequestRecord().GetBytes(recordIndex).Value()) -} - -func viewBlockRecords(ctx wasmlib.ScViewContext, f *BlockRecordsContext) { - records := coreblocklog.ScFuncs.GetRequestReceiptsForBlock(ctx) - records.Params.BlockIndex().SetValue(f.Params.BlockIndex().Value()) - records.Func.Call() - f.Results.Count().SetValue(records.Results.RequestRecord().Length()) -} - -func funcArrayClear(ctx wasmlib.ScFuncContext, f *ArrayClearContext) { - name := f.Params.Name().Value() - array := f.State.Arrays().GetStringArray(name) - array.Clear() +func funcRandom(ctx wasmlib.ScFuncContext, f *RandomContext) { + f.State.Random().SetValue(ctx.Random(1000)) } -func funcArrayCreate(ctx wasmlib.ScFuncContext, f *ArrayCreateContext) { - name := f.Params.Name().Value() - array := f.State.Arrays().GetStringArray(name) - array.Clear() +func funcTriggerEvent(ctx wasmlib.ScFuncContext, f *TriggerEventContext) { + f.Events.Test(f.Params.Address().Value(), f.Params.Name().Value()) } -func funcArraySet(ctx wasmlib.ScFuncContext, f *ArraySetContext) { +func viewArrayValue(ctx wasmlib.ScViewContext, f *ArrayValueContext) { name := f.Params.Name().Value() array := f.State.Arrays().GetStringArray(name) index := f.Params.Index().Value() - value := f.Params.Value().Value() - array.GetString(index).SetValue(value) + value := array.GetString(index).Value() + f.Results.Value().SetValue(value) } func viewArrayLength(ctx wasmlib.ScViewContext, f *ArrayLengthContext) { @@ -114,48 +130,28 @@ func viewArrayLength(ctx wasmlib.ScViewContext, f *ArrayLengthContext) { f.Results.Length().SetValue(length) } -func viewArrayValue(ctx wasmlib.ScViewContext, f *ArrayValueContext) { - name := f.Params.Name().Value() - array := f.State.Arrays().GetStringArray(name) - index := f.Params.Index().Value() - value := array.GetString(index).Value() - f.Results.Value().SetValue(value) -} - -func viewIotaBalance(ctx wasmlib.ScViewContext, f *IotaBalanceContext) { - f.Results.Iotas().SetValue(ctx.Balances().Balance(wasmlib.IOTA)) +func viewBlockRecord(ctx wasmlib.ScViewContext, f *BlockRecordContext) { + records := coreblocklog.ScFuncs.GetRequestReceiptsForBlock(ctx) + records.Params.BlockIndex().SetValue(f.Params.BlockIndex().Value()) + records.Func.Call() + recordIndex := f.Params.RecordIndex().Value() + ctx.Require(recordIndex < records.Results.RequestRecord().Length(), "invalid recordIndex") + f.Results.Record().SetValue(records.Results.RequestRecord().GetBytes(recordIndex).Value()) } -func funcRandom(ctx wasmlib.ScFuncContext, f *RandomContext) { - f.State.Random().SetValue(ctx.Random(1000)) +func viewBlockRecords(ctx wasmlib.ScViewContext, f *BlockRecordsContext) { + records := coreblocklog.ScFuncs.GetRequestReceiptsForBlock(ctx) + records.Params.BlockIndex().SetValue(f.Params.BlockIndex().Value()) + records.Func.Call() + f.Results.Count().SetValue(records.Results.RequestRecord().Length()) } func viewGetRandom(ctx wasmlib.ScViewContext, f *GetRandomContext) { f.Results.Random().SetValue(f.State.Random().Value()) } -func funcTriggerEvent(ctx wasmlib.ScFuncContext, f *TriggerEventContext) { - f.Events.Test(f.Params.Address().Value(), f.Params.Name().Value()) -} - -func funcMapClear(ctx wasmlib.ScFuncContext, f *MapClearContext) { - name := f.Params.Name().Value() - myMap := f.State.Maps().GetStringMap(name) - myMap.Clear() -} - -func funcMapCreate(ctx wasmlib.ScFuncContext, f *MapCreateContext) { - name := f.Params.Name().Value() - myMap := f.State.Maps().GetStringMap(name) - myMap.Clear() -} - -func funcMapSet(ctx wasmlib.ScFuncContext, f *MapSetContext) { - name := f.Params.Name().Value() - myMap := f.State.Maps().GetStringMap(name) - key := f.Params.Key().Value() - value := f.Params.Value().Value() - myMap.GetString(key).SetValue(value) +func viewIotaBalance(ctx wasmlib.ScViewContext, f *IotaBalanceContext) { + f.Results.Iotas().SetValue(ctx.Balances().Balance(wasmtypes.IOTA)) } func viewMapValue(ctx wasmlib.ScViewContext, f *MapValueContext) { diff --git a/contracts/wasm/testwasmlib/go/testwasmlib/typedefs.go b/contracts/wasm/testwasmlib/go/testwasmlib/typedefs.go index 97090d3d58..d6ac0e20ca 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlib/typedefs.go +++ b/contracts/wasm/testwasmlib/go/testwasmlib/typedefs.go @@ -7,60 +7,64 @@ package testwasmlib -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableString struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableString) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableString) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableString) GetString(index int32) wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(a.objID, wasmlib.Key32(index)) +func (a ArrayOfImmutableString) GetString(index uint32) wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(a.proxy.Index(index)) } type ImmutableStringArray = ArrayOfImmutableString type ArrayOfMutableString struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableString) AppendString() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(a.proxy.Append()) } func (a ArrayOfMutableString) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableString) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableString) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableString) GetString(index int32) wasmlib.ScMutableString { - return wasmlib.NewScMutableString(a.objID, wasmlib.Key32(index)) +func (a ArrayOfMutableString) GetString(index uint32) wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(a.proxy.Index(index)) } type MutableStringArray = ArrayOfMutableString type MapStringToImmutableString struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapStringToImmutableString) GetString(key string) wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToImmutableString) GetString(key string) wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(m.proxy.Key(wasmtypes.StringToBytes(key))) } type ImmutableStringMap = MapStringToImmutableString type MapStringToMutableString struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapStringToMutableString) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapStringToMutableString) GetString(key string) wasmlib.ScMutableString { - return wasmlib.NewScMutableString(m.objID, wasmlib.Key(key).KeyID()) +func (m MapStringToMutableString) GetString(key string) wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(m.proxy.Key(wasmtypes.StringToBytes(key))) } type MutableStringMap = MapStringToMutableString diff --git a/contracts/wasm/testwasmlib/go/testwasmlibclient/events.go b/contracts/wasm/testwasmlib/go/testwasmlibclient/events.go index e0c3faf93c..66152847d4 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlibclient/events.go +++ b/contracts/wasm/testwasmlib/go/testwasmlibclient/events.go @@ -7,10 +7,25 @@ package testwasmlibclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" -var EventHandlers = map[string]func([]string){ - "testwasmlib.test": onTestWasmLibTestThunk, +var testWasmLibHandlers = map[string]func(*TestWasmLibEvents, []string){ + "testwasmlib.test": func(evt *TestWasmLibEvents, msg []string) { evt.onTestWasmLibTestThunk(msg) }, +} + +type TestWasmLibEvents struct { + test func(e *EventTest) +} + +func (h *TestWasmLibEvents) CallHandler(topic string, params []string) { + handler := testWasmLibHandlers[topic] + if handler != nil { + handler(h, params) + } +} + +func (h *TestWasmLibEvents) OnTestWasmLibTest(handler func(e *EventTest)) { + h.test = handler } type EventTest struct { @@ -19,10 +34,13 @@ type EventTest struct { Name string } -func onTestWasmLibTestThunk(message []string) { +func (h *TestWasmLibEvents) onTestWasmLibTestThunk(message []string) { + if h.test == nil { + return + } e := &EventTest{} e.Init(message) e.Address = e.NextAddress() e.Name = e.NextString() - OnTestWasmLibTest(e) + h.test(e) } diff --git a/contracts/wasm/testwasmlib/go/testwasmlibclient/service.go b/contracts/wasm/testwasmlib/go/testwasmlibclient/service.go index 60b4dbd9fb..8b29b5cc0a 100644 --- a/contracts/wasm/testwasmlib/go/testwasmlibclient/service.go +++ b/contracts/wasm/testwasmlib/go/testwasmlibclient/service.go @@ -7,7 +7,7 @@ package testwasmlibclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgAddress = "address" @@ -44,36 +44,41 @@ const ( ResValue = "value" ) -///////////////////////////// arrayClear ///////////////////////////// +///////////////////////////// arrayAppend ///////////////////////////// -type ArrayClearFunc struct { +type ArrayAppendFunc struct { wasmclient.ClientFunc args wasmclient.Arguments } -func (f *ArrayClearFunc) Name(v string) { +func (f *ArrayAppendFunc) Name(v string) { f.args.Set(ArgName, f.args.FromString(v)) } -func (f *ArrayClearFunc) Post() wasmclient.Request { +func (f *ArrayAppendFunc) Value(v string) { + f.args.Set(ArgValue, f.args.FromString(v)) +} + +func (f *ArrayAppendFunc) Post() wasmclient.Request { f.args.Mandatory(ArgName) - return f.ClientFunc.Post(0x88021821, &f.args) + f.args.Mandatory(ArgValue) + return f.ClientFunc.Post(0x612f835f, &f.args) } -///////////////////////////// arrayCreate ///////////////////////////// +///////////////////////////// arrayClear ///////////////////////////// -type ArrayCreateFunc struct { +type ArrayClearFunc struct { wasmclient.ClientFunc args wasmclient.Arguments } -func (f *ArrayCreateFunc) Name(v string) { +func (f *ArrayClearFunc) Name(v string) { f.args.Set(ArgName, f.args.FromString(v)) } -func (f *ArrayCreateFunc) Post() wasmclient.Request { +func (f *ArrayClearFunc) Post() wasmclient.Request { f.args.Mandatory(ArgName) - return f.ClientFunc.Post(0x1ed5b23b, &f.args) + return f.ClientFunc.Post(0x88021821, &f.args) } ///////////////////////////// arraySet ///////////////////////////// @@ -83,8 +88,8 @@ type ArraySetFunc struct { args wasmclient.Arguments } -func (f *ArraySetFunc) Index(v int32) { - f.args.Set(ArgIndex, f.args.FromInt32(v)) +func (f *ArraySetFunc) Index(v uint32) { + f.args.Set(ArgIndex, f.args.FromUint32(v)) } func (f *ArraySetFunc) Name(v string) { @@ -118,22 +123,6 @@ func (f *MapClearFunc) Post() wasmclient.Request { return f.ClientFunc.Post(0x027f215a, &f.args) } -///////////////////////////// mapCreate ///////////////////////////// - -type MapCreateFunc struct { - wasmclient.ClientFunc - args wasmclient.Arguments -} - -func (f *MapCreateFunc) Name(v string) { - f.args.Set(ArgName, f.args.FromString(v)) -} - -func (f *MapCreateFunc) Post() wasmclient.Request { - f.args.Mandatory(ArgName) - return f.ClientFunc.Post(0x6295d599, &f.args) -} - ///////////////////////////// mapSet ///////////////////////////// type MapSetFunc struct { @@ -299,8 +288,8 @@ type ArrayLengthResults struct { res wasmclient.Results } -func (r *ArrayLengthResults) Length() int32 { - return r.res.ToInt32(r.res.Get(ResLength)) +func (r *ArrayLengthResults) Length() uint32 { + return r.res.ToUint32(r.res.Get(ResLength)) } ///////////////////////////// arrayValue ///////////////////////////// @@ -310,8 +299,8 @@ type ArrayValueView struct { args wasmclient.Arguments } -func (f *ArrayValueView) Index(v int32) { - f.args.Set(ArgIndex, f.args.FromInt32(v)) +func (f *ArrayValueView) Index(v uint32) { + f.args.Set(ArgIndex, f.args.FromUint32(v)) } func (f *ArrayValueView) Name(v string) { @@ -340,12 +329,12 @@ type BlockRecordView struct { args wasmclient.Arguments } -func (f *BlockRecordView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *BlockRecordView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } -func (f *BlockRecordView) RecordIndex(v int32) { - f.args.Set(ArgRecordIndex, f.args.FromInt32(v)) +func (f *BlockRecordView) RecordIndex(v uint32) { + f.args.Set(ArgRecordIndex, f.args.FromUint32(v)) } func (f *BlockRecordView) Call() BlockRecordResults { @@ -370,8 +359,8 @@ type BlockRecordsView struct { args wasmclient.Arguments } -func (f *BlockRecordsView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *BlockRecordsView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } func (f *BlockRecordsView) Call() BlockRecordsResults { @@ -384,8 +373,8 @@ type BlockRecordsResults struct { res wasmclient.Results } -func (r *BlockRecordsResults) Count() int32 { - return r.res.ToInt32(r.res.Get(ResCount)) +func (r *BlockRecordsResults) Count() uint32 { + return r.res.ToUint32(r.res.Get(ResCount)) } ///////////////////////////// getRandom ///////////////////////////// @@ -403,8 +392,8 @@ type GetRandomResults struct { res wasmclient.Results } -func (r *GetRandomResults) Random() int64 { - return r.res.ToInt64(r.res.Get(ResRandom)) +func (r *GetRandomResults) Random() uint64 { + return r.res.ToUint64(r.res.Get(ResRandom)) } ///////////////////////////// iotaBalance ///////////////////////////// @@ -422,8 +411,8 @@ type IotaBalanceResults struct { res wasmclient.Results } -func (r *IotaBalanceResults) Iotas() int64 { - return r.res.ToInt64(r.res.Get(ResIotas)) +func (r *IotaBalanceResults) Iotas() uint64 { + return r.res.ToUint64(r.res.Get(ResIotas)) } ///////////////////////////// mapValue ///////////////////////////// @@ -464,16 +453,20 @@ type TestWasmLibService struct { func NewTestWasmLibService(cl *wasmclient.ServiceClient, chainID string) (*TestWasmLibService, error) { s := &TestWasmLibService{} - err := s.Service.Init(cl, chainID, 0x89703a45, EventHandlers) + err := s.Service.Init(cl, chainID, 0x89703a45) return s, err } -func (s *TestWasmLibService) ArrayClear() ArrayClearFunc { - return ArrayClearFunc{ClientFunc: s.AsClientFunc()} +func (s *TestWasmLibService) NewEventHandler() *TestWasmLibEvents { + return &TestWasmLibEvents{} +} + +func (s *TestWasmLibService) ArrayAppend() ArrayAppendFunc { + return ArrayAppendFunc{ClientFunc: s.AsClientFunc()} } -func (s *TestWasmLibService) ArrayCreate() ArrayCreateFunc { - return ArrayCreateFunc{ClientFunc: s.AsClientFunc()} +func (s *TestWasmLibService) ArrayClear() ArrayClearFunc { + return ArrayClearFunc{ClientFunc: s.AsClientFunc()} } func (s *TestWasmLibService) ArraySet() ArraySetFunc { @@ -484,10 +477,6 @@ func (s *TestWasmLibService) MapClear() MapClearFunc { return MapClearFunc{ClientFunc: s.AsClientFunc()} } -func (s *TestWasmLibService) MapCreate() MapCreateFunc { - return MapCreateFunc{ClientFunc: s.AsClientFunc()} -} - func (s *TestWasmLibService) MapSet() MapSetFunc { return MapSetFunc{ClientFunc: s.AsClientFunc()} } diff --git a/contracts/wasm/testwasmlib/schema.yaml b/contracts/wasm/testwasmlib/schema.yaml index 7b1358e733..822e7b77d9 100644 --- a/contracts/wasm/testwasmlib/schema.yaml +++ b/contracts/wasm/testwasmlib/schema.yaml @@ -27,23 +27,24 @@ state: # ################################## arrays: map[String]StringArray maps: map[String]StringMap - random: Int64 + random: Uint64 # latLong: map[Int32]Longitude # ################################## funcs: # ################################## - arrayClear: + arrayAppend: params: name: String + value: String - arrayCreate: + arrayClear: params: name: String arraySet: params: - index: Int32 + index: Uint32 name: String value: String @@ -51,10 +52,6 @@ funcs: params: name: String - mapCreate: - params: - name: String - mapSet: params: name: String @@ -97,31 +94,31 @@ views: params: name: String results: - length: Int32 + length: Uint32 arrayValue: params: - index: Int32 + index: Uint32 name: String results: value: String blockRecord: params: - blockIndex: Int32 - recordIndex: Int32 + blockIndex: Uint32 + recordIndex: Uint32 results: record: Bytes blockRecords: params: - blockIndex: Int32 + blockIndex: Uint32 results: - count: Int32 + count: Uint32 iotaBalance: results: - iotas: Int64 + iotas: Uint64 mapValue: params: @@ -132,4 +129,4 @@ views: getRandom: results: - random: Int64 + random: Uint64 diff --git a/contracts/wasm/testwasmlib/src/consts.rs b/contracts/wasm/testwasmlib/src/consts.rs index 8842bfad04..27e099be87 100644 --- a/contracts/wasm/testwasmlib/src/consts.rs +++ b/contracts/wasm/testwasmlib/src/consts.rs @@ -50,11 +50,10 @@ pub const STATE_ARRAYS : &str = "arrays"; pub const STATE_MAPS : &str = "maps"; pub const STATE_RANDOM : &str = "random"; +pub const FUNC_ARRAY_APPEND : &str = "arrayAppend"; pub const FUNC_ARRAY_CLEAR : &str = "arrayClear"; -pub const FUNC_ARRAY_CREATE : &str = "arrayCreate"; pub const FUNC_ARRAY_SET : &str = "arraySet"; pub const FUNC_MAP_CLEAR : &str = "mapClear"; -pub const FUNC_MAP_CREATE : &str = "mapCreate"; pub const FUNC_MAP_SET : &str = "mapSet"; pub const FUNC_PARAM_TYPES : &str = "paramTypes"; pub const FUNC_RANDOM : &str = "random"; @@ -67,11 +66,10 @@ pub const VIEW_GET_RANDOM : &str = "getRandom"; pub const VIEW_IOTA_BALANCE : &str = "iotaBalance"; pub const VIEW_MAP_VALUE : &str = "mapValue"; +pub const HFUNC_ARRAY_APPEND : ScHname = ScHname(0x612f835f); pub const HFUNC_ARRAY_CLEAR : ScHname = ScHname(0x88021821); -pub const HFUNC_ARRAY_CREATE : ScHname = ScHname(0x1ed5b23b); pub const HFUNC_ARRAY_SET : ScHname = ScHname(0x2c4150b3); pub const HFUNC_MAP_CLEAR : ScHname = ScHname(0x027f215a); -pub const HFUNC_MAP_CREATE : ScHname = ScHname(0x6295d599); pub const HFUNC_MAP_SET : ScHname = ScHname(0xf2260404); pub const HFUNC_PARAM_TYPES : ScHname = ScHname(0x6921c4cd); pub const HFUNC_RANDOM : ScHname = ScHname(0xe86c97ca); diff --git a/contracts/wasm/testwasmlib/src/contract.rs b/contracts/wasm/testwasmlib/src/contract.rs index 8de723d684..b8ede236dc 100644 --- a/contracts/wasm/testwasmlib/src/contract.rs +++ b/contracts/wasm/testwasmlib/src/contract.rs @@ -7,22 +7,17 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; +use crate::*; -use crate::consts::*; -use crate::params::*; -use crate::results::*; - -pub struct ArrayClearCall { +pub struct ArrayAppendCall { pub func: ScFunc, - pub params: MutableArrayClearParams, + pub params: MutableArrayAppendParams, } -pub struct ArrayCreateCall { +pub struct ArrayClearCall { pub func: ScFunc, - pub params: MutableArrayCreateParams, + pub params: MutableArrayClearParams, } pub struct ArraySetCall { @@ -35,11 +30,6 @@ pub struct MapClearCall { pub params: MutableMapClearParams, } -pub struct MapCreateCall { - pub func: ScFunc, - pub params: MutableMapCreateParams, -} - pub struct MapSetCall { pub func: ScFunc, pub params: MutableMapSetParams, @@ -103,149 +93,145 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn array_clear(_ctx: & dyn ScFuncCallContext) -> ArrayClearCall { - let mut f = ArrayClearCall { - func: ScFunc::new(HSC_NAME, HFUNC_ARRAY_CLEAR), - params: MutableArrayClearParams { id: 0 }, + pub fn array_append(_ctx: &dyn ScFuncCallContext) -> ArrayAppendCall { + let mut f = ArrayAppendCall { + func: ScFunc::new(HSC_NAME, HFUNC_ARRAY_APPEND), + params: MutableArrayAppendParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn array_create(_ctx: & dyn ScFuncCallContext) -> ArrayCreateCall { - let mut f = ArrayCreateCall { - func: ScFunc::new(HSC_NAME, HFUNC_ARRAY_CREATE), - params: MutableArrayCreateParams { id: 0 }, + pub fn array_clear(_ctx: &dyn ScFuncCallContext) -> ArrayClearCall { + let mut f = ArrayClearCall { + func: ScFunc::new(HSC_NAME, HFUNC_ARRAY_CLEAR), + params: MutableArrayClearParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn array_set(_ctx: & dyn ScFuncCallContext) -> ArraySetCall { + pub fn array_set(_ctx: &dyn ScFuncCallContext) -> ArraySetCall { let mut f = ArraySetCall { func: ScFunc::new(HSC_NAME, HFUNC_ARRAY_SET), - params: MutableArraySetParams { id: 0 }, + params: MutableArraySetParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn map_clear(_ctx: & dyn ScFuncCallContext) -> MapClearCall { + pub fn map_clear(_ctx: &dyn ScFuncCallContext) -> MapClearCall { let mut f = MapClearCall { func: ScFunc::new(HSC_NAME, HFUNC_MAP_CLEAR), - params: MutableMapClearParams { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); - f - } - - pub fn map_create(_ctx: & dyn ScFuncCallContext) -> MapCreateCall { - let mut f = MapCreateCall { - func: ScFunc::new(HSC_NAME, HFUNC_MAP_CREATE), - params: MutableMapCreateParams { id: 0 }, + params: MutableMapClearParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn map_set(_ctx: & dyn ScFuncCallContext) -> MapSetCall { + pub fn map_set(_ctx: &dyn ScFuncCallContext) -> MapSetCall { let mut f = MapSetCall { func: ScFunc::new(HSC_NAME, HFUNC_MAP_SET), - params: MutableMapSetParams { id: 0 }, + params: MutableMapSetParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn param_types(_ctx: & dyn ScFuncCallContext) -> ParamTypesCall { + pub fn param_types(_ctx: &dyn ScFuncCallContext) -> ParamTypesCall { let mut f = ParamTypesCall { func: ScFunc::new(HSC_NAME, HFUNC_PARAM_TYPES), - params: MutableParamTypesParams { id: 0 }, + params: MutableParamTypesParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn random(_ctx: & dyn ScFuncCallContext) -> RandomCall { + pub fn random(_ctx: &dyn ScFuncCallContext) -> RandomCall { RandomCall { func: ScFunc::new(HSC_NAME, HFUNC_RANDOM), } } - pub fn trigger_event(_ctx: & dyn ScFuncCallContext) -> TriggerEventCall { + pub fn trigger_event(_ctx: &dyn ScFuncCallContext) -> TriggerEventCall { let mut f = TriggerEventCall { func: ScFunc::new(HSC_NAME, HFUNC_TRIGGER_EVENT), - params: MutableTriggerEventParams { id: 0 }, + params: MutableTriggerEventParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn array_length(_ctx: & dyn ScViewCallContext) -> ArrayLengthCall { + pub fn array_length(_ctx: &dyn ScViewCallContext) -> ArrayLengthCall { let mut f = ArrayLengthCall { func: ScView::new(HSC_NAME, HVIEW_ARRAY_LENGTH), - params: MutableArrayLengthParams { id: 0 }, - results: ImmutableArrayLengthResults { id: 0 }, + params: MutableArrayLengthParams { proxy: Proxy::nil() }, + results: ImmutableArrayLengthResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn array_value(_ctx: & dyn ScViewCallContext) -> ArrayValueCall { + pub fn array_value(_ctx: &dyn ScViewCallContext) -> ArrayValueCall { let mut f = ArrayValueCall { func: ScView::new(HSC_NAME, HVIEW_ARRAY_VALUE), - params: MutableArrayValueParams { id: 0 }, - results: ImmutableArrayValueResults { id: 0 }, + params: MutableArrayValueParams { proxy: Proxy::nil() }, + results: ImmutableArrayValueResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn block_record(_ctx: & dyn ScViewCallContext) -> BlockRecordCall { + pub fn block_record(_ctx: &dyn ScViewCallContext) -> BlockRecordCall { let mut f = BlockRecordCall { func: ScView::new(HSC_NAME, HVIEW_BLOCK_RECORD), - params: MutableBlockRecordParams { id: 0 }, - results: ImmutableBlockRecordResults { id: 0 }, + params: MutableBlockRecordParams { proxy: Proxy::nil() }, + results: ImmutableBlockRecordResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn block_records(_ctx: & dyn ScViewCallContext) -> BlockRecordsCall { + pub fn block_records(_ctx: &dyn ScViewCallContext) -> BlockRecordsCall { let mut f = BlockRecordsCall { func: ScView::new(HSC_NAME, HVIEW_BLOCK_RECORDS), - params: MutableBlockRecordsParams { id: 0 }, - results: ImmutableBlockRecordsResults { id: 0 }, + params: MutableBlockRecordsParams { proxy: Proxy::nil() }, + results: ImmutableBlockRecordsResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_random(_ctx: & dyn ScViewCallContext) -> GetRandomCall { + pub fn get_random(_ctx: &dyn ScViewCallContext) -> GetRandomCall { let mut f = GetRandomCall { func: ScView::new(HSC_NAME, HVIEW_GET_RANDOM), - results: ImmutableGetRandomResults { id: 0 }, + results: ImmutableGetRandomResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn iota_balance(_ctx: & dyn ScViewCallContext) -> IotaBalanceCall { + pub fn iota_balance(_ctx: &dyn ScViewCallContext) -> IotaBalanceCall { let mut f = IotaBalanceCall { func: ScView::new(HSC_NAME, HVIEW_IOTA_BALANCE), - results: ImmutableIotaBalanceResults { id: 0 }, + results: ImmutableIotaBalanceResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn map_value(_ctx: & dyn ScViewCallContext) -> MapValueCall { + pub fn map_value(_ctx: &dyn ScViewCallContext) -> MapValueCall { let mut f = MapValueCall { func: ScView::new(HSC_NAME, HVIEW_MAP_VALUE), - params: MutableMapValueParams { id: 0 }, - results: ImmutableMapValueResults { id: 0 }, + params: MutableMapValueParams { proxy: Proxy::nil() }, + results: ImmutableMapValueResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/testwasmlib/src/events.rs b/contracts/wasm/testwasmlib/src/events.rs index c190ba68d1..6e42899bbf 100644 --- a/contracts/wasm/testwasmlib/src/events.rs +++ b/contracts/wasm/testwasmlib/src/events.rs @@ -6,6 +6,7 @@ // Change the json schema instead #![allow(dead_code)] +#![allow(unused_mut)] use wasmlib::*; @@ -15,9 +16,9 @@ pub struct TestWasmLibEvents { impl TestWasmLibEvents { pub fn test(&self, address: &ScAddress, name: &str) { - let mut encoder = EventEncoder::new("testwasmlib.test"); - encoder.address(&address); - encoder.string(&name); - encoder.emit(); + let mut evt = EventEncoder::new("testwasmlib.test"); + evt.encode(&address_to_string(&address)); + evt.encode(&string_to_string(&name)); + evt.emit(); } } diff --git a/contracts/wasm/testwasmlib/src/keys.rs b/contracts/wasm/testwasmlib/src/keys.rs deleted file mode 100644 index 7aeff86e99..0000000000 --- a/contracts/wasm/testwasmlib/src/keys.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_ADDRESS : usize = 0; -pub(crate) const IDX_PARAM_AGENT_ID : usize = 1; -pub(crate) const IDX_PARAM_BLOCK_INDEX : usize = 2; -pub(crate) const IDX_PARAM_BOOL : usize = 3; -pub(crate) const IDX_PARAM_BYTES : usize = 4; -pub(crate) const IDX_PARAM_CHAIN_ID : usize = 5; -pub(crate) const IDX_PARAM_COLOR : usize = 6; -pub(crate) const IDX_PARAM_HASH : usize = 7; -pub(crate) const IDX_PARAM_HNAME : usize = 8; -pub(crate) const IDX_PARAM_INDEX : usize = 9; -pub(crate) const IDX_PARAM_INT16 : usize = 10; -pub(crate) const IDX_PARAM_INT32 : usize = 11; -pub(crate) const IDX_PARAM_INT64 : usize = 12; -pub(crate) const IDX_PARAM_INT8 : usize = 13; -pub(crate) const IDX_PARAM_KEY : usize = 14; -pub(crate) const IDX_PARAM_NAME : usize = 15; -pub(crate) const IDX_PARAM_PARAM : usize = 16; -pub(crate) const IDX_PARAM_RECORD_INDEX : usize = 17; -pub(crate) const IDX_PARAM_REQUEST_ID : usize = 18; -pub(crate) const IDX_PARAM_STRING : usize = 19; -pub(crate) const IDX_PARAM_UINT16 : usize = 20; -pub(crate) const IDX_PARAM_UINT32 : usize = 21; -pub(crate) const IDX_PARAM_UINT64 : usize = 22; -pub(crate) const IDX_PARAM_UINT8 : usize = 23; -pub(crate) const IDX_PARAM_VALUE : usize = 24; - -pub(crate) const IDX_RESULT_COUNT : usize = 25; -pub(crate) const IDX_RESULT_IOTAS : usize = 26; -pub(crate) const IDX_RESULT_LENGTH : usize = 27; -pub(crate) const IDX_RESULT_RANDOM : usize = 28; -pub(crate) const IDX_RESULT_RECORD : usize = 29; -pub(crate) const IDX_RESULT_VALUE : usize = 30; - -pub(crate) const IDX_STATE_ARRAYS : usize = 31; -pub(crate) const IDX_STATE_MAPS : usize = 32; -pub(crate) const IDX_STATE_RANDOM : usize = 33; - -pub const KEY_MAP_LEN: usize = 34; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_ADDRESS, - PARAM_AGENT_ID, - PARAM_BLOCK_INDEX, - PARAM_BOOL, - PARAM_BYTES, - PARAM_CHAIN_ID, - PARAM_COLOR, - PARAM_HASH, - PARAM_HNAME, - PARAM_INDEX, - PARAM_INT16, - PARAM_INT32, - PARAM_INT64, - PARAM_INT8, - PARAM_KEY, - PARAM_NAME, - PARAM_PARAM, - PARAM_RECORD_INDEX, - PARAM_REQUEST_ID, - PARAM_STRING, - PARAM_UINT16, - PARAM_UINT32, - PARAM_UINT64, - PARAM_UINT8, - PARAM_VALUE, - RESULT_COUNT, - RESULT_IOTAS, - RESULT_LENGTH, - RESULT_RANDOM, - RESULT_RECORD, - RESULT_VALUE, - STATE_ARRAYS, - STATE_MAPS, - STATE_RANDOM, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/testwasmlib/src/lib.rs b/contracts/wasm/testwasmlib/src/lib.rs index b5f7cade6a..44ed25847f 100644 --- a/contracts/wasm/testwasmlib/src/lib.rs +++ b/contracts/wasm/testwasmlib/src/lib.rs @@ -10,94 +10,108 @@ use testwasmlib::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; use crate::events::*; -use crate::keys::*; use crate::params::*; use crate::results::*; use crate::state::*; +use crate::typedefs::*; mod consts; mod contract; mod events; -mod keys; mod params; mod results; mod state; mod typedefs; + mod testwasmlib; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_ARRAY_APPEND, + FUNC_ARRAY_CLEAR, + FUNC_ARRAY_SET, + FUNC_MAP_CLEAR, + FUNC_MAP_SET, + FUNC_PARAM_TYPES, + FUNC_RANDOM, + FUNC_TRIGGER_EVENT, + VIEW_ARRAY_LENGTH, + VIEW_ARRAY_VALUE, + VIEW_BLOCK_RECORD, + VIEW_BLOCK_RECORDS, + VIEW_GET_RANDOM, + VIEW_IOTA_BALANCE, + VIEW_MAP_VALUE, + ], + funcs: &[ + func_array_append_thunk, + func_array_clear_thunk, + func_array_set_thunk, + func_map_clear_thunk, + func_map_set_thunk, + func_param_types_thunk, + func_random_thunk, + func_trigger_event_thunk, + ], + views: &[ + view_array_length_thunk, + view_array_value_thunk, + view_block_record_thunk, + view_block_records_thunk, + view_get_random_thunk, + view_iota_balance_thunk, + view_map_value_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_ARRAY_CLEAR, func_array_clear_thunk); - exports.add_func(FUNC_ARRAY_CREATE, func_array_create_thunk); - exports.add_func(FUNC_ARRAY_SET, func_array_set_thunk); - exports.add_func(FUNC_MAP_CLEAR, func_map_clear_thunk); - exports.add_func(FUNC_MAP_CREATE, func_map_create_thunk); - exports.add_func(FUNC_MAP_SET, func_map_set_thunk); - exports.add_func(FUNC_PARAM_TYPES, func_param_types_thunk); - exports.add_func(FUNC_RANDOM, func_random_thunk); - exports.add_func(FUNC_TRIGGER_EVENT, func_trigger_event_thunk); - exports.add_view(VIEW_ARRAY_LENGTH, view_array_length_thunk); - exports.add_view(VIEW_ARRAY_VALUE, view_array_value_thunk); - exports.add_view(VIEW_BLOCK_RECORD, view_block_record_thunk); - exports.add_view(VIEW_BLOCK_RECORDS, view_block_records_thunk); - exports.add_view(VIEW_GET_RANDOM, view_get_random_thunk); - exports.add_view(VIEW_IOTA_BALANCE, view_iota_balance_thunk); - exports.add_view(VIEW_MAP_VALUE, view_map_value_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } -pub struct ArrayClearContext { +pub struct ArrayAppendContext { events: TestWasmLibEvents, - params: ImmutableArrayClearParams, + params: ImmutableArrayAppendParams, state: MutableTestWasmLibState, } -fn func_array_clear_thunk(ctx: &ScFuncContext) { - ctx.log("testwasmlib.funcArrayClear"); - let f = ArrayClearContext { +fn func_array_append_thunk(ctx: &ScFuncContext) { + ctx.log("testwasmlib.funcArrayAppend"); + let f = ArrayAppendContext { events: TestWasmLibEvents {}, - params: ImmutableArrayClearParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableArrayAppendParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); - func_array_clear(ctx, &f); - ctx.log("testwasmlib.funcArrayClear ok"); + ctx.require(f.params.value().exists(), "missing mandatory value"); + func_array_append(ctx, &f); + ctx.log("testwasmlib.funcArrayAppend ok"); } -pub struct ArrayCreateContext { +pub struct ArrayClearContext { events: TestWasmLibEvents, - params: ImmutableArrayCreateParams, + params: ImmutableArrayClearParams, state: MutableTestWasmLibState, } -fn func_array_create_thunk(ctx: &ScFuncContext) { - ctx.log("testwasmlib.funcArrayCreate"); - let f = ArrayCreateContext { +fn func_array_clear_thunk(ctx: &ScFuncContext) { + ctx.log("testwasmlib.funcArrayClear"); + let f = ArrayClearContext { events: TestWasmLibEvents {}, - params: ImmutableArrayCreateParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableArrayClearParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); - func_array_create(ctx, &f); - ctx.log("testwasmlib.funcArrayCreate ok"); + func_array_clear(ctx, &f); + ctx.log("testwasmlib.funcArrayClear ok"); } pub struct ArraySetContext { @@ -110,12 +124,8 @@ fn func_array_set_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcArraySet"); let f = ArraySetContext { events: TestWasmLibEvents {}, - params: ImmutableArraySetParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableArraySetParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.index().exists(), "missing mandatory index"); ctx.require(f.params.name().exists(), "missing mandatory name"); @@ -134,40 +144,14 @@ fn func_map_clear_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcMapClear"); let f = MapClearContext { events: TestWasmLibEvents {}, - params: ImmutableMapClearParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableMapClearParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); func_map_clear(ctx, &f); ctx.log("testwasmlib.funcMapClear ok"); } -pub struct MapCreateContext { - events: TestWasmLibEvents, - params: ImmutableMapCreateParams, - state: MutableTestWasmLibState, -} - -fn func_map_create_thunk(ctx: &ScFuncContext) { - ctx.log("testwasmlib.funcMapCreate"); - let f = MapCreateContext { - events: TestWasmLibEvents {}, - params: ImmutableMapCreateParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, - }; - ctx.require(f.params.name().exists(), "missing mandatory name"); - func_map_create(ctx, &f); - ctx.log("testwasmlib.funcMapCreate ok"); -} - pub struct MapSetContext { events: TestWasmLibEvents, params: ImmutableMapSetParams, @@ -178,12 +162,8 @@ fn func_map_set_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcMapSet"); let f = MapSetContext { events: TestWasmLibEvents {}, - params: ImmutableMapSetParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableMapSetParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.key().exists(), "missing mandatory key"); ctx.require(f.params.name().exists(), "missing mandatory name"); @@ -202,12 +182,8 @@ fn func_param_types_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcParamTypes"); let f = ParamTypesContext { events: TestWasmLibEvents {}, - params: ImmutableParamTypesParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableParamTypesParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; func_param_types(ctx, &f); ctx.log("testwasmlib.funcParamTypes ok"); @@ -222,9 +198,7 @@ fn func_random_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcRandom"); let f = RandomContext { events: TestWasmLibEvents {}, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; func_random(ctx, &f); ctx.log("testwasmlib.funcRandom ok"); @@ -240,12 +214,8 @@ fn func_trigger_event_thunk(ctx: &ScFuncContext) { ctx.log("testwasmlib.funcTriggerEvent"); let f = TriggerEventContext { events: TestWasmLibEvents {}, - params: ImmutableTriggerEventParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableTriggerEventParams { proxy: params_proxy() }, + state: MutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.name().exists(), "missing mandatory name"); @@ -262,18 +232,13 @@ pub struct ArrayLengthContext { fn view_array_length_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewArrayLength"); let f = ArrayLengthContext { - params: ImmutableArrayLengthParams { - id: OBJ_ID_PARAMS, - }, - results: MutableArrayLengthResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableArrayLengthParams { proxy: params_proxy() }, + results: MutableArrayLengthResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.name().exists(), "missing mandatory name"); view_array_length(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewArrayLength ok"); } @@ -286,19 +251,14 @@ pub struct ArrayValueContext { fn view_array_value_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewArrayValue"); let f = ArrayValueContext { - params: ImmutableArrayValueParams { - id: OBJ_ID_PARAMS, - }, - results: MutableArrayValueResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableArrayValueParams { proxy: params_proxy() }, + results: MutableArrayValueResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.index().exists(), "missing mandatory index"); ctx.require(f.params.name().exists(), "missing mandatory name"); view_array_value(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewArrayValue ok"); } @@ -311,19 +271,14 @@ pub struct BlockRecordContext { fn view_block_record_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewBlockRecord"); let f = BlockRecordContext { - params: ImmutableBlockRecordParams { - id: OBJ_ID_PARAMS, - }, - results: MutableBlockRecordResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableBlockRecordParams { proxy: params_proxy() }, + results: MutableBlockRecordResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.block_index().exists(), "missing mandatory blockIndex"); ctx.require(f.params.record_index().exists(), "missing mandatory recordIndex"); view_block_record(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewBlockRecord ok"); } @@ -336,18 +291,13 @@ pub struct BlockRecordsContext { fn view_block_records_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewBlockRecords"); let f = BlockRecordsContext { - params: ImmutableBlockRecordsParams { - id: OBJ_ID_PARAMS, - }, - results: MutableBlockRecordsResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableBlockRecordsParams { proxy: params_proxy() }, + results: MutableBlockRecordsResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.block_index().exists(), "missing mandatory blockIndex"); view_block_records(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewBlockRecords ok"); } @@ -359,14 +309,11 @@ pub struct GetRandomContext { fn view_get_random_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewGetRandom"); let f = GetRandomContext { - results: MutableGetRandomResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + results: MutableGetRandomResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; view_get_random(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewGetRandom ok"); } @@ -378,14 +325,11 @@ pub struct IotaBalanceContext { fn view_iota_balance_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewIotaBalance"); let f = IotaBalanceContext { - results: MutableIotaBalanceResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + results: MutableIotaBalanceResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; view_iota_balance(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewIotaBalance ok"); } @@ -398,18 +342,13 @@ pub struct MapValueContext { fn view_map_value_thunk(ctx: &ScViewContext) { ctx.log("testwasmlib.viewMapValue"); let f = MapValueContext { - params: ImmutableMapValueParams { - id: OBJ_ID_PARAMS, - }, - results: MutableMapValueResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutableTestWasmLibState { - id: OBJ_ID_STATE, - }, + params: ImmutableMapValueParams { proxy: params_proxy() }, + results: MutableMapValueResults { proxy: results_proxy() }, + state: ImmutableTestWasmLibState { proxy: state_proxy() }, }; ctx.require(f.params.key().exists(), "missing mandatory key"); ctx.require(f.params.name().exists(), "missing mandatory name"); view_map_value(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("testwasmlib.viewMapValue ok"); } diff --git a/contracts/wasm/testwasmlib/src/params.rs b/contracts/wasm/testwasmlib/src/params.rs index 1d9f4e9d87..8b95fc56af 100644 --- a/contracts/wasm/testwasmlib/src/params.rs +++ b/contracts/wasm/testwasmlib/src/params.rs @@ -9,528 +9,510 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] -pub struct ImmutableArrayClearParams { - pub(crate) id: i32, +#[derive(Clone)] +pub struct ImmutableArrayAppendParams { + pub(crate) proxy: Proxy, } -impl ImmutableArrayClearParams { +impl ImmutableArrayAppendParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) + } + + pub fn value(&self) -> ScImmutableString { + ScImmutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] -pub struct MutableArrayClearParams { - pub(crate) id: i32, +#[derive(Clone)] +pub struct MutableArrayAppendParams { + pub(crate) proxy: Proxy, } -impl MutableArrayClearParams { +impl MutableArrayAppendParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) + } + + pub fn value(&self) -> ScMutableString { + ScMutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] -pub struct ImmutableArrayCreateParams { - pub(crate) id: i32, +#[derive(Clone)] +pub struct ImmutableArrayClearParams { + pub(crate) proxy: Proxy, } -impl ImmutableArrayCreateParams { +impl ImmutableArrayClearParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] -pub struct MutableArrayCreateParams { - pub(crate) id: i32, +#[derive(Clone)] +pub struct MutableArrayClearParams { + pub(crate) proxy: Proxy, } -impl MutableArrayCreateParams { +impl MutableArrayClearParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableArraySetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableArraySetParams { - pub fn index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_INDEX.get_key_id()) + pub fn index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_INDEX)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } pub fn value(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_VALUE.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableArraySetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableArraySetParams { - pub fn index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_INDEX.get_key_id()) + pub fn index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_INDEX)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } pub fn value(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_VALUE.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMapClearParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMapClearParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMapClearParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMapClearParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableMapCreateParams { - pub(crate) id: i32, -} - -impl ImmutableMapCreateParams { - pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableMapCreateParams { - pub(crate) id: i32, -} - -impl MutableMapCreateParams { - pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMapSetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMapSetParams { pub fn key(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_KEY.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_KEY)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } pub fn value(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_VALUE.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMapSetParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMapSetParams { pub fn key(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_KEY.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_KEY)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } pub fn value(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_VALUE.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableBytes { pub fn get_bytes(&self, key: &str) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, key.get_key_id()) + ScImmutableBytes::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableParamTypesParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableParamTypesParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn bool(&self) -> ScImmutableBool { - ScImmutableBool::new(self.id, PARAM_BOOL.get_key_id()) + ScImmutableBool::new(self.proxy.root(PARAM_BOOL)) } pub fn bytes(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, PARAM_BYTES.get_key_id()) + ScImmutableBytes::new(self.proxy.root(PARAM_BYTES)) } pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScImmutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn int16(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, PARAM_INT16.get_key_id()) + ScImmutableInt16::new(self.proxy.root(PARAM_INT16)) } pub fn int32(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_INT32.get_key_id()) + ScImmutableInt32::new(self.proxy.root(PARAM_INT32)) } pub fn int64(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int8(&self) -> ScImmutableInt8 { - ScImmutableInt8::new(self.id, PARAM_INT8.get_key_id()) + ScImmutableInt8::new(self.proxy.root(PARAM_INT8)) } pub fn param(&self) -> MapStringToImmutableBytes { - MapStringToImmutableBytes { obj_id: self.id } + MapStringToImmutableBytes { proxy: self.proxy.clone() } } pub fn request_id(&self) -> ScImmutableRequestID { - ScImmutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) + ScImmutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) } pub fn string(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_STRING.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_STRING)) } pub fn uint16(&self) -> ScImmutableUint16 { - ScImmutableUint16::new(self.id, PARAM_UINT16.get_key_id()) + ScImmutableUint16::new(self.proxy.root(PARAM_UINT16)) } pub fn uint32(&self) -> ScImmutableUint32 { - ScImmutableUint32::new(self.id, PARAM_UINT32.get_key_id()) + ScImmutableUint32::new(self.proxy.root(PARAM_UINT32)) } pub fn uint64(&self) -> ScImmutableUint64 { - ScImmutableUint64::new(self.id, PARAM_UINT64.get_key_id()) + ScImmutableUint64::new(self.proxy.root(PARAM_UINT64)) } pub fn uint8(&self) -> ScImmutableUint8 { - ScImmutableUint8::new(self.id, PARAM_UINT8.get_key_id()) + ScImmutableUint8::new(self.proxy.root(PARAM_UINT8)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableBytes { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bytes(&self, key: &str) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, key.get_key_id()) + ScMutableBytes::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableParamTypesParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableParamTypesParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } pub fn bool(&self) -> ScMutableBool { - ScMutableBool::new(self.id, PARAM_BOOL.get_key_id()) + ScMutableBool::new(self.proxy.root(PARAM_BOOL)) } pub fn bytes(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, PARAM_BYTES.get_key_id()) + ScMutableBytes::new(self.proxy.root(PARAM_BYTES)) } pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, PARAM_CHAIN_ID.get_key_id()) + ScMutableChainID::new(self.proxy.root(PARAM_CHAIN_ID)) } pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_HASH)) } pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn int16(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, PARAM_INT16.get_key_id()) + ScMutableInt16::new(self.proxy.root(PARAM_INT16)) } pub fn int32(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_INT32.get_key_id()) + ScMutableInt32::new(self.proxy.root(PARAM_INT32)) } pub fn int64(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_INT64.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_INT64)) } pub fn int8(&self) -> ScMutableInt8 { - ScMutableInt8::new(self.id, PARAM_INT8.get_key_id()) + ScMutableInt8::new(self.proxy.root(PARAM_INT8)) } pub fn param(&self) -> MapStringToMutableBytes { - MapStringToMutableBytes { obj_id: self.id } + MapStringToMutableBytes { proxy: self.proxy.clone() } } pub fn request_id(&self) -> ScMutableRequestID { - ScMutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) + ScMutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) } pub fn string(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_STRING.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_STRING)) } pub fn uint16(&self) -> ScMutableUint16 { - ScMutableUint16::new(self.id, PARAM_UINT16.get_key_id()) + ScMutableUint16::new(self.proxy.root(PARAM_UINT16)) } pub fn uint32(&self) -> ScMutableUint32 { - ScMutableUint32::new(self.id, PARAM_UINT32.get_key_id()) + ScMutableUint32::new(self.proxy.root(PARAM_UINT32)) } pub fn uint64(&self) -> ScMutableUint64 { - ScMutableUint64::new(self.id, PARAM_UINT64.get_key_id()) + ScMutableUint64::new(self.proxy.root(PARAM_UINT64)) } pub fn uint8(&self) -> ScMutableUint8 { - ScMutableUint8::new(self.id, PARAM_UINT8.get_key_id()) + ScMutableUint8::new(self.proxy.root(PARAM_UINT8)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTriggerEventParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTriggerEventParams { pub fn address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTriggerEventParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTriggerEventParams { pub fn address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_ADDRESS)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableArrayLengthParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableArrayLengthParams { pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableArrayLengthParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableArrayLengthParams { pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableArrayValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableArrayValueParams { - pub fn index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_INDEX.get_key_id()) + pub fn index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_INDEX)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableArrayValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableArrayValueParams { - pub fn index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_INDEX.get_key_id()) + pub fn index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_INDEX)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBlockRecordParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBlockRecordParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) } - pub fn record_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_RECORD_INDEX.get_key_id()) + pub fn record_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_RECORD_INDEX)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBlockRecordParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBlockRecordParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) } - pub fn record_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_RECORD_INDEX.get_key_id()) + pub fn record_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_RECORD_INDEX)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBlockRecordsParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBlockRecordsParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBlockRecordsParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBlockRecordsParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMapValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMapValueParams { pub fn key(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_KEY.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_KEY)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMapValueParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMapValueParams { pub fn key(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_KEY.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_KEY)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } } diff --git a/contracts/wasm/testwasmlib/src/results.rs b/contracts/wasm/testwasmlib/src/results.rs index e46d27f60b..2188072279 100644 --- a/contracts/wasm/testwasmlib/src/results.rs +++ b/contracts/wasm/testwasmlib/src/results.rs @@ -9,162 +9,158 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableArrayLengthResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableArrayLengthResults { - pub fn length(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_LENGTH.get_key_id()) + pub fn length(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_LENGTH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableArrayLengthResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableArrayLengthResults { - pub fn length(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_LENGTH.get_key_id()) + pub fn length(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_LENGTH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableArrayValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableArrayValueResults { pub fn value(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_VALUE.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableArrayValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableArrayValueResults { pub fn value(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_VALUE.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBlockRecordResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBlockRecordResults { pub fn record(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_RECORD.get_key_id()) + ScImmutableBytes::new(self.proxy.root(RESULT_RECORD)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBlockRecordResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBlockRecordResults { pub fn record(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_RECORD.get_key_id()) + ScMutableBytes::new(self.proxy.root(RESULT_RECORD)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBlockRecordsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBlockRecordsResults { - pub fn count(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_COUNT.get_key_id()) + pub fn count(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_COUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBlockRecordsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBlockRecordsResults { - pub fn count(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_COUNT.get_key_id()) + pub fn count(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_COUNT)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetRandomResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetRandomResults { - pub fn random(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_RANDOM.get_key_id()) + pub fn random(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_RANDOM)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetRandomResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetRandomResults { - pub fn random(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_RANDOM.get_key_id()) + pub fn random(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_RANDOM)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableIotaBalanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableIotaBalanceResults { - pub fn iotas(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_IOTAS.get_key_id()) + pub fn iotas(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_IOTAS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableIotaBalanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableIotaBalanceResults { - pub fn iotas(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_IOTAS.get_key_id()) + pub fn iotas(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_IOTAS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMapValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMapValueResults { pub fn value(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_VALUE.get_key_id()) + ScImmutableString::new(self.proxy.root(RESULT_VALUE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMapValueResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMapValueResults { pub fn value(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_VALUE.get_key_id()) + ScMutableString::new(self.proxy.root(RESULT_VALUE)) } } diff --git a/contracts/wasm/testwasmlib/src/state.rs b/contracts/wasm/testwasmlib/src/state.rs index 01ceb24c3b..e6167cb418 100644 --- a/contracts/wasm/testwasmlib/src/state.rs +++ b/contracts/wasm/testwasmlib/src/state.rs @@ -9,110 +9,99 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::typedefs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableStringArray { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableStringArray { pub fn get_string_array(&self, key: &str) -> ImmutableStringArray { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ARRAY | TYPE_STRING); - ImmutableStringArray { obj_id: sub_id } + ImmutableStringArray { proxy: self.proxy.key(&string_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableStringMap { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableStringMap { pub fn get_string_map(&self, key: &str) -> ImmutableStringMap { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ImmutableStringMap { obj_id: sub_id } + ImmutableStringMap { proxy: self.proxy.key(&string_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTestWasmLibState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTestWasmLibState { pub fn arrays(&self) -> MapStringToImmutableStringArray { - let map_id = get_object_id(self.id, STATE_ARRAYS.get_key_id(), TYPE_MAP); - MapStringToImmutableStringArray { obj_id: map_id } + MapStringToImmutableStringArray { proxy: self.proxy.root(STATE_ARRAYS) } } pub fn maps(&self) -> MapStringToImmutableStringMap { - let map_id = get_object_id(self.id, STATE_MAPS.get_key_id(), TYPE_MAP); - MapStringToImmutableStringMap { obj_id: map_id } + MapStringToImmutableStringMap { proxy: self.proxy.root(STATE_MAPS) } } - pub fn random(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_RANDOM.get_key_id()) + pub fn random(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(STATE_RANDOM)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableStringArray { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableStringArray { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_string_array(&self, key: &str) -> MutableStringArray { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ARRAY | TYPE_STRING); - MutableStringArray { obj_id: sub_id } + MutableStringArray { proxy: self.proxy.key(&string_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableStringMap { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableStringMap { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_string_map(&self, key: &str) -> MutableStringMap { - let sub_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - MutableStringMap { obj_id: sub_id } + MutableStringMap { proxy: self.proxy.key(&string_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTestWasmLibState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTestWasmLibState { pub fn as_immutable(&self) -> ImmutableTestWasmLibState { - ImmutableTestWasmLibState { id: self.id } + ImmutableTestWasmLibState { proxy: self.proxy.root("") } } pub fn arrays(&self) -> MapStringToMutableStringArray { - let map_id = get_object_id(self.id, STATE_ARRAYS.get_key_id(), TYPE_MAP); - MapStringToMutableStringArray { obj_id: map_id } + MapStringToMutableStringArray { proxy: self.proxy.root(STATE_ARRAYS) } } pub fn maps(&self) -> MapStringToMutableStringMap { - let map_id = get_object_id(self.id, STATE_MAPS.get_key_id(), TYPE_MAP); - MapStringToMutableStringMap { obj_id: map_id } + MapStringToMutableStringMap { proxy: self.proxy.root(STATE_MAPS) } } - pub fn random(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_RANDOM.get_key_id()) + pub fn random(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(STATE_RANDOM)) } } diff --git a/contracts/wasm/testwasmlib/src/structs.rs b/contracts/wasm/testwasmlib/src/structs.rs deleted file mode 100644 index 9d670e8dee..0000000000 --- a/contracts/wasm/testwasmlib/src/structs.rs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] -#![allow(unused_imports)] - -use wasmlib::*; -use wasmlib::host::*; -use crate::typedefs::*; - -pub struct Location { - pub x : i32, - pub y : i32, -} - -impl Location { - pub fn from_bytes(bytes: &[u8]) -> Location { - let mut decode = BytesDecoder::new(bytes); - Location { - x : decode.int32(), - y : decode.int32(), - } - } - - pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.int32(self.x); - encode.int32(self.y); - return encode.data(); - } -} - -pub struct ImmutableLocation { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, -} - -impl ImmutableLocation { - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) - } - - pub fn value(&self) -> Location { - Location::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) - } -} - -pub struct MutableLocation { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, -} - -impl MutableLocation { - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); - } - - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) - } - - pub fn set_value(&self, value: &Location) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); - } - - pub fn value(&self) -> Location { - Location::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) - } -} diff --git a/contracts/wasm/testwasmlib/src/testwasmlib.rs b/contracts/wasm/testwasmlib/src/testwasmlib.rs index 31db1e8ab6..bceec5fc3d 100644 --- a/contracts/wasm/testwasmlib/src/testwasmlib.rs +++ b/contracts/wasm/testwasmlib/src/testwasmlib.rs @@ -5,13 +5,14 @@ use wasmlib::*; use crate::*; -pub fn func_array_clear(_ctx: &ScFuncContext, f: &ArrayClearContext) { +pub fn func_array_append(_ctx: &ScFuncContext, f: &ArrayAppendContext) { let name = f.params.name().value(); let array = f.state.arrays().get_string_array(&name); - array.clear(); + let value = f.params.value().value(); + array.append_string().set_value(&value); } -pub fn func_array_create(_ctx: &ScFuncContext, f: &ArrayCreateContext) { +pub fn func_array_clear(_ctx: &ScFuncContext, f: &ArrayClearContext) { let name = f.params.name().value(); let array = f.state.arrays().get_string_array(&name); array.clear(); @@ -25,6 +26,20 @@ pub fn func_array_set(_ctx: &ScFuncContext, f: &ArraySetContext) { array.get_string(index).set_value(&value); } +pub fn func_map_clear(_ctx: &ScFuncContext, f: &MapClearContext) { + let name = f.params.name().value(); + let my_map = f.state.maps().get_string_map(&name); + my_map.clear(); +} + +pub fn func_map_set(_ctx: &ScFuncContext, f: &MapSetContext) { + let name = f.params.name().value(); + let my_map = f.state.maps().get_string_map(&name); + let key = f.params.key().value(); + let value = f.params.value().value(); + my_map.get_string(&key).set_value(&value); +} + pub fn func_param_types(ctx: &ScFuncContext, f: &ParamTypesContext) { if f.params.address().exists() { ctx.require(f.params.address().value() == ctx.account_id().address(), "mismatch: Address"); @@ -43,11 +58,11 @@ pub fn func_param_types(ctx: &ScFuncContext, f: &ParamTypesContext) { ctx.require(f.params.chain_id().value() == ctx.chain_id(), "mismatch: ChainID"); } if f.params.color().exists() { - let color = ScColor::from_bytes("RedGreenBlueYellowCyanBlackWhite".as_bytes()); + let color = color_from_bytes("RedGreenBlueYellowCyanBlackWhite".as_bytes()); ctx.require(f.params.color().value() == color, "mismatch: Color"); } if f.params.hash().exists() { - let hash = ScHash::from_bytes("0123456789abcdeffedcba9876543210".as_bytes()); + let hash = hash_from_bytes("0123456789abcdeffedcba9876543210".as_bytes()); ctx.require(f.params.hash().value() == hash, "mismatch: Hash"); } if f.params.hname().exists() { @@ -66,7 +81,7 @@ pub fn func_param_types(ctx: &ScFuncContext, f: &ParamTypesContext) { ctx.require(f.params.int64().value() == -1234567890123456789, "mismatch: Int64"); } if f.params.request_id().exists() { - let request_id = ScRequestID::from_bytes("abcdefghijklmnopqrstuvwxyz123456\x00\x00".as_bytes()); + let request_id = request_id_from_bytes("abcdefghijklmnopqrstuvwxyz123456\x00\x00".as_bytes()); ctx.require(f.params.request_id().value() == request_id, "mismatch: RequestID"); } if f.params.string().exists() { @@ -86,6 +101,14 @@ pub fn func_param_types(ctx: &ScFuncContext, f: &ParamTypesContext) { } } +pub fn func_random(ctx: &ScFuncContext, f: &RandomContext) { + f.state.random().set_value(ctx.random(1000)); +} + +pub fn func_trigger_event(_ctx: &ScFuncContext, f: &TriggerEventContext) { + f.events.test(&f.params.address().value(), &f.params.name().value()); +} + pub fn view_array_length(_ctx: &ScViewContext, f: &ArrayLengthContext) { let name = f.params.name().value(); let array = f.state.arrays().get_string_array(&name); @@ -117,29 +140,12 @@ pub fn view_block_records(ctx: &ScViewContext, f: &BlockRecordsContext) { f.results.count().set_value(records.results.request_record().length()); } -pub fn view_iota_balance(ctx: &ScViewContext, f: &IotaBalanceContext) { - f.results.iotas().set_value(ctx.balances().balance(&ScColor::IOTA)); -} - -pub fn func_random(ctx: &ScFuncContext, f: &RandomContext) { - f.state.random().set_value(ctx.random(1000)); -} - pub fn view_get_random(_ctx: &ScViewContext, f: &GetRandomContext) { f.results.random().set_value(f.state.random().value()); } -pub fn func_trigger_event(_ctx: &ScFuncContext, f: &TriggerEventContext) { - f.events.test(&f.params.address().value(), &f.params.name().value()); -} - -pub fn func_map_clear(_ctx: &ScFuncContext, _f: &MapClearContext) { -} - -pub fn func_map_create(_ctx: &ScFuncContext, _f: &MapCreateContext) { -} - -pub fn func_map_set(_ctx: &ScFuncContext, _f: &MapSetContext) { +pub fn view_iota_balance(ctx: &ScViewContext, f: &IotaBalanceContext) { + f.results.iotas().set_value(ctx.balances().balance(&ScColor::IOTA)); } pub fn view_map_value(_ctx: &ScViewContext, _f: &MapValueContext) { diff --git a/contracts/wasm/testwasmlib/src/typedefs.rs b/contracts/wasm/testwasmlib/src/typedefs.rs index 7f96eb2368..f217502412 100644 --- a/contracts/wasm/testwasmlib/src/typedefs.rs +++ b/contracts/wasm/testwasmlib/src/typedefs.rs @@ -8,71 +8,75 @@ #![allow(dead_code)] use wasmlib::*; -use wasmlib::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableString { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_string(&self, index: i32) -> ScImmutableString { - ScImmutableString::new(self.obj_id, Key32(index)) + pub fn get_string(&self, index: u32) -> ScImmutableString { + ScImmutableString::new(self.proxy.index(index)) } } pub type ImmutableStringArray = ArrayOfImmutableString; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableString { - pub fn clear(&self) { - clear(self.obj_id); + pub fn append_string(&self) -> ScMutableString { + ScMutableString::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_string(&self, index: i32) -> ScMutableString { - ScMutableString::new(self.obj_id, Key32(index)) + pub fn get_string(&self, index: u32) -> ScMutableString { + ScMutableString::new(self.proxy.index(index)) } } pub type MutableStringArray = ArrayOfMutableString; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableString { pub fn get_string(&self, key: &str) -> ScImmutableString { - ScImmutableString::new(self.obj_id, key.get_key_id()) + ScImmutableString::new(self.proxy.key(&string_to_bytes(key))) } } pub type ImmutableStringMap = MapStringToImmutableString; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableString { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableString { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_string(&self, key: &str) -> ScMutableString { - ScMutableString::new(self.obj_id, key.get_key_id()) + ScMutableString::new(self.proxy.key(&string_to_bytes(key))) } } diff --git a/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm b/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm index 39e10ae724..6fb540fc53 100644 Binary files a/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm and b/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm differ diff --git a/contracts/wasm/testwasmlib/test/testwasmlib_client_test.go b/contracts/wasm/testwasmlib/test/testwasmlib_client_test.go index f96da7f4b4..4159dd79a2 100644 --- a/contracts/wasm/testwasmlib/test/testwasmlib_client_test.go +++ b/contracts/wasm/testwasmlib/test/testwasmlib_client_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/iotaledger/wasp/contracts/wasm/testwasmlib/go/testwasmlibclient" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" - coreaccountsclient "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient/coreaccounts" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" + coreaccountsclient "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient/coreaccounts" "github.com/stretchr/testify/require" ) @@ -15,7 +15,7 @@ import ( // the contract has already been deployed in some way, so // these values are usually available from elsewhere const ( - myChainID = "tRA59jhoDG9QpXi7NcQ3phuQaaPqgXRBgXxK2Sy1FPGf" + myChainID = "pDtVgzXtTwc2B9bnrf2RbpWuexynqNiGU7waLknsgjWf" mySeed = "6C6tRksZDWeDTCzX4Q7R2hbpyFV86cSGLVxdkFKSB3sv" ) @@ -40,6 +40,11 @@ func setupClient(t *testing.T) *testwasmlibclient.TestWasmLibService { func TestClientEvents(t *testing.T) { svc := setupClient(t) + events := svc.NewEventHandler() + events.OnTestWasmLibTest(func(e *testwasmlibclient.EventTest) { + fmt.Printf("Name is %s\n", e.Name) + }) + svc.Register(events) // get new triggerEvent interface, pass params, and post the request f := svc.TriggerEvent() @@ -48,8 +53,8 @@ func TestClientEvents(t *testing.T) { req1 := f.Post() require.NoError(t, req1.Error()) - // err := svc.WaitRequest(req1) - // require.NoError(t, err) + err := svc.WaitRequest(req1) + require.NoError(t, err) // get new triggerEvent interface, pass params, and post the request f = svc.TriggerEvent() @@ -58,7 +63,7 @@ func TestClientEvents(t *testing.T) { req2 := f.Post() require.NoError(t, req2.Error()) - err := svc.WaitRequest(req2) + err = svc.WaitRequest(req2) require.NoError(t, err) } diff --git a/contracts/wasm/testwasmlib/test/testwasmlib_test.go b/contracts/wasm/testwasmlib/test/testwasmlib_test.go index 1fb5acb218..f2af58814b 100644 --- a/contracts/wasm/testwasmlib/test/testwasmlib_test.go +++ b/contracts/wasm/testwasmlib/test/testwasmlib_test.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package test import ( @@ -9,8 +12,8 @@ import ( "github.com/iotaledger/goshimmer/packages/ledgerstate" "github.com/iotaledger/wasp/contracts/wasm/testwasmlib/go/testwasmlib" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -34,7 +37,7 @@ var ( testwasmlib.ParamUint64, } allLengths = []int{33, 37, 1, 33, 32, 32, 4, 1, 2, 4, 8, 34, 1, 2, 4, 8} - invalidValues = map[wasmlib.Key][][]byte{ + invalidValues = map[string][][]byte{ testwasmlib.ParamAddress: { append([]byte{3}, zeroHash...), append([]byte{4}, zeroHash...), @@ -71,7 +74,7 @@ func TestNoParams(t *testing.T) { ctx := setupTest(t) f := testwasmlib.ScFuncs.ParamTypes(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) } @@ -88,20 +91,20 @@ func testValidParams(t *testing.T) *wasmsolo.SoloContext { pt.Params.Bool().SetValue(true) pt.Params.Bytes().SetValue([]byte("these are bytes")) pt.Params.ChainID().SetValue(ctx.ChainID()) - pt.Params.Color().SetValue(wasmlib.NewScColorFromBytes([]byte("RedGreenBlueYellowCyanBlackWhite"))) - pt.Params.Hash().SetValue(wasmlib.NewScHashFromBytes([]byte("0123456789abcdeffedcba9876543210"))) + pt.Params.Color().SetValue(wasmtypes.ColorFromBytes([]byte("RedGreenBlueYellowCyanBlackWhite"))) + pt.Params.Hash().SetValue(wasmtypes.HashFromBytes([]byte("0123456789abcdeffedcba9876543210"))) pt.Params.Hname().SetValue(testwasmlib.HScName) pt.Params.Int8().SetValue(-123) pt.Params.Int16().SetValue(-12345) pt.Params.Int32().SetValue(-1234567890) pt.Params.Int64().SetValue(-1234567890123456789) - pt.Params.RequestID().SetValue(wasmlib.NewScRequestIDFromBytes([]byte("abcdefghijklmnopqrstuvwxyz123456\x00\x00"))) + pt.Params.RequestID().SetValue(wasmtypes.RequestIDFromBytes([]byte("abcdefghijklmnopqrstuvwxyz123456\x00\x00"))) pt.Params.String().SetValue("this is a string") pt.Params.Uint8().SetValue(123) pt.Params.Uint16().SetValue(12345) pt.Params.Uint32().SetValue(1234567890) pt.Params.Uint64().SetValue(1234567890123456789) - pt.Func.TransferIotas(1).Post() + pt.Func.Post() require.NoError(t, ctx.Err) return ctx } @@ -110,15 +113,16 @@ func TestValidSizeParams(t *testing.T) { ctx := setupTest(t) for index, param := range allParams { t.Run("ValidSize "+param, func(t *testing.T) { + paramMismatch := fmt.Sprintf("mismatch: %s%s", strings.ToUpper(param[:1]), param[1:]) pt := testwasmlib.ScFuncs.ParamTypes(ctx) bytes := make([]byte, allLengths[index]) if param == testwasmlib.ParamChainID { bytes[0] = byte(ledgerstate.AliasAddressType) } pt.Params.Param().GetBytes(param).SetValue(bytes) - pt.Func.TransferIotas(1).Post() + pt.Func.Post() require.Error(t, ctx.Err) - require.Contains(t, ctx.Err.Error(), "mismatch: ") + require.Contains(t, ctx.Err.Error(), paramMismatch) }) } } @@ -127,23 +131,30 @@ func TestInvalidSizeParams(t *testing.T) { ctx := setupTest(t) for index, param := range allParams { t.Run("InvalidSize "+param, func(t *testing.T) { - pt := testwasmlib.ScFuncs.ParamTypes(ctx) - pt.Params.Param().GetBytes(param).SetValue(make([]byte, 0)) - pt.Func.TransferIotas(1).Post() - require.Error(t, ctx.Err) - require.True(t, strings.HasSuffix(ctx.Err.Error(), "invalid type size")) - - pt = testwasmlib.ScFuncs.ParamTypes(ctx) - pt.Params.Param().GetBytes(param).SetValue(make([]byte, allLengths[index]-1)) - pt.Func.TransferIotas(1).Post() - require.Error(t, ctx.Err) - require.True(t, strings.HasSuffix(ctx.Err.Error(), "invalid type size")) + invalidLength := fmt.Sprintf("invalid %s%s length", strings.ToUpper(param[:1]), param[1:]) + + // note that zero lengths are valid and will return a default value + + // no need to check bool/int8/uint8 + if allLengths[index] != 1 { + pt := testwasmlib.ScFuncs.ParamTypes(ctx) + pt.Params.Param().GetBytes(param).SetValue(make([]byte, 1)) + pt.Func.Post() + require.Error(t, ctx.Err) + require.Contains(t, ctx.Err.Error(), invalidLength) + + pt = testwasmlib.ScFuncs.ParamTypes(ctx) + pt.Params.Param().GetBytes(param).SetValue(make([]byte, allLengths[index]-1)) + pt.Func.Post() + require.Error(t, ctx.Err) + require.Contains(t, ctx.Err.Error(), invalidLength) + } - pt = testwasmlib.ScFuncs.ParamTypes(ctx) + pt := testwasmlib.ScFuncs.ParamTypes(ctx) pt.Params.Param().GetBytes(param).SetValue(make([]byte, allLengths[index]+1)) - pt.Func.TransferIotas(1).Post() + pt.Func.Post() require.Error(t, ctx.Err) - require.Contains(t, ctx.Err.Error(), "invalid type size") + require.Contains(t, ctx.Err.Error(), invalidLength) }) } } @@ -152,13 +163,14 @@ func TestInvalidTypeParams(t *testing.T) { ctx := setupTest(t) for param, values := range invalidValues { for index, value := range values { - t.Run("InvalidType "+string(param)+" "+strconv.Itoa(index), func(t *testing.T) { + t.Run("InvalidType "+param+" "+strconv.Itoa(index), func(t *testing.T) { + invalidParam := fmt.Sprintf("invalid %s%s", strings.ToUpper(param[:1]), param[1:]) req := solo.NewCallParams(testwasmlib.ScName, testwasmlib.FuncParamTypes, - string(param), value, + param, value, ).WithIotas(1) _, err := ctx.Chain.PostRequestSync(req, nil) require.Error(t, err) - require.Contains(t, err.Error(), "invalid ") + require.Contains(t, err.Error(), invalidParam) }) } } @@ -187,25 +199,22 @@ func TestViewBlockRecords(t *testing.T) { func TestClearArray(t *testing.T) { ctx := setupTest(t) - as := testwasmlib.ScFuncs.ArraySet(ctx) + as := testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") - as.Params.Index().SetValue(0) as.Params.Value().SetValue("Simple Minds") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) - as = testwasmlib.ScFuncs.ArraySet(ctx) + as = testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") - as.Params.Index().SetValue(1) as.Params.Value().SetValue("Dire Straits") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) - as = testwasmlib.ScFuncs.ArraySet(ctx) + as = testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") - as.Params.Index().SetValue(2) as.Params.Value().SetValue("ELO") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) al := testwasmlib.ScFuncs.ArrayLength(ctx) @@ -227,7 +236,7 @@ func TestClearArray(t *testing.T) { ac := testwasmlib.ScFuncs.ArrayClear(ctx) ac.Params.Name().SetValue("bands") - ac.Func.TransferIotas(1).Post() + ac.Func.Post() require.NoError(t, ctx.Err) al = testwasmlib.ScFuncs.ArrayLength(ctx) @@ -249,32 +258,31 @@ func TestClearMap(t *testing.T) { // test reproduces a problem that needs fixing t.SkipNow() - *wasmsolo.GoDebug = true ctx := setupTest(t) as := testwasmlib.ScFuncs.MapSet(ctx) as.Params.Name().SetValue("albums") as.Params.Key().SetValue("Simple Minds") as.Params.Value().SetValue("New Gold Dream") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) as = testwasmlib.ScFuncs.MapSet(ctx) - as.Params.Name().SetValue("bands") + as.Params.Name().SetValue("albums") as.Params.Key().SetValue("Dire Straits") as.Params.Value().SetValue("Calling Elvis") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) as = testwasmlib.ScFuncs.MapSet(ctx) - as.Params.Name().SetValue("bands") + as.Params.Name().SetValue("albums") as.Params.Key().SetValue("ELO") as.Params.Value().SetValue("Mr. Blue Sky") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) av := testwasmlib.ScFuncs.MapValue(ctx) - av.Params.Name().SetValue("bands") + av.Params.Name().SetValue("albums") av.Params.Key().SetValue("Dire Straits") av.Func.Call() require.NoError(t, ctx.Err) @@ -282,13 +290,13 @@ func TestClearMap(t *testing.T) { require.True(t, value.Exists()) require.EqualValues(t, "Calling Elvis", value.Value()) - ac := testwasmlib.ScFuncs.ArrayClear(ctx) - ac.Params.Name().SetValue("bands") - ac.Func.TransferIotas(1).Post() + ac := testwasmlib.ScFuncs.MapClear(ctx) + ac.Params.Name().SetValue("albums") + ac.Func.Post() require.NoError(t, ctx.Err) av = testwasmlib.ScFuncs.MapValue(ctx) - av.Params.Name().SetValue("bands") + av.Params.Name().SetValue("albums") av.Params.Key().SetValue("Dire Straits") av.Func.Call() require.NoError(t, ctx.Err) @@ -324,31 +332,31 @@ func TestRandom(t *testing.T) { ctx := setupTest(t) f := testwasmlib.ScFuncs.Random(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) v := testwasmlib.ScFuncs.GetRandom(ctx) v.Func.Call() require.NoError(t, ctx.Err) random := v.Results.Random().Value() - require.True(t, random >= 0 && random < 1000) + require.True(t, random < 1000) fmt.Printf("Random value: %d\n", random) } func TestMultiRandom(t *testing.T) { ctx := setupTest(t) - numbers := make([]int64, 0) + numbers := make([]uint64, 0) for i := 0; i < 10; i++ { f := testwasmlib.ScFuncs.Random(ctx) - f.Func.TransferIotas(1).Post() + f.Func.Post() require.NoError(t, ctx.Err) v := testwasmlib.ScFuncs.GetRandom(ctx) v.Func.Call() require.NoError(t, ctx.Err) random := v.Results.Random().Value() - require.True(t, random >= 0 && random < 1000) + require.True(t, random < 1000) numbers = append(numbers, random) } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/consts.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/consts.ts index fbce884289..996d0e3dbf 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/consts.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "testwasmlib"; export const ScDescription = "Exercise several aspects of WasmLib"; -export const HScName = new wasmlib.ScHname(0x89703a45); +export const HScName = new wasmtypes.ScHname(0x89703a45); export const ParamAddress = "address"; export const ParamAgentID = "agentID"; @@ -48,11 +48,10 @@ export const StateArrays = "arrays"; export const StateMaps = "maps"; export const StateRandom = "random"; +export const FuncArrayAppend = "arrayAppend"; export const FuncArrayClear = "arrayClear"; -export const FuncArrayCreate = "arrayCreate"; export const FuncArraySet = "arraySet"; export const FuncMapClear = "mapClear"; -export const FuncMapCreate = "mapCreate"; export const FuncMapSet = "mapSet"; export const FuncParamTypes = "paramTypes"; export const FuncRandom = "random"; @@ -65,19 +64,18 @@ export const ViewGetRandom = "getRandom"; export const ViewIotaBalance = "iotaBalance"; export const ViewMapValue = "mapValue"; -export const HFuncArrayClear = new wasmlib.ScHname(0x88021821); -export const HFuncArrayCreate = new wasmlib.ScHname(0x1ed5b23b); -export const HFuncArraySet = new wasmlib.ScHname(0x2c4150b3); -export const HFuncMapClear = new wasmlib.ScHname(0x027f215a); -export const HFuncMapCreate = new wasmlib.ScHname(0x6295d599); -export const HFuncMapSet = new wasmlib.ScHname(0xf2260404); -export const HFuncParamTypes = new wasmlib.ScHname(0x6921c4cd); -export const HFuncRandom = new wasmlib.ScHname(0xe86c97ca); -export const HFuncTriggerEvent = new wasmlib.ScHname(0xd5438ac6); -export const HViewArrayLength = new wasmlib.ScHname(0x3a831021); -export const HViewArrayValue = new wasmlib.ScHname(0x662dbd81); -export const HViewBlockRecord = new wasmlib.ScHname(0xad13b2f8); -export const HViewBlockRecords = new wasmlib.ScHname(0x16e249ea); -export const HViewGetRandom = new wasmlib.ScHname(0x46263045); -export const HViewIotaBalance = new wasmlib.ScHname(0x9d3920bd); -export const HViewMapValue = new wasmlib.ScHname(0x23149bef); +export const HFuncArrayAppend = new wasmtypes.ScHname(0x612f835f); +export const HFuncArrayClear = new wasmtypes.ScHname(0x88021821); +export const HFuncArraySet = new wasmtypes.ScHname(0x2c4150b3); +export const HFuncMapClear = new wasmtypes.ScHname(0x027f215a); +export const HFuncMapSet = new wasmtypes.ScHname(0xf2260404); +export const HFuncParamTypes = new wasmtypes.ScHname(0x6921c4cd); +export const HFuncRandom = new wasmtypes.ScHname(0xe86c97ca); +export const HFuncTriggerEvent = new wasmtypes.ScHname(0xd5438ac6); +export const HViewArrayLength = new wasmtypes.ScHname(0x3a831021); +export const HViewArrayValue = new wasmtypes.ScHname(0x662dbd81); +export const HViewBlockRecord = new wasmtypes.ScHname(0xad13b2f8); +export const HViewBlockRecords = new wasmtypes.ScHname(0x16e249ea); +export const HViewGetRandom = new wasmtypes.ScHname(0x46263045); +export const HViewIotaBalance = new wasmtypes.ScHname(0x9d3920bd); +export const HViewMapValue = new wasmtypes.ScHname(0x23149bef); diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/contract.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/contract.ts index 0b3ecd8c70..dbdebdd6fa 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/contract.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/contract.ts @@ -8,81 +8,70 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; -export class ArrayClearCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncArrayClear); - params: sc.MutableArrayClearParams = new sc.MutableArrayClearParams(); +export class ArrayAppendCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncArrayAppend); + params: sc.MutableArrayAppendParams = new sc.MutableArrayAppendParams(wasmlib.ScView.nilProxy); } -export class ArrayClearContext { +export class ArrayAppendContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableArrayClearParams = new sc.ImmutableArrayClearParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableArrayAppendParams = new sc.ImmutableArrayAppendParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } -export class ArrayCreateCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncArrayCreate); - params: sc.MutableArrayCreateParams = new sc.MutableArrayCreateParams(); +export class ArrayClearCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncArrayClear); + params: sc.MutableArrayClearParams = new sc.MutableArrayClearParams(wasmlib.ScView.nilProxy); } -export class ArrayCreateContext { +export class ArrayClearContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableArrayCreateParams = new sc.ImmutableArrayCreateParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableArrayClearParams = new sc.ImmutableArrayClearParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class ArraySetCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncArraySet); - params: sc.MutableArraySetParams = new sc.MutableArraySetParams(); + params: sc.MutableArraySetParams = new sc.MutableArraySetParams(wasmlib.ScView.nilProxy); } export class ArraySetContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableArraySetParams = new sc.ImmutableArraySetParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableArraySetParams = new sc.ImmutableArraySetParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class MapClearCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMapClear); - params: sc.MutableMapClearParams = new sc.MutableMapClearParams(); + params: sc.MutableMapClearParams = new sc.MutableMapClearParams(wasmlib.ScView.nilProxy); } export class MapClearContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableMapClearParams = new sc.ImmutableMapClearParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); -} - -export class MapCreateCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMapCreate); - params: sc.MutableMapCreateParams = new sc.MutableMapCreateParams(); -} - -export class MapCreateContext { - events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableMapCreateParams = new sc.ImmutableMapCreateParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableMapClearParams = new sc.ImmutableMapClearParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class MapSetCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMapSet); - params: sc.MutableMapSetParams = new sc.MutableMapSetParams(); + params: sc.MutableMapSetParams = new sc.MutableMapSetParams(wasmlib.ScView.nilProxy); } export class MapSetContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableMapSetParams = new sc.ImmutableMapSetParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableMapSetParams = new sc.ImmutableMapSetParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class ParamTypesCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncParamTypes); - params: sc.MutableParamTypesParams = new sc.MutableParamTypesParams(); + params: sc.MutableParamTypesParams = new sc.MutableParamTypesParams(wasmlib.ScView.nilProxy); } export class ParamTypesContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableParamTypesParams = new sc.ImmutableParamTypesParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableParamTypesParams = new sc.ImmutableParamTypesParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class RandomCall { @@ -91,192 +80,191 @@ export class RandomCall { export class RandomContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class TriggerEventCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTriggerEvent); - params: sc.MutableTriggerEventParams = new sc.MutableTriggerEventParams(); + params: sc.MutableTriggerEventParams = new sc.MutableTriggerEventParams(wasmlib.ScView.nilProxy); } export class TriggerEventContext { events: sc.TestWasmLibEvents = new sc.TestWasmLibEvents(); - params: sc.ImmutableTriggerEventParams = new sc.ImmutableTriggerEventParams(); - state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(); + params: sc.ImmutableTriggerEventParams = new sc.ImmutableTriggerEventParams(wasmlib.paramsProxy()); + state: sc.MutableTestWasmLibState = new sc.MutableTestWasmLibState(wasmlib.ScState.proxy()); } export class ArrayLengthCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewArrayLength); - params: sc.MutableArrayLengthParams = new sc.MutableArrayLengthParams(); - results: sc.ImmutableArrayLengthResults = new sc.ImmutableArrayLengthResults(); + params: sc.MutableArrayLengthParams = new sc.MutableArrayLengthParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableArrayLengthResults = new sc.ImmutableArrayLengthResults(wasmlib.ScView.nilProxy); } export class ArrayLengthContext { - params: sc.ImmutableArrayLengthParams = new sc.ImmutableArrayLengthParams(); - results: sc.MutableArrayLengthResults = new sc.MutableArrayLengthResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + params: sc.ImmutableArrayLengthParams = new sc.ImmutableArrayLengthParams(wasmlib.paramsProxy()); + results: sc.MutableArrayLengthResults = new sc.MutableArrayLengthResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class ArrayValueCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewArrayValue); - params: sc.MutableArrayValueParams = new sc.MutableArrayValueParams(); - results: sc.ImmutableArrayValueResults = new sc.ImmutableArrayValueResults(); + params: sc.MutableArrayValueParams = new sc.MutableArrayValueParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableArrayValueResults = new sc.ImmutableArrayValueResults(wasmlib.ScView.nilProxy); } export class ArrayValueContext { - params: sc.ImmutableArrayValueParams = new sc.ImmutableArrayValueParams(); - results: sc.MutableArrayValueResults = new sc.MutableArrayValueResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + params: sc.ImmutableArrayValueParams = new sc.ImmutableArrayValueParams(wasmlib.paramsProxy()); + results: sc.MutableArrayValueResults = new sc.MutableArrayValueResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class BlockRecordCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBlockRecord); - params: sc.MutableBlockRecordParams = new sc.MutableBlockRecordParams(); - results: sc.ImmutableBlockRecordResults = new sc.ImmutableBlockRecordResults(); + params: sc.MutableBlockRecordParams = new sc.MutableBlockRecordParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableBlockRecordResults = new sc.ImmutableBlockRecordResults(wasmlib.ScView.nilProxy); } export class BlockRecordContext { - params: sc.ImmutableBlockRecordParams = new sc.ImmutableBlockRecordParams(); - results: sc.MutableBlockRecordResults = new sc.MutableBlockRecordResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + params: sc.ImmutableBlockRecordParams = new sc.ImmutableBlockRecordParams(wasmlib.paramsProxy()); + results: sc.MutableBlockRecordResults = new sc.MutableBlockRecordResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class BlockRecordsCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBlockRecords); - params: sc.MutableBlockRecordsParams = new sc.MutableBlockRecordsParams(); - results: sc.ImmutableBlockRecordsResults = new sc.ImmutableBlockRecordsResults(); + params: sc.MutableBlockRecordsParams = new sc.MutableBlockRecordsParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableBlockRecordsResults = new sc.ImmutableBlockRecordsResults(wasmlib.ScView.nilProxy); } export class BlockRecordsContext { - params: sc.ImmutableBlockRecordsParams = new sc.ImmutableBlockRecordsParams(); - results: sc.MutableBlockRecordsResults = new sc.MutableBlockRecordsResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + params: sc.ImmutableBlockRecordsParams = new sc.ImmutableBlockRecordsParams(wasmlib.paramsProxy()); + results: sc.MutableBlockRecordsResults = new sc.MutableBlockRecordsResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class GetRandomCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRandom); - results: sc.ImmutableGetRandomResults = new sc.ImmutableGetRandomResults(); + results: sc.ImmutableGetRandomResults = new sc.ImmutableGetRandomResults(wasmlib.ScView.nilProxy); } export class GetRandomContext { - results: sc.MutableGetRandomResults = new sc.MutableGetRandomResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + results: sc.MutableGetRandomResults = new sc.MutableGetRandomResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class IotaBalanceCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewIotaBalance); - results: sc.ImmutableIotaBalanceResults = new sc.ImmutableIotaBalanceResults(); + results: sc.ImmutableIotaBalanceResults = new sc.ImmutableIotaBalanceResults(wasmlib.ScView.nilProxy); } export class IotaBalanceContext { - results: sc.MutableIotaBalanceResults = new sc.MutableIotaBalanceResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + results: sc.MutableIotaBalanceResults = new sc.MutableIotaBalanceResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class MapValueCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewMapValue); - params: sc.MutableMapValueParams = new sc.MutableMapValueParams(); - results: sc.ImmutableMapValueResults = new sc.ImmutableMapValueResults(); + params: sc.MutableMapValueParams = new sc.MutableMapValueParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableMapValueResults = new sc.ImmutableMapValueResults(wasmlib.ScView.nilProxy); } export class MapValueContext { - params: sc.ImmutableMapValueParams = new sc.ImmutableMapValueParams(); - results: sc.MutableMapValueResults = new sc.MutableMapValueResults(); - state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(); + params: sc.ImmutableMapValueParams = new sc.ImmutableMapValueParams(wasmlib.paramsProxy()); + results: sc.MutableMapValueResults = new sc.MutableMapValueResults(wasmlib.ScView.nilProxy); + state: sc.ImmutableTestWasmLibState = new sc.ImmutableTestWasmLibState(wasmlib.ScState.proxy()); } export class ScFuncs { - static arrayClear(ctx: wasmlib.ScFuncCallContext): ArrayClearCall { - let f = new ArrayClearCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static arrayCreate(ctx: wasmlib.ScFuncCallContext): ArrayCreateCall { - let f = new ArrayCreateCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static arraySet(ctx: wasmlib.ScFuncCallContext): ArraySetCall { - let f = new ArraySetCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static mapClear(ctx: wasmlib.ScFuncCallContext): MapClearCall { - let f = new MapClearCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static mapCreate(ctx: wasmlib.ScFuncCallContext): MapCreateCall { - let f = new MapCreateCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static mapSet(ctx: wasmlib.ScFuncCallContext): MapSetCall { - let f = new MapSetCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static paramTypes(ctx: wasmlib.ScFuncCallContext): ParamTypesCall { - let f = new ParamTypesCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static random(ctx: wasmlib.ScFuncCallContext): RandomCall { - return new RandomCall(); - } - - static triggerEvent(ctx: wasmlib.ScFuncCallContext): TriggerEventCall { - let f = new TriggerEventCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static arrayLength(ctx: wasmlib.ScViewCallContext): ArrayLengthCall { - let f = new ArrayLengthCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static arrayValue(ctx: wasmlib.ScViewCallContext): ArrayValueCall { - let f = new ArrayValueCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static blockRecord(ctx: wasmlib.ScViewCallContext): BlockRecordCall { - let f = new BlockRecordCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static blockRecords(ctx: wasmlib.ScViewCallContext): BlockRecordsCall { - let f = new BlockRecordsCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getRandom(ctx: wasmlib.ScViewCallContext): GetRandomCall { - let f = new GetRandomCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static iotaBalance(ctx: wasmlib.ScViewCallContext): IotaBalanceCall { - let f = new IotaBalanceCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static mapValue(ctx: wasmlib.ScViewCallContext): MapValueCall { - let f = new MapValueCall(); - f.func.setPtrs(f.params, f.results); - return f; - } + static arrayAppend(_ctx: wasmlib.ScFuncCallContext): ArrayAppendCall { + const f = new ArrayAppendCall(); + f.params = new sc.MutableArrayAppendParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static arrayClear(_ctx: wasmlib.ScFuncCallContext): ArrayClearCall { + const f = new ArrayClearCall(); + f.params = new sc.MutableArrayClearParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static arraySet(_ctx: wasmlib.ScFuncCallContext): ArraySetCall { + const f = new ArraySetCall(); + f.params = new sc.MutableArraySetParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static mapClear(_ctx: wasmlib.ScFuncCallContext): MapClearCall { + const f = new MapClearCall(); + f.params = new sc.MutableMapClearParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static mapSet(_ctx: wasmlib.ScFuncCallContext): MapSetCall { + const f = new MapSetCall(); + f.params = new sc.MutableMapSetParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static paramTypes(_ctx: wasmlib.ScFuncCallContext): ParamTypesCall { + const f = new ParamTypesCall(); + f.params = new sc.MutableParamTypesParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static random(_ctx: wasmlib.ScFuncCallContext): RandomCall { + return new RandomCall(); + } + + static triggerEvent(_ctx: wasmlib.ScFuncCallContext): TriggerEventCall { + const f = new TriggerEventCall(); + f.params = new sc.MutableTriggerEventParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static arrayLength(_ctx: wasmlib.ScViewCallContext): ArrayLengthCall { + const f = new ArrayLengthCall(); + f.params = new sc.MutableArrayLengthParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableArrayLengthResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static arrayValue(_ctx: wasmlib.ScViewCallContext): ArrayValueCall { + const f = new ArrayValueCall(); + f.params = new sc.MutableArrayValueParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableArrayValueResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static blockRecord(_ctx: wasmlib.ScViewCallContext): BlockRecordCall { + const f = new BlockRecordCall(); + f.params = new sc.MutableBlockRecordParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableBlockRecordResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static blockRecords(_ctx: wasmlib.ScViewCallContext): BlockRecordsCall { + const f = new BlockRecordsCall(); + f.params = new sc.MutableBlockRecordsParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableBlockRecordsResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getRandom(_ctx: wasmlib.ScViewCallContext): GetRandomCall { + const f = new GetRandomCall(); + f.results = new sc.ImmutableGetRandomResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static iotaBalance(_ctx: wasmlib.ScViewCallContext): IotaBalanceCall { + const f = new IotaBalanceCall(); + f.results = new sc.ImmutableIotaBalanceResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static mapValue(_ctx: wasmlib.ScViewCallContext): MapValueCall { + const f = new MapValueCall(); + f.params = new sc.MutableMapValueParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableMapValueResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/events.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/events.ts index 8fd0c6416b..9ee07eebf9 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/events.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/events.ts @@ -6,13 +6,14 @@ // Change the json schema instead import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class TestWasmLibEvents { - test(address: wasmlib.ScAddress, name: string): void { - new wasmlib.EventEncoder("testwasmlib.test"). - address(address). - string(name). - emit(); + test(address: wasmtypes.ScAddress, name: string): void { + const evt = new wasmlib.EventEncoder("testwasmlib.test"); + evt.encode(wasmtypes.addressToString(address)); + evt.encode(wasmtypes.stringToString(name)); + evt.emit(); } } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/index.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/index.ts index 502314c2d3..e647be41d3 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/index.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/index.ts @@ -10,7 +10,6 @@ export * from "./testwasmlib"; export * from "./consts"; export * from "./contract"; export * from "./events"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./results"; diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/keys.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/keys.ts deleted file mode 100644 index 92517c4880..0000000000 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/keys.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamAddress = 0; -export const IdxParamAgentID = 1; -export const IdxParamBlockIndex = 2; -export const IdxParamBool = 3; -export const IdxParamBytes = 4; -export const IdxParamChainID = 5; -export const IdxParamColor = 6; -export const IdxParamHash = 7; -export const IdxParamHname = 8; -export const IdxParamIndex = 9; -export const IdxParamInt16 = 10; -export const IdxParamInt32 = 11; -export const IdxParamInt64 = 12; -export const IdxParamInt8 = 13; -export const IdxParamKey = 14; -export const IdxParamName = 15; -export const IdxParamParam = 16; -export const IdxParamRecordIndex = 17; -export const IdxParamRequestID = 18; -export const IdxParamString = 19; -export const IdxParamUint16 = 20; -export const IdxParamUint32 = 21; -export const IdxParamUint64 = 22; -export const IdxParamUint8 = 23; -export const IdxParamValue = 24; - -export const IdxResultCount = 25; -export const IdxResultIotas = 26; -export const IdxResultLength = 27; -export const IdxResultRandom = 28; -export const IdxResultRecord = 29; -export const IdxResultValue = 30; - -export const IdxStateArrays = 31; -export const IdxStateMaps = 32; -export const IdxStateRandom = 33; - -export let keyMap: string[] = [ - sc.ParamAddress, - sc.ParamAgentID, - sc.ParamBlockIndex, - sc.ParamBool, - sc.ParamBytes, - sc.ParamChainID, - sc.ParamColor, - sc.ParamHash, - sc.ParamHname, - sc.ParamIndex, - sc.ParamInt16, - sc.ParamInt32, - sc.ParamInt64, - sc.ParamInt8, - sc.ParamKey, - sc.ParamName, - sc.ParamParam, - sc.ParamRecordIndex, - sc.ParamRequestID, - sc.ParamString, - sc.ParamUint16, - sc.ParamUint32, - sc.ParamUint64, - sc.ParamUint8, - sc.ParamValue, - sc.ResultCount, - sc.ResultIotas, - sc.ResultLength, - sc.ResultRandom, - sc.ResultRecord, - sc.ResultValue, - sc.StateArrays, - sc.StateMaps, - sc.StateRandom, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/lib.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/lib.ts index 10066f63d0..014f7adcb2 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/lib.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/lib.ts @@ -8,59 +8,73 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncArrayAppend, + sc.FuncArrayClear, + sc.FuncArraySet, + sc.FuncMapClear, + sc.FuncMapSet, + sc.FuncParamTypes, + sc.FuncRandom, + sc.FuncTriggerEvent, + sc.ViewArrayLength, + sc.ViewArrayValue, + sc.ViewBlockRecord, + sc.ViewBlockRecords, + sc.ViewGetRandom, + sc.ViewIotaBalance, + sc.ViewMapValue, + ], + funcs: [ + funcArrayAppendThunk, + funcArrayClearThunk, + funcArraySetThunk, + funcMapClearThunk, + funcMapSetThunk, + funcParamTypesThunk, + funcRandomThunk, + funcTriggerEventThunk, + ], + views: [ + viewArrayLengthThunk, + viewArrayValueThunk, + viewBlockRecordThunk, + viewBlockRecordsThunk, + viewGetRandomThunk, + viewIotaBalanceThunk, + viewMapValueThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncArrayClear, funcArrayClearThunk); - exports.addFunc(sc.FuncArrayCreate, funcArrayCreateThunk); - exports.addFunc(sc.FuncArraySet, funcArraySetThunk); - exports.addFunc(sc.FuncMapClear, funcMapClearThunk); - exports.addFunc(sc.FuncMapCreate, funcMapCreateThunk); - exports.addFunc(sc.FuncMapSet, funcMapSetThunk); - exports.addFunc(sc.FuncParamTypes, funcParamTypesThunk); - exports.addFunc(sc.FuncRandom, funcRandomThunk); - exports.addFunc(sc.FuncTriggerEvent, funcTriggerEventThunk); - exports.addView(sc.ViewArrayLength, viewArrayLengthThunk); - exports.addView(sc.ViewArrayValue, viewArrayValueThunk); - exports.addView(sc.ViewBlockRecord, viewBlockRecordThunk); - exports.addView(sc.ViewBlockRecords, viewBlockRecordsThunk); - exports.addView(sc.ViewGetRandom, viewGetRandomThunk); - exports.addView(sc.ViewIotaBalance, viewIotaBalanceThunk); - exports.addView(sc.ViewMapValue, viewMapValueThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); +} + +function funcArrayAppendThunk(ctx: wasmlib.ScFuncContext): void { + ctx.log("testwasmlib.funcArrayAppend"); + let f = new sc.ArrayAppendContext(); + ctx.require(f.params.name().exists(), "missing mandatory name"); + ctx.require(f.params.value().exists(), "missing mandatory value"); + sc.funcArrayAppend(ctx, f); + ctx.log("testwasmlib.funcArrayAppend ok"); } function funcArrayClearThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcArrayClear"); let f = new sc.ArrayClearContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.name().exists(), "missing mandatory name"); sc.funcArrayClear(ctx, f); ctx.log("testwasmlib.funcArrayClear ok"); } -function funcArrayCreateThunk(ctx: wasmlib.ScFuncContext): void { - ctx.log("testwasmlib.funcArrayCreate"); - let f = new sc.ArrayCreateContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; - ctx.require(f.params.name().exists(), "missing mandatory name"); - sc.funcArrayCreate(ctx, f); - ctx.log("testwasmlib.funcArrayCreate ok"); -} - function funcArraySetThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcArraySet"); let f = new sc.ArraySetContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.index().exists(), "missing mandatory index"); ctx.require(f.params.name().exists(), "missing mandatory name"); ctx.require(f.params.value().exists(), "missing mandatory value"); @@ -71,28 +85,14 @@ function funcArraySetThunk(ctx: wasmlib.ScFuncContext): void { function funcMapClearThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcMapClear"); let f = new sc.MapClearContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.name().exists(), "missing mandatory name"); sc.funcMapClear(ctx, f); ctx.log("testwasmlib.funcMapClear ok"); } -function funcMapCreateThunk(ctx: wasmlib.ScFuncContext): void { - ctx.log("testwasmlib.funcMapCreate"); - let f = new sc.MapCreateContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; - ctx.require(f.params.name().exists(), "missing mandatory name"); - sc.funcMapCreate(ctx, f); - ctx.log("testwasmlib.funcMapCreate ok"); -} - function funcMapSetThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcMapSet"); let f = new sc.MapSetContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.key().exists(), "missing mandatory key"); ctx.require(f.params.name().exists(), "missing mandatory name"); ctx.require(f.params.value().exists(), "missing mandatory value"); @@ -103,8 +103,6 @@ function funcMapSetThunk(ctx: wasmlib.ScFuncContext): void { function funcParamTypesThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcParamTypes"); let f = new sc.ParamTypesContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcParamTypes(ctx, f); ctx.log("testwasmlib.funcParamTypes ok"); } @@ -112,7 +110,6 @@ function funcParamTypesThunk(ctx: wasmlib.ScFuncContext): void { function funcRandomThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcRandom"); let f = new sc.RandomContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcRandom(ctx, f); ctx.log("testwasmlib.funcRandom ok"); } @@ -120,8 +117,6 @@ function funcRandomThunk(ctx: wasmlib.ScFuncContext): void { function funcTriggerEventThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("testwasmlib.funcTriggerEvent"); let f = new sc.TriggerEventContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.address().exists(), "missing mandatory address"); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.funcTriggerEvent(ctx, f); @@ -131,75 +126,77 @@ function funcTriggerEventThunk(ctx: wasmlib.ScFuncContext): void { function viewArrayLengthThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewArrayLength"); let f = new sc.ArrayLengthContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableArrayLengthResults(results.asProxy()); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.viewArrayLength(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewArrayLength ok"); } function viewArrayValueThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewArrayValue"); let f = new sc.ArrayValueContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableArrayValueResults(results.asProxy()); ctx.require(f.params.index().exists(), "missing mandatory index"); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.viewArrayValue(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewArrayValue ok"); } function viewBlockRecordThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewBlockRecord"); let f = new sc.BlockRecordContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableBlockRecordResults(results.asProxy()); ctx.require(f.params.blockIndex().exists(), "missing mandatory blockIndex"); ctx.require(f.params.recordIndex().exists(), "missing mandatory recordIndex"); sc.viewBlockRecord(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewBlockRecord ok"); } function viewBlockRecordsThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewBlockRecords"); let f = new sc.BlockRecordsContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableBlockRecordsResults(results.asProxy()); ctx.require(f.params.blockIndex().exists(), "missing mandatory blockIndex"); sc.viewBlockRecords(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewBlockRecords ok"); } function viewGetRandomThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewGetRandom"); let f = new sc.GetRandomContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetRandomResults(results.asProxy()); sc.viewGetRandom(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewGetRandom ok"); } function viewIotaBalanceThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewIotaBalance"); let f = new sc.IotaBalanceContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableIotaBalanceResults(results.asProxy()); sc.viewIotaBalance(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewIotaBalance ok"); } function viewMapValueThunk(ctx: wasmlib.ScViewContext): void { ctx.log("testwasmlib.viewMapValue"); let f = new sc.MapValueContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableMapValueResults(results.asProxy()); ctx.require(f.params.key().exists(), "missing mandatory key"); ctx.require(f.params.name().exists(), "missing mandatory name"); sc.viewMapValue(ctx, f); + ctx.results(results); ctx.log("testwasmlib.viewMapValue ok"); } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/params.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/params.ts index cacc72ca4d..d0c3ee7ea4 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/params.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/params.ts @@ -5,397 +5,383 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableArrayClearParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class ImmutableArrayAppendParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } -} -export class MutableArrayClearParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + value(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamValue)); } } -export class ImmutableArrayCreateParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class MutableArrayAppendParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } -} -export class MutableArrayCreateParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + value(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamValue)); } } -export class ImmutableArraySetParams extends wasmlib.ScMapID { - index(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamIndex)); - } - - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class ImmutableArrayClearParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } +} - value(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamValue)); +export class MutableArrayClearParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class MutableArraySetParams extends wasmlib.ScMapID { - index(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamIndex)); +export class ImmutableArraySetParams extends wasmtypes.ScProxy { + index(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamIndex)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } - value(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamValue)); + value(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamValue)); } } -export class ImmutableMapClearParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class MutableArraySetParams extends wasmtypes.ScProxy { + index(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamIndex)); } -} -export class MutableMapClearParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); + } + + value(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamValue)); } } -export class ImmutableMapCreateParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class ImmutableMapClearParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableMapCreateParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class MutableMapClearParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableMapSetParams extends wasmlib.ScMapID { - key(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamKey)); +export class ImmutableMapSetParams extends wasmtypes.ScProxy { + key(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamKey)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } - value(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamValue)); + value(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamValue)); } } -export class MutableMapSetParams extends wasmlib.ScMapID { - key(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamKey)); +export class MutableMapSetParams extends wasmtypes.ScProxy { + key(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamKey)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } - value(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamValue)); + value(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamValue)); } } -export class MapStringToImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToImmutableBytes extends wasmtypes.ScProxy { - getBytes(key: string): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, wasmlib.Key32.fromString(key)); - } + getBytes(key: string): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class ImmutableParamTypesParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutableParamTypesParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); } - bool(): wasmlib.ScImmutableBool { - return new wasmlib.ScImmutableBool(this.mapID, wasmlib.Key32.fromString(sc.ParamBool)); + bool(): wasmtypes.ScImmutableBool { + return new wasmtypes.ScImmutableBool(this.proxy.root(sc.ParamBool)); } - bytes(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ParamBytes)); + bytes(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ParamBytes)); } - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ParamChainID)); } - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); } - int16(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamInt16)); + int16(): wasmtypes.ScImmutableInt16 { + return new wasmtypes.ScImmutableInt16(this.proxy.root(sc.ParamInt16)); } - int32(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamInt32)); + int32(): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.root(sc.ParamInt32)); } - int64(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamInt64)); } - int8(): wasmlib.ScImmutableInt8 { - return new wasmlib.ScImmutableInt8(this.mapID, wasmlib.Key32.fromString(sc.ParamInt8)); + int8(): wasmtypes.ScImmutableInt8 { + return new wasmtypes.ScImmutableInt8(this.proxy.root(sc.ParamInt8)); } - param(): sc.MapStringToImmutableBytes { - return new sc.MapStringToImmutableBytes(this.mapID); + param(): sc.MapStringToImmutableBytes { + return new sc.MapStringToImmutableBytes(this.proxy); } - requestID(): wasmlib.ScImmutableRequestID { - return new wasmlib.ScImmutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); + requestID(): wasmtypes.ScImmutableRequestID { + return new wasmtypes.ScImmutableRequestID(this.proxy.root(sc.ParamRequestID)); } - string(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamString)); } - uint16(): wasmlib.ScImmutableUint16 { - return new wasmlib.ScImmutableUint16(this.mapID, wasmlib.Key32.fromString(sc.ParamUint16)); + uint16(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.ParamUint16)); } - uint32(): wasmlib.ScImmutableUint32 { - return new wasmlib.ScImmutableUint32(this.mapID, wasmlib.Key32.fromString(sc.ParamUint32)); + uint32(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamUint32)); } - uint64(): wasmlib.ScImmutableUint64 { - return new wasmlib.ScImmutableUint64(this.mapID, wasmlib.Key32.fromString(sc.ParamUint64)); + uint64(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ParamUint64)); } - uint8(): wasmlib.ScImmutableUint8 { - return new wasmlib.ScImmutableUint8(this.mapID, wasmlib.Key32.fromString(sc.ParamUint8)); + uint8(): wasmtypes.ScImmutableUint8 { + return new wasmtypes.ScImmutableUint8(this.proxy.root(sc.ParamUint8)); } } -export class MapStringToMutableBytes { - objID: i32; +export class MapStringToMutableBytes extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getBytes(key: string): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, wasmlib.Key32.fromString(key)); - } + getBytes(key: string): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MutableParamTypesParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutableParamTypesParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); } - bool(): wasmlib.ScMutableBool { - return new wasmlib.ScMutableBool(this.mapID, wasmlib.Key32.fromString(sc.ParamBool)); + bool(): wasmtypes.ScMutableBool { + return new wasmtypes.ScMutableBool(this.proxy.root(sc.ParamBool)); } - bytes(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ParamBytes)); + bytes(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ParamBytes)); } - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainID)); + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ParamChainID)); } - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamHash)); } - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); } - int16(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamInt16)); + int16(): wasmtypes.ScMutableInt16 { + return new wasmtypes.ScMutableInt16(this.proxy.root(sc.ParamInt16)); } - int32(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamInt32)); + int32(): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.root(sc.ParamInt32)); } - int64(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamInt64)); + int64(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamInt64)); } - int8(): wasmlib.ScMutableInt8 { - return new wasmlib.ScMutableInt8(this.mapID, wasmlib.Key32.fromString(sc.ParamInt8)); + int8(): wasmtypes.ScMutableInt8 { + return new wasmtypes.ScMutableInt8(this.proxy.root(sc.ParamInt8)); } - param(): sc.MapStringToMutableBytes { - return new sc.MapStringToMutableBytes(this.mapID); + param(): sc.MapStringToMutableBytes { + return new sc.MapStringToMutableBytes(this.proxy); } - requestID(): wasmlib.ScMutableRequestID { - return new wasmlib.ScMutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); + requestID(): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.root(sc.ParamRequestID)); } - string(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamString)); + string(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamString)); } - uint16(): wasmlib.ScMutableUint16 { - return new wasmlib.ScMutableUint16(this.mapID, wasmlib.Key32.fromString(sc.ParamUint16)); + uint16(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.ParamUint16)); } - uint32(): wasmlib.ScMutableUint32 { - return new wasmlib.ScMutableUint32(this.mapID, wasmlib.Key32.fromString(sc.ParamUint32)); + uint32(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamUint32)); } - uint64(): wasmlib.ScMutableUint64 { - return new wasmlib.ScMutableUint64(this.mapID, wasmlib.Key32.fromString(sc.ParamUint64)); + uint64(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ParamUint64)); } - uint8(): wasmlib.ScMutableUint8 { - return new wasmlib.ScMutableUint8(this.mapID, wasmlib.Key32.fromString(sc.ParamUint8)); + uint8(): wasmtypes.ScMutableUint8 { + return new wasmtypes.ScMutableUint8(this.proxy.root(sc.ParamUint8)); } } -export class ImmutableTriggerEventParams extends wasmlib.ScMapID { - address(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class ImmutableTriggerEventParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamAddress)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableTriggerEventParams extends wasmlib.ScMapID { - address(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamAddress)); +export class MutableTriggerEventParams extends wasmtypes.ScProxy { + address(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamAddress)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableArrayLengthParams extends wasmlib.ScMapID { - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class ImmutableArrayLengthParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableArrayLengthParams extends wasmlib.ScMapID { - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); +export class MutableArrayLengthParams extends wasmtypes.ScProxy { + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableArrayValueParams extends wasmlib.ScMapID { - index(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamIndex)); +export class ImmutableArrayValueParams extends wasmtypes.ScProxy { + index(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamIndex)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableArrayValueParams extends wasmlib.ScMapID { - index(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamIndex)); +export class MutableArrayValueParams extends wasmtypes.ScProxy { + index(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamIndex)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } -export class ImmutableBlockRecordParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); +export class ImmutableBlockRecordParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); } - recordIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamRecordIndex)); + recordIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamRecordIndex)); } } -export class MutableBlockRecordParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); +export class MutableBlockRecordParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); } - recordIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamRecordIndex)); + recordIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamRecordIndex)); } } -export class ImmutableBlockRecordsParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); +export class ImmutableBlockRecordsParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); } } -export class MutableBlockRecordsParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); +export class MutableBlockRecordsParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); } } -export class ImmutableMapValueParams extends wasmlib.ScMapID { - key(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamKey)); +export class ImmutableMapValueParams extends wasmtypes.ScProxy { + key(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamKey)); } - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); } } -export class MutableMapValueParams extends wasmlib.ScMapID { - key(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamKey)); +export class MutableMapValueParams extends wasmtypes.ScProxy { + key(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamKey)); } - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); } } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/results.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/results.ts index 476649ffcd..9d4de99d94 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/results.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/results.ts @@ -5,89 +5,89 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableArrayLengthResults extends wasmlib.ScMapID { - length(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultLength)); +export class ImmutableArrayLengthResults extends wasmtypes.ScProxy { + length(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultLength)); } } -export class MutableArrayLengthResults extends wasmlib.ScMapID { - length(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultLength)); +export class MutableArrayLengthResults extends wasmtypes.ScProxy { + length(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultLength)); } } -export class ImmutableArrayValueResults extends wasmlib.ScMapID { - value(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultValue)); +export class ImmutableArrayValueResults extends wasmtypes.ScProxy { + value(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultValue)); } } -export class MutableArrayValueResults extends wasmlib.ScMapID { - value(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultValue)); +export class MutableArrayValueResults extends wasmtypes.ScProxy { + value(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultValue)); } } -export class ImmutableBlockRecordResults extends wasmlib.ScMapID { - record(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultRecord)); +export class ImmutableBlockRecordResults extends wasmtypes.ScProxy { + record(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultRecord)); } } -export class MutableBlockRecordResults extends wasmlib.ScMapID { - record(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultRecord)); +export class MutableBlockRecordResults extends wasmtypes.ScProxy { + record(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultRecord)); } } -export class ImmutableBlockRecordsResults extends wasmlib.ScMapID { - count(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultCount)); +export class ImmutableBlockRecordsResults extends wasmtypes.ScProxy { + count(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultCount)); } } -export class MutableBlockRecordsResults extends wasmlib.ScMapID { - count(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultCount)); +export class MutableBlockRecordsResults extends wasmtypes.ScProxy { + count(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultCount)); } } -export class ImmutableGetRandomResults extends wasmlib.ScMapID { - random(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultRandom)); +export class ImmutableGetRandomResults extends wasmtypes.ScProxy { + random(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultRandom)); } } -export class MutableGetRandomResults extends wasmlib.ScMapID { - random(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultRandom)); +export class MutableGetRandomResults extends wasmtypes.ScProxy { + random(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultRandom)); } } -export class ImmutableIotaBalanceResults extends wasmlib.ScMapID { - iotas(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIotas)); +export class ImmutableIotaBalanceResults extends wasmtypes.ScProxy { + iotas(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultIotas)); } } -export class MutableIotaBalanceResults extends wasmlib.ScMapID { - iotas(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultIotas)); +export class MutableIotaBalanceResults extends wasmtypes.ScProxy { + iotas(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultIotas)); } } -export class ImmutableMapValueResults extends wasmlib.ScMapID { - value(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultValue)); +export class ImmutableMapValueResults extends wasmtypes.ScProxy { + value(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultValue)); } } -export class MutableMapValueResults extends wasmlib.ScMapID { - value(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultValue)); +export class MutableMapValueResults extends wasmtypes.ScProxy { + value(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultValue)); } } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/state.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/state.ts index bdc4b782a3..0104a3174b 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/state.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/state.ts @@ -5,103 +5,73 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class MapStringToImmutableStringArray { - objID: i32; +export class MapStringToImmutableStringArray extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getStringArray(key: string): sc.ImmutableStringArray { - let subID = wasmlib.getObjectID(this.objID, wasmlib.Key32.fromString(key), wasmlib.TYPE_ARRAY|wasmlib.TYPE_STRING); - return new sc.ImmutableStringArray(subID); - } + getStringArray(key: string): sc.ImmutableStringArray { + return new sc.ImmutableStringArray(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MapStringToImmutableStringMap { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToImmutableStringMap extends wasmtypes.ScProxy { - getStringMap(key: string): sc.ImmutableStringMap { - let subID = wasmlib.getObjectID(this.objID, wasmlib.Key32.fromString(key), wasmlib.TYPE_MAP); - return new sc.ImmutableStringMap(subID); - } + getStringMap(key: string): sc.ImmutableStringMap { + return new sc.ImmutableStringMap(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class ImmutableTestWasmLibState extends wasmlib.ScMapID { - arrays(): sc.MapStringToImmutableStringArray { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateArrays), wasmlib.TYPE_MAP); - return new sc.MapStringToImmutableStringArray(mapID); +export class ImmutableTestWasmLibState extends wasmtypes.ScProxy { + arrays(): sc.MapStringToImmutableStringArray { + return new sc.MapStringToImmutableStringArray(this.proxy.root(sc.StateArrays)); } - maps(): sc.MapStringToImmutableStringMap { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMaps), wasmlib.TYPE_MAP); - return new sc.MapStringToImmutableStringMap(mapID); + maps(): sc.MapStringToImmutableStringMap { + return new sc.MapStringToImmutableStringMap(this.proxy.root(sc.StateMaps)); } - random(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateRandom)); + random(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateRandom)); } } -export class MapStringToMutableStringArray { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToMutableStringArray extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getStringArray(key: string): sc.MutableStringArray { - let subID = wasmlib.getObjectID(this.objID, wasmlib.Key32.fromString(key), wasmlib.TYPE_ARRAY|wasmlib.TYPE_STRING); - return new sc.MutableStringArray(subID); - } + getStringArray(key: string): sc.MutableStringArray { + return new sc.MutableStringArray(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MapStringToMutableStringMap { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToMutableStringMap extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getStringMap(key: string): sc.MutableStringMap { - let subID = wasmlib.getObjectID(this.objID, wasmlib.Key32.fromString(key), wasmlib.TYPE_MAP); - return new sc.MutableStringMap(subID); - } + getStringMap(key: string): sc.MutableStringMap { + return new sc.MutableStringMap(this.proxy.key(wasmtypes.stringToBytes(key))); + } } -export class MutableTestWasmLibState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableTestWasmLibState { - const imm = new sc.ImmutableTestWasmLibState(); - imm.mapID = this.mapID; - return imm; +export class MutableTestWasmLibState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableTestWasmLibState { + return new sc.ImmutableTestWasmLibState(this.proxy); } - arrays(): sc.MapStringToMutableStringArray { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateArrays), wasmlib.TYPE_MAP); - return new sc.MapStringToMutableStringArray(mapID); + arrays(): sc.MapStringToMutableStringArray { + return new sc.MapStringToMutableStringArray(this.proxy.root(sc.StateArrays)); } - maps(): sc.MapStringToMutableStringMap { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateMaps), wasmlib.TYPE_MAP); - return new sc.MapStringToMutableStringMap(mapID); + maps(): sc.MapStringToMutableStringMap { + return new sc.MapStringToMutableStringMap(this.proxy.root(sc.StateMaps)); } - random(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateRandom)); + random(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateRandom)); } } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/structs.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/structs.ts deleted file mode 100644 index 943ee88121..0000000000 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/structs.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; - -export class Location { - x : i32 = 0; - y : i32 = 0; - - static fromBytes(bytes: u8[]): Location { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Location(); - data.x = decode.int32(); - data.y = decode.int32(); - decode.close(); - return data; - } - - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - int32(this.x). - int32(this.y). - data(); - } -} - -export class ImmutableLocation { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } - - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Location { - return Location.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } -} - -export class MutableLocation { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } - - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - setValue(value: Location): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } - - value(): Location { - return Location.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } -} diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/testwasmlib.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/testwasmlib.ts index c92f97dba5..41eb29297a 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/testwasmlib.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/testwasmlib.ts @@ -2,16 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmlib from "wasmlib" +import * as wasmtypes from "wasmlib/wasmtypes"; import * as coreblocklog from "wasmlib/coreblocklog" import * as sc from "./index"; -export function funcArrayClear(ctx: wasmlib.ScFuncContext, f: sc.ArrayClearContext): void { +export function funcArrayAppend(ctx: wasmlib.ScFuncContext, f: sc.ArrayAppendContext): void { let name = f.params.name().value(); let array = f.state.arrays().getStringArray(name); - array.clear(); + let value = f.params.value().value(); + array.appendString().setValue(value); } -export function funcArrayCreate(ctx: wasmlib.ScFuncContext, f: sc.ArrayCreateContext): void { +export function funcArrayClear(ctx: wasmlib.ScFuncContext, f: sc.ArrayClearContext): void { let name = f.params.name().value(); let array = f.state.arrays().getStringArray(name); array.clear(); @@ -25,6 +27,20 @@ export function funcArraySet(ctx: wasmlib.ScFuncContext, f: sc.ArraySetContext): array.getString(index).setValue(value); } +export function funcMapClear(ctx: wasmlib.ScFuncContext, f: sc.MapClearContext): void { + let name = f.params.name().value(); + let myMap = f.state.maps().getStringMap(name); + myMap.clear(); +} + +export function funcMapSet(ctx: wasmlib.ScFuncContext, f: sc.MapSetContext): void { + let name = f.params.name().value(); + let myMap = f.state.maps().getStringMap(name); + let key = f.params.key().value(); + let value = f.params.value().value(); + myMap.getString(key).setValue(value); +} + export function funcParamTypes(ctx: wasmlib.ScFuncContext, f: sc.ParamTypesContext): void { if (f.params.address().exists()) { ctx.require(f.params.address().value().equals(ctx.accountID().address()), "mismatch: Address"); @@ -36,18 +52,18 @@ export function funcParamTypes(ctx: wasmlib.ScFuncContext, f: sc.ParamTypesConte ctx.require(f.params.bool().value(), "mismatch: Bool"); } if (f.params.bytes().exists()) { - let byteData = wasmlib.Convert.fromString("these are bytes"); - ctx.require(wasmlib.Convert.equals(f.params.bytes().value(), byteData), "mismatch: Bytes"); + const byteData = wasmtypes.stringToBytes("these are bytes"); + ctx.require(wasmtypes.bytesCompare(f.params.bytes().value(), byteData) == 0, "mismatch: Bytes"); } if (f.params.chainID().exists()) { ctx.require(f.params.chainID().value().equals(ctx.chainID()), "mismatch: ChainID"); } if (f.params.color().exists()) { - let color = wasmlib.ScColor.fromBytes(wasmlib.Convert.fromString("RedGreenBlueYellowCyanBlackWhite")); + const color = wasmlib.colorFromBytes(wasmtypes.stringToBytes("RedGreenBlueYellowCyanBlackWhite")); ctx.require(f.params.color().value().equals(color), "mismatch: Color"); } if (f.params.hash().exists()) { - let hash = wasmlib.ScHash.fromBytes(wasmlib.Convert.fromString("0123456789abcdeffedcba9876543210")); + const hash = wasmtypes.hashFromBytes(wasmtypes.stringToBytes("0123456789abcdeffedcba9876543210")); ctx.require(f.params.hash().value().equals(hash), "mismatch: Hash"); } if (f.params.hname().exists()) { @@ -66,7 +82,7 @@ export function funcParamTypes(ctx: wasmlib.ScFuncContext, f: sc.ParamTypesConte ctx.require(f.params.int64().value() == -1234567890123456789, "mismatch: Int64"); } if (f.params.requestID().exists()) { - let requestId = wasmlib.ScRequestID.fromBytes(wasmlib.Convert.fromString("abcdefghijklmnopqrstuvwxyz123456\x00\x00")); + const requestId = wasmtypes.requestIDFromBytes(wasmtypes.stringToBytes("abcdefghijklmnopqrstuvwxyz123456\x00\x00")); ctx.require(f.params.requestID().value().equals(requestId), "mismatch: RequestID"); } if (f.params.string().exists()) { @@ -86,6 +102,14 @@ export function funcParamTypes(ctx: wasmlib.ScFuncContext, f: sc.ParamTypesConte } } +export function funcRandom(ctx: wasmlib.ScFuncContext, f: sc.RandomContext): void { + f.state.random().setValue(ctx.random(1000)); +} + +export function funcTriggerEvent(ctx: wasmlib.ScFuncContext, f: sc.TriggerEventContext): void { + f.events.test(f.params.address().value(), f.params.name().value()); +} + export function viewArrayLength(ctx: wasmlib.ScViewContext, f: sc.ArrayLengthContext): void { let name = f.params.name().value(); let array = f.state.arrays().getStringArray(name); @@ -106,8 +130,17 @@ export function viewBlockRecord(ctx: wasmlib.ScViewContext, f: sc.BlockRecordCon records.params.blockIndex().setValue(f.params.blockIndex().value()); records.func.call(); let recordIndex = f.params.recordIndex().value(); - ctx.require(recordIndex < records.results.requestRecord().length(), "invalid recordIndex"); - f.results.record().setValue(records.results.requestRecord().getBytes(recordIndex).value()); + ctx.log("index: " + recordIndex.toString()); + recordIndex = f.params.recordIndex().value(); + ctx.log("index: " + recordIndex.toString()); + const requestRecord = records.results.requestRecord(); + const length = requestRecord.length(); + ctx.log("length: " + length.toString()); + const length2 = requestRecord.length(); + ctx.log("length2: " + length2.toString()); + ctx.require(recordIndex < length, "invalid recordIndex"); + const buf = requestRecord.getBytes(recordIndex).value(); + f.results.record().setValue(buf); } export function viewBlockRecords(ctx: wasmlib.ScViewContext, f: sc.BlockRecordsContext): void { @@ -117,30 +150,18 @@ export function viewBlockRecords(ctx: wasmlib.ScViewContext, f: sc.BlockRecordsC f.results.count().setValue(records.results.requestRecord().length()); } -export function viewIotaBalance(ctx: wasmlib.ScViewContext, f: sc.IotaBalanceContext): void { - f.results.iotas().setValue(ctx.balances().balance(wasmlib.ScColor.IOTA)); -} - -export function funcRandom(ctx: wasmlib.ScFuncContext, f: sc.RandomContext): void { - f.state.random().setValue(ctx.random(1000)); -} - export function viewGetRandom(ctx: wasmlib.ScViewContext, f: sc.GetRandomContext): void { f.results.random().setValue(f.state.random().value()); } -export function funcTriggerEvent(ctx: wasmlib.ScFuncContext, f: sc.TriggerEventContext): void { - f.events.test(f.params.address().value(), f.params.name().value()); -} - -export function funcMapClear(ctx: wasmlib.ScFuncContext, f: sc.MapClearContext): void { -} - -export function funcMapCreate(ctx: wasmlib.ScFuncContext, f: sc.MapCreateContext): void { -} - -export function funcMapSet(ctx: wasmlib.ScFuncContext, f: sc.MapSetContext): void { +export function viewIotaBalance(ctx: wasmlib.ScViewContext, f: sc.IotaBalanceContext): void { + f.results.iotas().setValue(ctx.balances().balance(wasmtypes.IOTA)); } export function viewMapValue(ctx: wasmlib.ScViewContext, f: sc.MapValueContext): void { + let name = f.params.name().value(); + let myMap = f.state.maps().getStringMap(name); + let key = f.params.key().value(); + let value = myMap.getString(key).value(); + f.results.value().setValue(value); } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlib/typedefs.ts b/contracts/wasm/testwasmlib/ts/testwasmlib/typedefs.ts index a38bec20bd..fd526848e1 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlib/typedefs.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlib/typedefs.ts @@ -5,81 +5,65 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableString { - objID: i32; +export class ArrayOfImmutableString extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + length(): u32 { + return this.proxy.length(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getString(index: i32): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.objID, new wasmlib.Key32(index)); - } + getString(index: u32): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.index(index)); + } } export class ImmutableStringArray extends ArrayOfImmutableString { -}; +} -export class ArrayOfMutableString { - objID: i32; +export class ArrayOfMutableString extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendString(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getString(index: i32): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.objID, new wasmlib.Key32(index)); - } + getString(index: u32): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.index(index)); + } } export class MutableStringArray extends ArrayOfMutableString { -}; - -export class MapStringToImmutableString { - objID: i32; +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToImmutableString extends wasmtypes.ScProxy { - getString(key: string): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.objID, wasmlib.Key32.fromString(key)); - } + getString(key: string): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.key(wasmtypes.stringToBytes(key))); + } } export class ImmutableStringMap extends MapStringToImmutableString { -}; - -export class MapStringToMutableString { - objID: i32; +} - constructor(objID: i32) { - this.objID = objID; - } +export class MapStringToMutableString extends wasmtypes.ScProxy { - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getString(key: string): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.objID, wasmlib.Key32.fromString(key)); - } + getString(key: string): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.key(wasmtypes.stringToBytes(key))); + } } export class MutableStringMap extends MapStringToMutableString { -}; +} diff --git a/contracts/wasm/testwasmlib/ts/testwasmlibclient/events.ts b/contracts/wasm/testwasmlib/ts/testwasmlibclient/events.ts index 6d066c0cf0..1fce46bcb8 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlibclient/events.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlibclient/events.ts @@ -6,18 +6,34 @@ // Change the json schema instead import * as wasmclient from "wasmclient" -import * as app from "./testwasmlib" -export const eventHandlers: wasmclient.EventHandlers = new Map([ - ["testwasmlib.test", (msg: string[]) => app.onTestWasmLibTest(new EventTest(msg))], +const testWasmLibHandlers = new Map void>([ + ["testwasmlib.test", (evt: TestWasmLibEvents, msg: string[]) => evt.test(new EventTest(msg))], ]); +export class TestWasmLibEvents implements wasmclient.IEventHandler { +/* eslint-disable @typescript-eslint/no-empty-function */ + test: (evt: EventTest) => void = () => {}; +/* eslint-enable @typescript-eslint/no-empty-function */ + + public callHandler(topic: string, params: string[]): void { + const handler = testWasmLibHandlers.get(topic); + if (handler) { + handler(this, params); + } + } + + public onTestWasmLibTest(handler: (evt: EventTest) => void): void { + this.test = handler; + } +} + export class EventTest extends wasmclient.Event { public readonly address: wasmclient.Address; public readonly name: wasmclient.String; public constructor(msg: string[]) { - super(msg) + super(msg); this.address = this.nextAddress(); this.name = this.nextString(); } diff --git a/contracts/wasm/testwasmlib/ts/testwasmlibclient/index.ts b/contracts/wasm/testwasmlib/ts/testwasmlibclient/index.ts index f3eff69c33..1c2d312bca 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlibclient/index.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlibclient/index.ts @@ -5,6 +5,5 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -export * from "./testwasmlib"; export * from "./events"; export * from "./service"; diff --git a/contracts/wasm/testwasmlib/ts/testwasmlibclient/service.ts b/contracts/wasm/testwasmlib/ts/testwasmlibclient/service.ts index f738825fd4..fab9b3e3f0 100644 --- a/contracts/wasm/testwasmlib/ts/testwasmlibclient/service.ts +++ b/contracts/wasm/testwasmlib/ts/testwasmlibclient/service.ts @@ -41,24 +41,29 @@ const ResRandom = "random"; const ResRecord = "record"; const ResValue = "value"; -///////////////////////////// arrayClear ///////////////////////////// +///////////////////////////// arrayAppend ///////////////////////////// -export class ArrayClearFunc extends wasmclient.ClientFunc { +export class ArrayAppendFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { this.args.set(ArgName, this.args.fromString(v)); } + public value(v: string): void { + this.args.set(ArgValue, this.args.fromString(v)); + } + public async post(): Promise { this.args.mandatory(ArgName); - return await super.post(0x88021821, this.args); + this.args.mandatory(ArgValue); + return await super.post(0x612f835f, this.args); } } -///////////////////////////// arrayCreate ///////////////////////////// +///////////////////////////// arrayClear ///////////////////////////// -export class ArrayCreateFunc extends wasmclient.ClientFunc { +export class ArrayClearFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); public name(v: string): void { @@ -67,7 +72,7 @@ export class ArrayCreateFunc extends wasmclient.ClientFunc { public async post(): Promise { this.args.mandatory(ArgName); - return await super.post(0x1ed5b23b, this.args); + return await super.post(0x88021821, this.args); } } @@ -76,8 +81,8 @@ export class ArrayCreateFunc extends wasmclient.ClientFunc { export class ArraySetFunc extends wasmclient.ClientFunc { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public index(v: wasmclient.Int32): void { - this.args.set(ArgIndex, this.args.fromInt32(v)); + public index(v: wasmclient.Uint32): void { + this.args.set(ArgIndex, this.args.fromUint32(v)); } public name(v: string): void { @@ -111,21 +116,6 @@ export class MapClearFunc extends wasmclient.ClientFunc { } } -///////////////////////////// mapCreate ///////////////////////////// - -export class MapCreateFunc extends wasmclient.ClientFunc { - private args: wasmclient.Arguments = new wasmclient.Arguments(); - - public name(v: string): void { - this.args.set(ArgName, this.args.fromString(v)); - } - - public async post(): Promise { - this.args.mandatory(ArgName); - return await super.post(0x6295d599, this.args); - } -} - ///////////////////////////// mapSet ///////////////////////////// export class MapSetFunc extends wasmclient.ClientFunc { @@ -277,7 +267,7 @@ export class ArrayLengthView extends wasmclient.ClientView { public async call(): Promise { this.args.mandatory(ArgName); - const res = new ArrayLengthResults(); + const res = new ArrayLengthResults(); await this.callView("arrayLength", this.args, res); return res; } @@ -285,8 +275,8 @@ export class ArrayLengthView extends wasmclient.ClientView { export class ArrayLengthResults extends wasmclient.Results { - length(): wasmclient.Int32 { - return this.toInt32(this.get(ResLength)); + length(): wasmclient.Uint32 { + return this.toUint32(this.get(ResLength)); } } @@ -295,8 +285,8 @@ export class ArrayLengthResults extends wasmclient.Results { export class ArrayValueView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public index(v: wasmclient.Int32): void { - this.args.set(ArgIndex, this.args.fromInt32(v)); + public index(v: wasmclient.Uint32): void { + this.args.set(ArgIndex, this.args.fromUint32(v)); } public name(v: string): void { @@ -306,7 +296,7 @@ export class ArrayValueView extends wasmclient.ClientView { public async call(): Promise { this.args.mandatory(ArgIndex); this.args.mandatory(ArgName); - const res = new ArrayValueResults(); + const res = new ArrayValueResults(); await this.callView("arrayValue", this.args, res); return res; } @@ -324,18 +314,18 @@ export class ArrayValueResults extends wasmclient.Results { export class BlockRecordView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } - public recordIndex(v: wasmclient.Int32): void { - this.args.set(ArgRecordIndex, this.args.fromInt32(v)); + public recordIndex(v: wasmclient.Uint32): void { + this.args.set(ArgRecordIndex, this.args.fromUint32(v)); } public async call(): Promise { this.args.mandatory(ArgBlockIndex); this.args.mandatory(ArgRecordIndex); - const res = new BlockRecordResults(); + const res = new BlockRecordResults(); await this.callView("blockRecord", this.args, res); return res; } @@ -353,13 +343,13 @@ export class BlockRecordResults extends wasmclient.Results { export class BlockRecordsView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } public async call(): Promise { this.args.mandatory(ArgBlockIndex); - const res = new BlockRecordsResults(); + const res = new BlockRecordsResults(); await this.callView("blockRecords", this.args, res); return res; } @@ -367,8 +357,8 @@ export class BlockRecordsView extends wasmclient.ClientView { export class BlockRecordsResults extends wasmclient.Results { - count(): wasmclient.Int32 { - return this.toInt32(this.get(ResCount)); + count(): wasmclient.Uint32 { + return this.toUint32(this.get(ResCount)); } } @@ -377,7 +367,7 @@ export class BlockRecordsResults extends wasmclient.Results { export class GetRandomView extends wasmclient.ClientView { public async call(): Promise { - const res = new GetRandomResults(); + const res = new GetRandomResults(); await this.callView("getRandom", null, res); return res; } @@ -385,8 +375,8 @@ export class GetRandomView extends wasmclient.ClientView { export class GetRandomResults extends wasmclient.Results { - random(): wasmclient.Int64 { - return this.toInt64(this.get(ResRandom)); + random(): wasmclient.Uint64 { + return this.toUint64(this.get(ResRandom)); } } @@ -395,7 +385,7 @@ export class GetRandomResults extends wasmclient.Results { export class IotaBalanceView extends wasmclient.ClientView { public async call(): Promise { - const res = new IotaBalanceResults(); + const res = new IotaBalanceResults(); await this.callView("iotaBalance", null, res); return res; } @@ -403,8 +393,8 @@ export class IotaBalanceView extends wasmclient.ClientView { export class IotaBalanceResults extends wasmclient.Results { - iotas(): wasmclient.Int64 { - return this.toInt64(this.get(ResIotas)); + iotas(): wasmclient.Uint64 { + return this.toUint64(this.get(ResIotas)); } } @@ -424,7 +414,7 @@ export class MapValueView extends wasmclient.ClientView { public async call(): Promise { this.args.mandatory(ArgKey); this.args.mandatory(ArgName); - const res = new MapValueResults(); + const res = new MapValueResults(); await this.callView("mapValue", this.args, res); return res; } @@ -442,15 +432,19 @@ export class MapValueResults extends wasmclient.Results { export class TestWasmLibService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0x89703a45, events.eventHandlers); + super(cl, 0x89703a45); } - public arrayClear(): ArrayClearFunc { - return new ArrayClearFunc(this); + public newEventHandler(): events.TestWasmLibEvents { + return new events.TestWasmLibEvents(); } - public arrayCreate(): ArrayCreateFunc { - return new ArrayCreateFunc(this); + public arrayAppend(): ArrayAppendFunc { + return new ArrayAppendFunc(this); + } + + public arrayClear(): ArrayClearFunc { + return new ArrayClearFunc(this); } public arraySet(): ArraySetFunc { @@ -461,10 +455,6 @@ export class TestWasmLibService extends wasmclient.Service { return new MapClearFunc(this); } - public mapCreate(): MapCreateFunc { - return new MapCreateFunc(this); - } - public mapSet(): MapSetFunc { return new MapSetFunc(this); } diff --git a/contracts/wasm/timestamp/Cargo.toml b/contracts/wasm/timestamp/Cargo.toml index 1484bd0a63..7370467cfd 100644 --- a/contracts/wasm/timestamp/Cargo.toml +++ b/contracts/wasm/timestamp/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } console_error_panic_hook = { version = "0.1.6", optional = true } wee_alloc = { version = "0.4.5", optional = true } diff --git a/contracts/wasm/timestamp/go/main.go b/contracts/wasm/timestamp/go/main.go index 1d75f182d8..874d8a58e9 100644 --- a/contracts/wasm/timestamp/go/main.go +++ b/contracts/wasm/timestamp/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/timestamp/go/timestamp" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + timestamp.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - timestamp.OnLoad() + timestamp.OnLoad(-1) } diff --git a/contracts/wasm/timestamp/go/timestamp/consts.go b/contracts/wasm/timestamp/go/timestamp/consts.go index 7e2f5135f8..3e11452c57 100644 --- a/contracts/wasm/timestamp/go/timestamp/consts.go +++ b/contracts/wasm/timestamp/go/timestamp/consts.go @@ -7,28 +7,24 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "timestamp" ScDescription = "Extremely simple timestamp server" - HScName = wasmlib.ScHname(0x3988002e) + HScName = wasmtypes.ScHname(0x3988002e) ) const ( ResultTimestamp = "timestamp" ) -const ( - StateTimestamp = "timestamp" -) - const ( FuncNow = "now" ViewGetTimestamp = "getTimestamp" ) const ( - HFuncNow = wasmlib.ScHname(0xd73b7fc9) - HViewGetTimestamp = wasmlib.ScHname(0x40c6376a) + HFuncNow = wasmtypes.ScHname(0xd73b7fc9) + HViewGetTimestamp = wasmtypes.ScHname(0x40c6376a) ) diff --git a/contracts/wasm/timestamp/go/timestamp/contract.go b/contracts/wasm/timestamp/go/timestamp/contract.go index e58a562fbd..223d2f266f 100644 --- a/contracts/wasm/timestamp/go/timestamp/contract.go +++ b/contracts/wasm/timestamp/go/timestamp/contract.go @@ -7,7 +7,7 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type NowCall struct { Func *wasmlib.ScFunc @@ -28,6 +28,6 @@ func (sc Funcs) Now(ctx wasmlib.ScFuncCallContext) *NowCall { func (sc Funcs) GetTimestamp(ctx wasmlib.ScViewCallContext) *GetTimestampCall { f := &GetTimestampCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetTimestamp)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } diff --git a/contracts/wasm/timestamp/go/timestamp/keys.go b/contracts/wasm/timestamp/go/timestamp/keys.go deleted file mode 100644 index 9b658897b1..0000000000 --- a/contracts/wasm/timestamp/go/timestamp/keys.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package timestamp - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxResultTimestamp = 0 - - IdxStateTimestamp = 1 -) - -const keyMapLen = 2 - -var keyMap = [keyMapLen]wasmlib.Key{ - ResultTimestamp, - StateTimestamp, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/timestamp/go/timestamp/lib.go b/contracts/wasm/timestamp/go/timestamp/lib.go index bc42403aa1..b5eee016b9 100644 --- a/contracts/wasm/timestamp/go/timestamp/lib.go +++ b/contracts/wasm/timestamp/go/timestamp/lib.go @@ -7,16 +7,28 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncNow, funcNowThunk) - exports.AddView(ViewGetTimestamp, viewGetTimestampThunk) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncNow, + ViewGetTimestamp, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcNowThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetTimestampThunk, + }, +} - for i, key := range keyMap { - idxMap[i] = key.KeyID() +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type NowContext struct { @@ -27,7 +39,7 @@ func funcNowThunk(ctx wasmlib.ScFuncContext) { ctx.Log("timestamp.funcNow") f := &NowContext{ State: MutabletimestampState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcNow(ctx, f) @@ -41,14 +53,16 @@ type GetTimestampContext struct { func viewGetTimestampThunk(ctx wasmlib.ScViewContext) { ctx.Log("timestamp.viewGetTimestamp") + results := wasmlib.NewScDict() f := &GetTimestampContext{ Results: MutableGetTimestampResults{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, State: ImmutabletimestampState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } viewGetTimestamp(ctx, f) + ctx.Results(results) ctx.Log("timestamp.viewGetTimestamp ok") } diff --git a/contracts/wasm/timestamp/go/timestamp/results.go b/contracts/wasm/timestamp/go/timestamp/results.go index ca6aaac36a..532bf93bab 100644 --- a/contracts/wasm/timestamp/go/timestamp/results.go +++ b/contracts/wasm/timestamp/go/timestamp/results.go @@ -7,20 +7,20 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableGetTimestampResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetTimestampResults) Timestamp() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultTimestamp)) +func (s ImmutableGetTimestampResults) Timestamp() wasmtypes.ScImmutableUint64 { + return wasmtypes.NewScImmutableUint64(s.proxy.Root(ResultTimestamp)) } type MutableGetTimestampResults struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetTimestampResults) Timestamp() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultTimestamp)) +func (s MutableGetTimestampResults) Timestamp() wasmtypes.ScMutableUint64 { + return wasmtypes.NewScMutableUint64(s.proxy.Root(ResultTimestamp)) } diff --git a/contracts/wasm/timestamp/go/timestamp/state.go b/contracts/wasm/timestamp/go/timestamp/state.go index 8d1efbe83e..6c04f0877a 100644 --- a/contracts/wasm/timestamp/go/timestamp/state.go +++ b/contracts/wasm/timestamp/go/timestamp/state.go @@ -7,24 +7,16 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutabletimestampState struct { - id int32 -} - -func (s ImmutabletimestampState) Timestamp() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(StateTimestamp)) + proxy wasmtypes.Proxy } type MutabletimestampState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutabletimestampState) AsImmutable() ImmutabletimestampState { return ImmutabletimestampState(s) } - -func (s MutabletimestampState) Timestamp() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(StateTimestamp)) -} diff --git a/contracts/wasm/timestamp/go/timestamp/timestamp.go b/contracts/wasm/timestamp/go/timestamp/timestamp.go index f8af6b9764..c16d40a25b 100644 --- a/contracts/wasm/timestamp/go/timestamp/timestamp.go +++ b/contracts/wasm/timestamp/go/timestamp/timestamp.go @@ -3,12 +3,11 @@ package timestamp -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" func funcNow(ctx wasmlib.ScFuncContext, f *NowContext) { - f.State.Timestamp().SetValue(ctx.Timestamp()) } func viewGetTimestamp(ctx wasmlib.ScViewContext, f *GetTimestampContext) { - f.Results.Timestamp().SetValue(f.State.Timestamp().Value()) + f.Results.Timestamp().SetValue(ctx.Timestamp()) } diff --git a/contracts/wasm/timestamp/schema.yaml b/contracts/wasm/timestamp/schema.yaml index aaad197bea..3f901f04f5 100644 --- a/contracts/wasm/timestamp/schema.yaml +++ b/contracts/wasm/timestamp/schema.yaml @@ -3,10 +3,9 @@ description: Extremely simple timestamp server structs: {} typedefs: {} state: - timestamp: Int64 // last official timestamp generated funcs: now: views: getTimestamp: results: - timestamp: Int64 // last official timestamp generated + timestamp: Uint64 // last official timestamp generated diff --git a/contracts/wasm/timestamp/src/consts.rs b/contracts/wasm/timestamp/src/consts.rs index 31a77b2afd..252410419d 100644 --- a/contracts/wasm/timestamp/src/consts.rs +++ b/contracts/wasm/timestamp/src/consts.rs @@ -15,8 +15,6 @@ pub const HSC_NAME : ScHname = ScHname(0x3988002e); pub const RESULT_TIMESTAMP : &str = "timestamp"; -pub const STATE_TIMESTAMP : &str = "timestamp"; - pub const FUNC_NOW : &str = "now"; pub const VIEW_GET_TIMESTAMP : &str = "getTimestamp"; diff --git a/contracts/wasm/timestamp/src/contract.rs b/contracts/wasm/timestamp/src/contract.rs index 91ec41f186..7462ad0067 100644 --- a/contracts/wasm/timestamp/src/contract.rs +++ b/contracts/wasm/timestamp/src/contract.rs @@ -7,12 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::results::*; +use crate::*; pub struct NowCall { pub func: ScFunc, @@ -27,18 +23,18 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn now(_ctx: & dyn ScFuncCallContext) -> NowCall { + pub fn now(_ctx: &dyn ScFuncCallContext) -> NowCall { NowCall { func: ScFunc::new(HSC_NAME, HFUNC_NOW), } } - pub fn get_timestamp(_ctx: & dyn ScViewCallContext) -> GetTimestampCall { + pub fn get_timestamp(_ctx: &dyn ScViewCallContext) -> GetTimestampCall { let mut f = GetTimestampCall { func: ScView::new(HSC_NAME, HVIEW_GET_TIMESTAMP), - results: ImmutableGetTimestampResults { id: 0 }, + results: ImmutableGetTimestampResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/contracts/wasm/timestamp/src/keys.rs b/contracts/wasm/timestamp/src/keys.rs deleted file mode 100644 index 52cdcdbbb8..0000000000 --- a/contracts/wasm/timestamp/src/keys.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - - -pub(crate) const IDX_RESULT_TIMESTAMP : usize = 0; - -pub(crate) const IDX_STATE_TIMESTAMP : usize = 1; - -pub const KEY_MAP_LEN: usize = 2; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - RESULT_TIMESTAMP, - STATE_TIMESTAMP, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/timestamp/src/lib.rs b/contracts/wasm/timestamp/src/lib.rs index e50f6ade0a..b56c8f3b0c 100644 --- a/contracts/wasm/timestamp/src/lib.rs +++ b/contracts/wasm/timestamp/src/lib.rs @@ -10,31 +10,39 @@ use timestamp::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::results::*; use crate::state::*; mod consts; mod contract; -mod keys; mod results; mod state; + mod timestamp; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_NOW, + VIEW_GET_TIMESTAMP, + ], + funcs: &[ + func_now_thunk, + ], + views: &[ + view_get_timestamp_thunk, + ], +}; + #[no_mangle] -fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_NOW, func_now_thunk); - exports.add_view(VIEW_GET_TIMESTAMP, view_get_timestamp_thunk); +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } +#[no_mangle] +fn on_load() { + ScExports::export(&EXPORT_MAP); } pub struct NowContext { @@ -44,9 +52,7 @@ pub struct NowContext { fn func_now_thunk(ctx: &ScFuncContext) { ctx.log("timestamp.funcNow"); let f = NowContext { - state: MutabletimestampState { - id: OBJ_ID_STATE, - }, + state: MutabletimestampState { proxy: state_proxy() }, }; func_now(ctx, &f); ctx.log("timestamp.funcNow ok"); @@ -60,13 +66,10 @@ pub struct GetTimestampContext { fn view_get_timestamp_thunk(ctx: &ScViewContext) { ctx.log("timestamp.viewGetTimestamp"); let f = GetTimestampContext { - results: MutableGetTimestampResults { - id: OBJ_ID_RESULTS, - }, - state: ImmutabletimestampState { - id: OBJ_ID_STATE, - }, + results: MutableGetTimestampResults { proxy: results_proxy() }, + state: ImmutabletimestampState { proxy: state_proxy() }, }; view_get_timestamp(ctx, &f); + ctx.results(&f.results.proxy.kv_store); ctx.log("timestamp.viewGetTimestamp ok"); } diff --git a/contracts/wasm/timestamp/src/results.rs b/contracts/wasm/timestamp/src/results.rs index b0de1e3b73..115284a700 100644 --- a/contracts/wasm/timestamp/src/results.rs +++ b/contracts/wasm/timestamp/src/results.rs @@ -9,29 +9,26 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetTimestampResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetTimestampResults { - pub fn timestamp(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_TIMESTAMP.get_key_id()) + pub fn timestamp(&self) -> ScImmutableUint64 { + ScImmutableUint64::new(self.proxy.root(RESULT_TIMESTAMP)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetTimestampResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetTimestampResults { - pub fn timestamp(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_TIMESTAMP.get_key_id()) + pub fn timestamp(&self) -> ScMutableUint64 { + ScMutableUint64::new(self.proxy.root(RESULT_TIMESTAMP)) } } diff --git a/contracts/wasm/timestamp/src/state.rs b/contracts/wasm/timestamp/src/state.rs index 3b05d63230..35fe5c6ee0 100644 --- a/contracts/wasm/timestamp/src/state.rs +++ b/contracts/wasm/timestamp/src/state.rs @@ -9,33 +9,15 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutabletimestampState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } -impl ImmutabletimestampState { - pub fn timestamp(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, STATE_TIMESTAMP.get_key_id()) - } -} - -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutabletimestampState { - pub(crate) id: i32, -} - -impl MutabletimestampState { - pub fn as_immutable(&self) -> ImmutabletimestampState { - ImmutabletimestampState { id: self.id } - } - - pub fn timestamp(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, STATE_TIMESTAMP.get_key_id()) - } + pub(crate) proxy: Proxy, } diff --git a/contracts/wasm/timestamp/src/timestamp.rs b/contracts/wasm/timestamp/src/timestamp.rs index 1ca7585bd1..4e07b56b4e 100644 --- a/contracts/wasm/timestamp/src/timestamp.rs +++ b/contracts/wasm/timestamp/src/timestamp.rs @@ -5,10 +5,9 @@ use wasmlib::*; use crate::*; -pub fn func_now(ctx: &ScFuncContext, f: &NowContext) { - f.state.timestamp().set_value(ctx.timestamp()); +pub fn func_now(_ctx: &ScFuncContext, _f: &NowContext) { } -pub fn view_get_timestamp(_ctx: &ScViewContext, f: &GetTimestampContext) { - f.results.timestamp().set_value(f.state.timestamp().value()); +pub fn view_get_timestamp(ctx: &ScViewContext, f: &GetTimestampContext) { + f.results.timestamp().set_value(ctx.timestamp()); } diff --git a/contracts/wasm/timestamp/test/timestamp_bg.wasm b/contracts/wasm/timestamp/test/timestamp_bg.wasm index 9c3c530519..cc59470060 100644 Binary files a/contracts/wasm/timestamp/test/timestamp_bg.wasm and b/contracts/wasm/timestamp/test/timestamp_bg.wasm differ diff --git a/contracts/wasm/timestamp/test/timestamp_test.go b/contracts/wasm/timestamp/test/timestamp_test.go index 5dbf04649e..1eb2423fee 100644 --- a/contracts/wasm/timestamp/test/timestamp_test.go +++ b/contracts/wasm/timestamp/test/timestamp_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/iotaledger/wasp/contracts/wasm/timestamp/go/timestamp" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -12,3 +12,47 @@ func TestDeploy(t *testing.T) { ctx := wasmsolo.NewSoloContext(t, timestamp.ScName, timestamp.OnLoad) require.NoError(t, ctx.ContractExists(timestamp.ScName)) } + +func TestStamp(t *testing.T) { + ctx := wasmsolo.NewSoloContext(t, timestamp.ScName, timestamp.OnLoad) + + v := timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + t1 := v.Results.Timestamp().Value() + + v = timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + require.EqualValues(t, t1, v.Results.Timestamp().Value()) + + f := timestamp.ScFuncs.Now(ctx) + f.Func.Post() + require.NoError(t, ctx.Err) + + v = timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + t2 := v.Results.Timestamp().Value() + require.Greater(t, t2, t1) + + v = timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + require.EqualValues(t, t2, v.Results.Timestamp().Value()) + + f = timestamp.ScFuncs.Now(ctx) + f.Func.Post() + require.NoError(t, ctx.Err) + + v = timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + t3 := v.Results.Timestamp().Value() + require.Greater(t, t3, t2) + + v = timestamp.ScFuncs.GetTimestamp(ctx) + v.Func.Call() + require.NoError(t, ctx.Err) + require.EqualValues(t, t3, v.Results.Timestamp().Value()) +} diff --git a/contracts/wasm/timestamp/ts/timestamp/consts.ts b/contracts/wasm/timestamp/ts/timestamp/consts.ts index 62157f5505..f2926df660 100644 --- a/contracts/wasm/timestamp/ts/timestamp/consts.ts +++ b/contracts/wasm/timestamp/ts/timestamp/consts.ts @@ -5,18 +5,16 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "timestamp"; export const ScDescription = "Extremely simple timestamp server"; -export const HScName = new wasmlib.ScHname(0x3988002e); +export const HScName = new wasmtypes.ScHname(0x3988002e); export const ResultTimestamp = "timestamp"; -export const StateTimestamp = "timestamp"; - export const FuncNow = "now"; export const ViewGetTimestamp = "getTimestamp"; -export const HFuncNow = new wasmlib.ScHname(0xd73b7fc9); -export const HViewGetTimestamp = new wasmlib.ScHname(0x40c6376a); +export const HFuncNow = new wasmtypes.ScHname(0xd73b7fc9); +export const HViewGetTimestamp = new wasmtypes.ScHname(0x40c6376a); diff --git a/contracts/wasm/timestamp/ts/timestamp/contract.ts b/contracts/wasm/timestamp/ts/timestamp/contract.ts index f95a487aa2..3b6c099557 100644 --- a/contracts/wasm/timestamp/ts/timestamp/contract.ts +++ b/contracts/wasm/timestamp/ts/timestamp/contract.ts @@ -13,27 +13,27 @@ export class NowCall { } export class NowContext { - state: sc.MutabletimestampState = new sc.MutabletimestampState(); + state: sc.MutabletimestampState = new sc.MutabletimestampState(wasmlib.ScState.proxy()); } export class GetTimestampCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetTimestamp); - results: sc.ImmutableGetTimestampResults = new sc.ImmutableGetTimestampResults(); + results: sc.ImmutableGetTimestampResults = new sc.ImmutableGetTimestampResults(wasmlib.ScView.nilProxy); } export class GetTimestampContext { - results: sc.MutableGetTimestampResults = new sc.MutableGetTimestampResults(); - state: sc.ImmutabletimestampState = new sc.ImmutabletimestampState(); + results: sc.MutableGetTimestampResults = new sc.MutableGetTimestampResults(wasmlib.ScView.nilProxy); + state: sc.ImmutabletimestampState = new sc.ImmutabletimestampState(wasmlib.ScState.proxy()); } export class ScFuncs { - static now(ctx: wasmlib.ScFuncCallContext): NowCall { - return new NowCall(); - } - - static getTimestamp(ctx: wasmlib.ScViewCallContext): GetTimestampCall { - let f = new GetTimestampCall(); - f.func.setPtrs(null, f.results); - return f; - } + static now(_ctx: wasmlib.ScFuncCallContext): NowCall { + return new NowCall(); + } + + static getTimestamp(_ctx: wasmlib.ScViewCallContext): GetTimestampCall { + const f = new GetTimestampCall(); + f.results = new sc.ImmutableGetTimestampResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/timestamp/ts/timestamp/index.ts b/contracts/wasm/timestamp/ts/timestamp/index.ts index 0b905cf8fd..f356a4ef4f 100644 --- a/contracts/wasm/timestamp/ts/timestamp/index.ts +++ b/contracts/wasm/timestamp/ts/timestamp/index.ts @@ -9,7 +9,6 @@ export * from "./timestamp"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./results"; export * from "./state"; diff --git a/contracts/wasm/timestamp/ts/timestamp/keys.ts b/contracts/wasm/timestamp/ts/timestamp/keys.ts deleted file mode 100644 index 3cfd4e84d0..0000000000 --- a/contracts/wasm/timestamp/ts/timestamp/keys.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - - -export const IdxResultTimestamp = 0; - -export const IdxStateTimestamp = 1; - -export let keyMap: string[] = [ - sc.ResultTimestamp, - sc.StateTimestamp, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/timestamp/ts/timestamp/lib.ts b/contracts/wasm/timestamp/ts/timestamp/lib.ts index 80e29210f7..c189814461 100644 --- a/contracts/wasm/timestamp/ts/timestamp/lib.ts +++ b/contracts/wasm/timestamp/ts/timestamp/lib.ts @@ -8,24 +8,30 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncNow, + sc.ViewGetTimestamp, + ], + funcs: [ + funcNowThunk, + ], + views: [ + viewGetTimestampThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncNow, funcNowThunk); - exports.addView(sc.ViewGetTimestamp, viewGetTimestampThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcNowThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("timestamp.funcNow"); let f = new sc.NowContext(); - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcNow(ctx, f); ctx.log("timestamp.funcNow ok"); } @@ -33,8 +39,9 @@ function funcNowThunk(ctx: wasmlib.ScFuncContext): void { function viewGetTimestampThunk(ctx: wasmlib.ScViewContext): void { ctx.log("timestamp.viewGetTimestamp"); let f = new sc.GetTimestampContext(); - f.results.mapID = wasmlib.OBJ_ID_RESULTS; - f.state.mapID = wasmlib.OBJ_ID_STATE; + const results = new wasmlib.ScDict([]); + f.results = new sc.MutableGetTimestampResults(results.asProxy()); sc.viewGetTimestamp(ctx, f); + ctx.results(results); ctx.log("timestamp.viewGetTimestamp ok"); } diff --git a/contracts/wasm/timestamp/ts/timestamp/results.ts b/contracts/wasm/timestamp/ts/timestamp/results.ts index 5644226dec..45bf35eb11 100644 --- a/contracts/wasm/timestamp/ts/timestamp/results.ts +++ b/contracts/wasm/timestamp/ts/timestamp/results.ts @@ -5,17 +5,17 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableGetTimestampResults extends wasmlib.ScMapID { - timestamp(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTimestamp)); +export class ImmutableGetTimestampResults extends wasmtypes.ScProxy { + timestamp(): wasmtypes.ScImmutableUint64 { + return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.ResultTimestamp)); } } -export class MutableGetTimestampResults extends wasmlib.ScMapID { - timestamp(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultTimestamp)); +export class MutableGetTimestampResults extends wasmtypes.ScProxy { + timestamp(): wasmtypes.ScMutableUint64 { + return new wasmtypes.ScMutableUint64(this.proxy.root(sc.ResultTimestamp)); } } diff --git a/contracts/wasm/timestamp/ts/timestamp/state.ts b/contracts/wasm/timestamp/ts/timestamp/state.ts index 43c2fce463..14ff8b02f4 100644 --- a/contracts/wasm/timestamp/ts/timestamp/state.ts +++ b/contracts/wasm/timestamp/ts/timestamp/state.ts @@ -5,23 +5,14 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutabletimestampState extends wasmlib.ScMapID { - timestamp(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTimestamp)); - } +export class ImmutabletimestampState extends wasmtypes.ScProxy { } -export class MutabletimestampState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutabletimestampState { - const imm = new sc.ImmutabletimestampState(); - imm.mapID = this.mapID; - return imm; - } - - timestamp(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.StateTimestamp)); +export class MutabletimestampState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutabletimestampState { + return new sc.ImmutabletimestampState(this.proxy); } } diff --git a/contracts/wasm/timestamp/ts/timestamp/timestamp.ts b/contracts/wasm/timestamp/ts/timestamp/timestamp.ts index 5c232cf49a..275a2c6529 100644 --- a/contracts/wasm/timestamp/ts/timestamp/timestamp.ts +++ b/contracts/wasm/timestamp/ts/timestamp/timestamp.ts @@ -5,9 +5,8 @@ import * as wasmlib from "wasmlib" import * as sc from "./index"; export function funcNow(ctx: wasmlib.ScFuncContext, f: sc.NowContext): void { - f.state.timestamp().setValue(ctx.timestamp()); } export function viewGetTimestamp(ctx: wasmlib.ScViewContext, f: sc.GetTimestampContext): void { - f.results.timestamp().setValue(f.state.timestamp().value()); + f.results.timestamp().setValue(ctx.timestamp()); } diff --git a/contracts/wasm/tokenregistry/Cargo.toml b/contracts/wasm/tokenregistry/Cargo.toml index 77d8171015..bf2dd6ea95 100644 --- a/contracts/wasm/tokenregistry/Cargo.toml +++ b/contracts/wasm/tokenregistry/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../../packages/vm/wasmlib" } +wasmlib = { path = "../../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/contracts/wasm/tokenregistry/go/main.go b/contracts/wasm/tokenregistry/go/main.go index be160c7c43..fb18f0f44e 100644 --- a/contracts/wasm/tokenregistry/go/main.go +++ b/contracts/wasm/tokenregistry/go/main.go @@ -5,20 +5,28 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "github.com/iotaledger/wasp/contracts/wasm/tokenregistry/go/tokenregistry" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + tokenregistry.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - tokenregistry.OnLoad() + tokenregistry.OnLoad(-1) } diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/consts.go b/contracts/wasm/tokenregistry/go/tokenregistry/consts.go index 03f53793bd..9d4bad073b 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/consts.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/consts.go @@ -7,12 +7,12 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "tokenregistry" ScDescription = "" - HScName = wasmlib.ScHname(0xe1ba0c78) + HScName = wasmtypes.ScHname(0xe1ba0c78) ) const ( @@ -34,8 +34,8 @@ const ( ) const ( - HFuncMintSupply = wasmlib.ScHname(0x564349a7) - HFuncTransferOwnership = wasmlib.ScHname(0xbb9eb5af) - HFuncUpdateMetadata = wasmlib.ScHname(0xa26b23b6) - HViewGetInfo = wasmlib.ScHname(0xcfedba5f) + HFuncMintSupply = wasmtypes.ScHname(0x564349a7) + HFuncTransferOwnership = wasmtypes.ScHname(0xbb9eb5af) + HFuncUpdateMetadata = wasmtypes.ScHname(0xa26b23b6) + HViewGetInfo = wasmtypes.ScHname(0xcfedba5f) ) diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/contract.go b/contracts/wasm/tokenregistry/go/tokenregistry/contract.go index c254b5d29d..c2c04115a0 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/contract.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/contract.go @@ -7,7 +7,7 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type MintSupplyCall struct { Func *wasmlib.ScFunc @@ -35,24 +35,24 @@ var ScFuncs Funcs func (sc Funcs) MintSupply(ctx wasmlib.ScFuncCallContext) *MintSupplyCall { f := &MintSupplyCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncMintSupply)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) TransferOwnership(ctx wasmlib.ScFuncCallContext) *TransferOwnershipCall { f := &TransferOwnershipCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferOwnership)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) UpdateMetadata(ctx wasmlib.ScFuncCallContext) *UpdateMetadataCall { f := &UpdateMetadataCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncUpdateMetadata)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GetInfo(ctx wasmlib.ScViewCallContext) *GetInfoCall { f := &GetInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetInfo)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) return f } diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/keys.go b/contracts/wasm/tokenregistry/go/tokenregistry/keys.go deleted file mode 100644 index ec80cb792f..0000000000 --- a/contracts/wasm/tokenregistry/go/tokenregistry/keys.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package tokenregistry - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -const ( - IdxParamColor = 0 - IdxParamDescription = 1 - IdxParamUserDefined = 2 - - IdxStateColorList = 3 - IdxStateRegistry = 4 -) - -const keyMapLen = 5 - -var keyMap = [keyMapLen]wasmlib.Key{ - ParamColor, - ParamDescription, - ParamUserDefined, - StateColorList, - StateRegistry, -} - -var idxMap [keyMapLen]wasmlib.Key32 diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/lib.go b/contracts/wasm/tokenregistry/go/tokenregistry/lib.go index 1d16acbac7..af4b4823d9 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/lib.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/lib.go @@ -7,18 +7,32 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncMintSupply, funcMintSupplyThunk) - exports.AddFunc(FuncTransferOwnership, funcTransferOwnershipThunk) - exports.AddFunc(FuncUpdateMetadata, funcUpdateMetadataThunk) - exports.AddView(ViewGetInfo, viewGetInfoThunk) +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncMintSupply, + FuncTransferOwnership, + FuncUpdateMetadata, + ViewGetInfo, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + funcMintSupplyThunk, + funcTransferOwnershipThunk, + funcUpdateMetadataThunk, + }, + Views: []wasmlib.ScViewContextFunction{ + viewGetInfoThunk, + }, +} - for i, key := range keyMap { - idxMap[i] = key.KeyID() +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } type MintSupplyContext struct { @@ -30,10 +44,10 @@ func funcMintSupplyThunk(ctx wasmlib.ScFuncContext) { ctx.Log("tokenregistry.funcMintSupply") f := &MintSupplyContext{ Params: ImmutableMintSupplyParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTokenRegistryState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } funcMintSupply(ctx, f) @@ -47,18 +61,18 @@ type TransferOwnershipContext struct { func funcTransferOwnershipThunk(ctx wasmlib.ScFuncContext) { ctx.Log("tokenregistry.funcTransferOwnership") - - // TODO the one who can transfer token ownership - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &TransferOwnershipContext{ Params: ImmutableTransferOwnershipParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTokenRegistryState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // TODO the one who can transfer token ownership + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + ctx.Require(f.Params.Color().Exists(), "missing mandatory color") funcTransferOwnership(ctx, f) ctx.Log("tokenregistry.funcTransferOwnership ok") @@ -71,18 +85,18 @@ type UpdateMetadataContext struct { func funcUpdateMetadataThunk(ctx wasmlib.ScFuncContext) { ctx.Log("tokenregistry.funcUpdateMetadata") - - // TODO the one who can change the token info - ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") - f := &UpdateMetadataContext{ Params: ImmutableUpdateMetadataParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: MutableTokenRegistryState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } + + // TODO the one who can change the token info + ctx.Require(ctx.Caller() == ctx.ContractCreator(), "no permission") + ctx.Require(f.Params.Color().Exists(), "missing mandatory color") funcUpdateMetadata(ctx, f) ctx.Log("tokenregistry.funcUpdateMetadata ok") @@ -97,10 +111,10 @@ func viewGetInfoThunk(ctx wasmlib.ScViewContext) { ctx.Log("tokenregistry.viewGetInfo") f := &GetInfoContext{ Params: ImmutableGetInfoParams{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, State: ImmutableTokenRegistryState{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, } ctx.Require(f.Params.Color().Exists(), "missing mandatory color") diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/params.go b/contracts/wasm/tokenregistry/go/tokenregistry/params.go index 4a71631851..38abcb8bb3 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/params.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/params.go @@ -7,76 +7,76 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ImmutableMintSupplyParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableMintSupplyParams) Description() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamDescription)) +func (s ImmutableMintSupplyParams) Description() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamDescription)) } -func (s ImmutableMintSupplyParams) UserDefined() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamUserDefined)) +func (s ImmutableMintSupplyParams) UserDefined() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamUserDefined)) } type MutableMintSupplyParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableMintSupplyParams) Description() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamDescription)) +func (s MutableMintSupplyParams) Description() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamDescription)) } -func (s MutableMintSupplyParams) UserDefined() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamUserDefined)) +func (s MutableMintSupplyParams) UserDefined() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamUserDefined)) } type ImmutableTransferOwnershipParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableTransferOwnershipParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableTransferOwnershipParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutableTransferOwnershipParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableTransferOwnershipParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableTransferOwnershipParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } type ImmutableUpdateMetadataParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableUpdateMetadataParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableUpdateMetadataParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutableUpdateMetadataParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableUpdateMetadataParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableUpdateMetadataParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } type ImmutableGetInfoParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s ImmutableGetInfoParams) Color() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s ImmutableGetInfoParams) Color() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamColor)) } type MutableGetInfoParams struct { - id int32 + proxy wasmtypes.Proxy } -func (s MutableGetInfoParams) Color() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamColor)) +func (s MutableGetInfoParams) Color() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamColor)) } diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/state.go b/contracts/wasm/tokenregistry/go/tokenregistry/state.go index ffd7d313f9..8e88404f71 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/state.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/state.go @@ -7,72 +7,74 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type ArrayOfImmutableColor struct { - objID int32 + proxy wasmtypes.Proxy } -func (a ArrayOfImmutableColor) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfImmutableColor) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfImmutableColor) GetColor(index int32) wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(a.objID, wasmlib.Key32(index)) +func (a ArrayOfImmutableColor) GetColor(index uint32) wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(a.proxy.Index(index)) } type MapColorToImmutableToken struct { - objID int32 + proxy wasmtypes.Proxy } -func (m MapColorToImmutableToken) GetToken(key wasmlib.ScColor) ImmutableToken { - return ImmutableToken{objID: m.objID, keyID: key.KeyID()} +func (m MapColorToImmutableToken) GetToken(key wasmtypes.ScColor) ImmutableToken { + return ImmutableToken{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type ImmutableTokenRegistryState struct { - id int32 + proxy wasmtypes.Proxy } func (s ImmutableTokenRegistryState) ColorList() ArrayOfImmutableColor { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateColorList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_COLOR) - return ArrayOfImmutableColor{objID: arrID} + return ArrayOfImmutableColor{proxy: s.proxy.Root(StateColorList)} } func (s ImmutableTokenRegistryState) Registry() MapColorToImmutableToken { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateRegistry), wasmlib.TYPE_MAP) - return MapColorToImmutableToken{objID: mapID} + return MapColorToImmutableToken{proxy: s.proxy.Root(StateRegistry)} } type ArrayOfMutableColor struct { - objID int32 + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableColor) AppendColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(a.proxy.Append()) } func (a ArrayOfMutableColor) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } -func (a ArrayOfMutableColor) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a ArrayOfMutableColor) Length() uint32 { + return a.proxy.Length() } -func (a ArrayOfMutableColor) GetColor(index int32) wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(a.objID, wasmlib.Key32(index)) +func (a ArrayOfMutableColor) GetColor(index uint32) wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(a.proxy.Index(index)) } type MapColorToMutableToken struct { - objID int32 + proxy wasmtypes.Proxy } func (m MapColorToMutableToken) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } -func (m MapColorToMutableToken) GetToken(key wasmlib.ScColor) MutableToken { - return MutableToken{objID: m.objID, keyID: key.KeyID()} +func (m MapColorToMutableToken) GetToken(key wasmtypes.ScColor) MutableToken { + return MutableToken{proxy: m.proxy.Key(wasmtypes.ColorToBytes(key))} } type MutableTokenRegistryState struct { - id int32 + proxy wasmtypes.Proxy } func (s MutableTokenRegistryState) AsImmutable() ImmutableTokenRegistryState { @@ -80,11 +82,9 @@ func (s MutableTokenRegistryState) AsImmutable() ImmutableTokenRegistryState { } func (s MutableTokenRegistryState) ColorList() ArrayOfMutableColor { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateColorList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_COLOR) - return ArrayOfMutableColor{objID: arrID} + return ArrayOfMutableColor{proxy: s.proxy.Root(StateColorList)} } func (s MutableTokenRegistryState) Registry() MapColorToMutableToken { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(StateRegistry), wasmlib.TYPE_MAP) - return MapColorToMutableToken{objID: mapID} + return MapColorToMutableToken{proxy: s.proxy.Root(StateRegistry)} } diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/structs.go b/contracts/wasm/tokenregistry/go/tokenregistry/structs.go index 7dbf217c6f..85b36a2554 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/structs.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/structs.go @@ -7,74 +7,72 @@ package tokenregistry -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" type Token struct { - Created int64 // creation timestamp - Description string // description what minted token represents - MintedBy wasmlib.ScAgentID // original minter - Owner wasmlib.ScAgentID // current owner - Supply int64 // amount of tokens originally minted - Updated int64 // last update timestamp - UserDefined string // any user defined text + Created uint64 // creation timestamp + Description string // description what minted token represents + MintedBy wasmtypes.ScAgentID // original minter + Owner wasmtypes.ScAgentID // current owner + Supply uint64 // amount of tokens originally minted + Updated uint64 // last update timestamp + UserDefined string // any user defined text } -func NewTokenFromBytes(bytes []byte) *Token { - decode := wasmlib.NewBytesDecoder(bytes) +func NewTokenFromBytes(buf []byte) *Token { + dec := wasmtypes.NewWasmDecoder(buf) data := &Token{} - data.Created = decode.Int64() - data.Description = decode.String() - data.MintedBy = decode.AgentID() - data.Owner = decode.AgentID() - data.Supply = decode.Int64() - data.Updated = decode.Int64() - data.UserDefined = decode.String() - decode.Close() + data.Created = wasmtypes.Uint64Decode(dec) + data.Description = wasmtypes.StringDecode(dec) + data.MintedBy = wasmtypes.AgentIDDecode(dec) + data.Owner = wasmtypes.AgentIDDecode(dec) + data.Supply = wasmtypes.Uint64Decode(dec) + data.Updated = wasmtypes.Uint64Decode(dec) + data.UserDefined = wasmtypes.StringDecode(dec) + dec.Close() return data } func (o *Token) Bytes() []byte { - return wasmlib.NewBytesEncoder(). - Int64(o.Created). - String(o.Description). - AgentID(o.MintedBy). - AgentID(o.Owner). - Int64(o.Supply). - Int64(o.Updated). - String(o.UserDefined). - Data() + enc := wasmtypes.NewWasmEncoder() + wasmtypes.Uint64Encode(enc, o.Created) + wasmtypes.StringEncode(enc, o.Description) + wasmtypes.AgentIDEncode(enc, o.MintedBy) + wasmtypes.AgentIDEncode(enc, o.Owner) + wasmtypes.Uint64Encode(enc, o.Supply) + wasmtypes.Uint64Encode(enc, o.Updated) + wasmtypes.StringEncode(enc, o.UserDefined) + return enc.Buf() } type ImmutableToken struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o ImmutableToken) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o ImmutableToken) Value() *Token { - return NewTokenFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewTokenFromBytes(o.proxy.Get()) } type MutableToken struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } func (o MutableToken) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } func (o MutableToken) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } func (o MutableToken) SetValue(value *Token) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } func (o MutableToken) Value() *Token { - return NewTokenFromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return NewTokenFromBytes(o.proxy.Get()) } diff --git a/contracts/wasm/tokenregistry/go/tokenregistry/tokenregistry.go b/contracts/wasm/tokenregistry/go/tokenregistry/tokenregistry.go index cc6d7d48dc..849a1d66e3 100644 --- a/contracts/wasm/tokenregistry/go/tokenregistry/tokenregistry.go +++ b/contracts/wasm/tokenregistry/go/tokenregistry/tokenregistry.go @@ -4,14 +4,14 @@ package tokenregistry import ( - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" ) func funcMintSupply(ctx wasmlib.ScFuncContext, f *MintSupplyContext) { minted := ctx.Minted() mintedColors := minted.Colors() - ctx.Require(mintedColors.Length() == 1, "need single minted color") - mintedColor := mintedColors.GetColor(0).Value() + ctx.Require(len(mintedColors) == 1, "need single minted color") + mintedColor := mintedColors[0] currentToken := f.State.Registry().GetToken(mintedColor) if currentToken.Exists() { // should never happen, because transaction id is unique @@ -31,7 +31,7 @@ func funcMintSupply(ctx wasmlib.ScFuncContext, f *MintSupplyContext) { } currentToken.SetValue(token) colorList := f.State.ColorList() - colorList.GetColor(colorList.Length()).SetValue(mintedColor) + colorList.AppendColor().SetValue(mintedColor) } func funcTransferOwnership(ctx wasmlib.ScFuncContext, f *TransferOwnershipContext) { diff --git a/contracts/wasm/tokenregistry/schema.yaml b/contracts/wasm/tokenregistry/schema.yaml index 3048afcc3e..b980690567 100644 --- a/contracts/wasm/tokenregistry/schema.yaml +++ b/contracts/wasm/tokenregistry/schema.yaml @@ -2,12 +2,12 @@ name: TokenRegistry description: "" structs: Token: - created: Int64 // creation timestamp + created: Uint64 // creation timestamp description: String // description what minted token represents mintedBy: AgentID // original minter owner: AgentID // current owner - supply: Int64 // amount of tokens originally minted - updated: Int64 // last update timestamp + supply: Uint64 // amount of tokens originally minted + updated: Uint64 // last update timestamp userDefined: String // any user defined text typedefs: {} state: diff --git a/contracts/wasm/tokenregistry/src/contract.rs b/contracts/wasm/tokenregistry/src/contract.rs index d99016a400..2bd333ef37 100644 --- a/contracts/wasm/tokenregistry/src/contract.rs +++ b/contracts/wasm/tokenregistry/src/contract.rs @@ -7,12 +7,8 @@ #![allow(dead_code)] -use std::ptr; - use wasmlib::*; - -use crate::consts::*; -use crate::params::*; +use crate::*; pub struct MintSupplyCall { pub func: ScFunc, @@ -38,39 +34,39 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn mint_supply(_ctx: & dyn ScFuncCallContext) -> MintSupplyCall { + pub fn mint_supply(_ctx: &dyn ScFuncCallContext) -> MintSupplyCall { let mut f = MintSupplyCall { func: ScFunc::new(HSC_NAME, HFUNC_MINT_SUPPLY), - params: MutableMintSupplyParams { id: 0 }, + params: MutableMintSupplyParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn transfer_ownership(_ctx: & dyn ScFuncCallContext) -> TransferOwnershipCall { + pub fn transfer_ownership(_ctx: &dyn ScFuncCallContext) -> TransferOwnershipCall { let mut f = TransferOwnershipCall { func: ScFunc::new(HSC_NAME, HFUNC_TRANSFER_OWNERSHIP), - params: MutableTransferOwnershipParams { id: 0 }, + params: MutableTransferOwnershipParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn update_metadata(_ctx: & dyn ScFuncCallContext) -> UpdateMetadataCall { + pub fn update_metadata(_ctx: &dyn ScFuncCallContext) -> UpdateMetadataCall { let mut f = UpdateMetadataCall { func: ScFunc::new(HSC_NAME, HFUNC_UPDATE_METADATA), - params: MutableUpdateMetadataParams { id: 0 }, + params: MutableUpdateMetadataParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn get_info(_ctx: & dyn ScViewCallContext) -> GetInfoCall { + pub fn get_info(_ctx: &dyn ScViewCallContext) -> GetInfoCall { let mut f = GetInfoCall { func: ScView::new(HSC_NAME, HVIEW_GET_INFO), - params: MutableGetInfoParams { id: 0 }, + params: MutableGetInfoParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScView::link_params(&mut f.params.proxy, &f.func); f } } diff --git a/contracts/wasm/tokenregistry/src/keys.rs b/contracts/wasm/tokenregistry/src/keys.rs deleted file mode 100644 index 4d155e37c3..0000000000 --- a/contracts/wasm/tokenregistry/src/keys.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -pub(crate) const IDX_PARAM_COLOR : usize = 0; -pub(crate) const IDX_PARAM_DESCRIPTION : usize = 1; -pub(crate) const IDX_PARAM_USER_DEFINED : usize = 2; - - -pub(crate) const IDX_STATE_COLOR_LIST : usize = 3; -pub(crate) const IDX_STATE_REGISTRY : usize = 4; - -pub const KEY_MAP_LEN: usize = 5; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ - PARAM_COLOR, - PARAM_DESCRIPTION, - PARAM_USER_DEFINED, - STATE_COLOR_LIST, - STATE_REGISTRY, -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} diff --git a/contracts/wasm/tokenregistry/src/lib.rs b/contracts/wasm/tokenregistry/src/lib.rs index 629e025911..23aa005839 100644 --- a/contracts/wasm/tokenregistry/src/lib.rs +++ b/contracts/wasm/tokenregistry/src/lib.rs @@ -10,34 +10,45 @@ use tokenregistry::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -use crate::keys::*; use crate::params::*; use crate::state::*; +use crate::structs::*; mod consts; mod contract; -mod keys; mod params; mod state; mod structs; + mod tokenregistry; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + FUNC_MINT_SUPPLY, + FUNC_TRANSFER_OWNERSHIP, + FUNC_UPDATE_METADATA, + VIEW_GET_INFO, + ], + funcs: &[ + func_mint_supply_thunk, + func_transfer_ownership_thunk, + func_update_metadata_thunk, + ], + views: &[ + view_get_info_thunk, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - let exports = ScExports::new(); - exports.add_func(FUNC_MINT_SUPPLY, func_mint_supply_thunk); - exports.add_func(FUNC_TRANSFER_OWNERSHIP, func_transfer_ownership_thunk); - exports.add_func(FUNC_UPDATE_METADATA, func_update_metadata_thunk); - exports.add_view(VIEW_GET_INFO, view_get_info_thunk); - - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } + ScExports::export(&EXPORT_MAP); } pub struct MintSupplyContext { @@ -48,12 +59,8 @@ pub struct MintSupplyContext { fn func_mint_supply_thunk(ctx: &ScFuncContext) { ctx.log("tokenregistry.funcMintSupply"); let f = MintSupplyContext { - params: ImmutableMintSupplyParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTokenRegistryState { - id: OBJ_ID_STATE, - }, + params: ImmutableMintSupplyParams { proxy: params_proxy() }, + state: MutableTokenRegistryState { proxy: state_proxy() }, }; func_mint_supply(ctx, &f); ctx.log("tokenregistry.funcMintSupply ok"); @@ -66,18 +73,14 @@ pub struct TransferOwnershipContext { fn func_transfer_ownership_thunk(ctx: &ScFuncContext) { ctx.log("tokenregistry.funcTransferOwnership"); + let f = TransferOwnershipContext { + params: ImmutableTransferOwnershipParams { proxy: params_proxy() }, + state: MutableTokenRegistryState { proxy: state_proxy() }, + }; // TODO the one who can transfer token ownership ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = TransferOwnershipContext { - params: ImmutableTransferOwnershipParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTokenRegistryState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.color().exists(), "missing mandatory color"); func_transfer_ownership(ctx, &f); ctx.log("tokenregistry.funcTransferOwnership ok"); @@ -90,18 +93,14 @@ pub struct UpdateMetadataContext { fn func_update_metadata_thunk(ctx: &ScFuncContext) { ctx.log("tokenregistry.funcUpdateMetadata"); + let f = UpdateMetadataContext { + params: ImmutableUpdateMetadataParams { proxy: params_proxy() }, + state: MutableTokenRegistryState { proxy: state_proxy() }, + }; // TODO the one who can change the token info ctx.require(ctx.caller() == ctx.contract_creator(), "no permission"); - let f = UpdateMetadataContext { - params: ImmutableUpdateMetadataParams { - id: OBJ_ID_PARAMS, - }, - state: MutableTokenRegistryState { - id: OBJ_ID_STATE, - }, - }; ctx.require(f.params.color().exists(), "missing mandatory color"); func_update_metadata(ctx, &f); ctx.log("tokenregistry.funcUpdateMetadata ok"); @@ -115,12 +114,8 @@ pub struct GetInfoContext { fn view_get_info_thunk(ctx: &ScViewContext) { ctx.log("tokenregistry.viewGetInfo"); let f = GetInfoContext { - params: ImmutableGetInfoParams { - id: OBJ_ID_PARAMS, - }, - state: ImmutableTokenRegistryState { - id: OBJ_ID_STATE, - }, + params: ImmutableGetInfoParams { proxy: params_proxy() }, + state: ImmutableTokenRegistryState { proxy: state_proxy() }, }; ctx.require(f.params.color().exists(), "missing mandatory color"); view_get_info(ctx, &f); diff --git a/contracts/wasm/tokenregistry/src/params.rs b/contracts/wasm/tokenregistry/src/params.rs index 324f58e091..4979e3097e 100644 --- a/contracts/wasm/tokenregistry/src/params.rs +++ b/contracts/wasm/tokenregistry/src/params.rs @@ -9,104 +9,100 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; - use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableMintSupplyParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableMintSupplyParams { pub fn description(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } pub fn user_defined(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_USER_DEFINED.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_USER_DEFINED)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableMintSupplyParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableMintSupplyParams { pub fn description(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } pub fn user_defined(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_USER_DEFINED.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_USER_DEFINED)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTransferOwnershipParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTransferOwnershipParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTransferOwnershipParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTransferOwnershipParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableUpdateMetadataParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableUpdateMetadataParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableUpdateMetadataParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableUpdateMetadataParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetInfoParams { pub fn color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetInfoParams { pub fn color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_COLOR)) } } diff --git a/contracts/wasm/tokenregistry/src/state.rs b/contracts/wasm/tokenregistry/src/state.rs index 786e448ff1..00431b229f 100644 --- a/contracts/wasm/tokenregistry/src/state.rs +++ b/contracts/wasm/tokenregistry/src/state.rs @@ -9,106 +9,103 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -use crate::structs::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfImmutableColor { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfImmutableColor { - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_color(&self, index: i32) -> ScImmutableColor { - ScImmutableColor::new(self.obj_id, Key32(index)) + pub fn get_color(&self, index: u32) -> ScImmutableColor { + ScImmutableColor::new(self.proxy.index(index)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToImmutableToken { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToImmutableToken { pub fn get_token(&self, key: &ScColor) -> ImmutableToken { - ImmutableToken { obj_id: self.obj_id, key_id: key.get_key_id() } + ImmutableToken { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTokenRegistryState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTokenRegistryState { pub fn color_list(&self) -> ArrayOfImmutableColor { - let arr_id = get_object_id(self.id, STATE_COLOR_LIST.get_key_id(), TYPE_ARRAY | TYPE_COLOR); - ArrayOfImmutableColor { obj_id: arr_id } + ArrayOfImmutableColor { proxy: self.proxy.root(STATE_COLOR_LIST) } } pub fn registry(&self) -> MapColorToImmutableToken { - let map_id = get_object_id(self.id, STATE_REGISTRY.get_key_id(), TYPE_MAP); - MapColorToImmutableToken { obj_id: map_id } + MapColorToImmutableToken { proxy: self.proxy.root(STATE_REGISTRY) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ArrayOfMutableColor { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl ArrayOfMutableColor { - pub fn clear(&self) { - clear(self.obj_id); + pub fn append_color(&self) -> ScMutableColor { + ScMutableColor::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); } - pub fn length(&self) -> i32 { - get_length(self.obj_id) + pub fn length(&self) -> u32 { + self.proxy.length() } - pub fn get_color(&self, index: i32) -> ScMutableColor { - ScMutableColor::new(self.obj_id, Key32(index)) + pub fn get_color(&self, index: u32) -> ScMutableColor { + ScMutableColor::new(self.proxy.index(index)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToMutableToken { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToMutableToken { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_token(&self, key: &ScColor) -> MutableToken { - MutableToken { obj_id: self.obj_id, key_id: key.get_key_id() } + MutableToken { proxy: self.proxy.key(&color_to_bytes(key)) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTokenRegistryState { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTokenRegistryState { pub fn as_immutable(&self) -> ImmutableTokenRegistryState { - ImmutableTokenRegistryState { id: self.id } + ImmutableTokenRegistryState { proxy: self.proxy.root("") } } pub fn color_list(&self) -> ArrayOfMutableColor { - let arr_id = get_object_id(self.id, STATE_COLOR_LIST.get_key_id(), TYPE_ARRAY | TYPE_COLOR); - ArrayOfMutableColor { obj_id: arr_id } + ArrayOfMutableColor { proxy: self.proxy.root(STATE_COLOR_LIST) } } pub fn registry(&self) -> MapColorToMutableToken { - let map_id = get_object_id(self.id, STATE_REGISTRY.get_key_id(), TYPE_MAP); - MapColorToMutableToken { obj_id: map_id } + MapColorToMutableToken { proxy: self.proxy.root(STATE_REGISTRY) } } } diff --git a/contracts/wasm/tokenregistry/src/structs.rs b/contracts/wasm/tokenregistry/src/structs.rs index 3fce40d7f1..0546a78af7 100644 --- a/contracts/wasm/tokenregistry/src/structs.rs +++ b/contracts/wasm/tokenregistry/src/structs.rs @@ -9,82 +9,79 @@ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; #[derive(Clone)] pub struct Token { - pub created : i64, // creation timestamp + pub created : u64, // creation timestamp pub description : String, // description what minted token represents pub minted_by : ScAgentID, // original minter pub owner : ScAgentID, // current owner - pub supply : i64, // amount of tokens originally minted - pub updated : i64, // last update timestamp + pub supply : u64, // amount of tokens originally minted + pub updated : u64, // last update timestamp pub user_defined : String, // any user defined text } impl Token { pub fn from_bytes(bytes: &[u8]) -> Token { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); Token { - created : decode.int64(), - description : decode.string(), - minted_by : decode.agent_id(), - owner : decode.agent_id(), - supply : decode.int64(), - updated : decode.int64(), - user_defined : decode.string(), + created : uint64_decode(&mut dec), + description : string_decode(&mut dec), + minted_by : agent_id_decode(&mut dec), + owner : agent_id_decode(&mut dec), + supply : uint64_decode(&mut dec), + updated : uint64_decode(&mut dec), + user_defined : string_decode(&mut dec), } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); - encode.int64(self.created); - encode.string(&self.description); - encode.agent_id(&self.minted_by); - encode.agent_id(&self.owner); - encode.int64(self.supply); - encode.int64(self.updated); - encode.string(&self.user_defined); - return encode.data(); + let mut enc = WasmEncoder::new(); + uint64_encode(&mut enc, self.created); + string_encode(&mut enc, &self.description); + agent_id_encode(&mut enc, &self.minted_by); + agent_id_encode(&mut enc, &self.owner); + uint64_encode(&mut enc, self.supply); + uint64_encode(&mut enc, self.updated); + string_encode(&mut enc, &self.user_defined); + enc.buf() } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableToken { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl ImmutableToken { pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn value(&self) -> Token { - Token::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Token::from_bytes(&self.proxy.get()) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableToken { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl MutableToken { pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } pub fn set_value(&self, value: &Token) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } pub fn value(&self) -> Token { - Token::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + Token::from_bytes(&self.proxy.get()) } } diff --git a/contracts/wasm/tokenregistry/src/tokenregistry.rs b/contracts/wasm/tokenregistry/src/tokenregistry.rs index 52058a4c8d..b3adf35eb6 100644 --- a/contracts/wasm/tokenregistry/src/tokenregistry.rs +++ b/contracts/wasm/tokenregistry/src/tokenregistry.rs @@ -9,8 +9,8 @@ use crate::structs::*; pub fn func_mint_supply(ctx: &ScFuncContext, f: &MintSupplyContext) { let minted = ctx.minted(); let minted_colors = minted.colors(); - ctx.require(minted_colors.length() == 1, "need single minted color"); - let minted_color = minted_colors.get_color(0).value(); + ctx.require(minted_colors.len() == 1, "need single minted color"); + let minted_color = minted_colors.get(0).unwrap(); let current_token = f.state.registry().get_token(&minted_color); if current_token.exists() { // should never happen, because transaction id is unique @@ -30,7 +30,7 @@ pub fn func_mint_supply(ctx: &ScFuncContext, f: &MintSupplyContext) { } current_token.set_value(&token); let color_list = f.state.color_list(); - color_list.get_color(color_list.length()).set_value(&minted_color); + color_list.append_color().set_value(&minted_color); } pub fn func_transfer_ownership(_ctx: &ScFuncContext, _f: &TransferOwnershipContext) { diff --git a/contracts/wasm/tokenregistry/test/tokenregistry_bg.wasm b/contracts/wasm/tokenregistry/test/tokenregistry_bg.wasm index 5791385713..7d2ee3035b 100644 Binary files a/contracts/wasm/tokenregistry/test/tokenregistry_bg.wasm and b/contracts/wasm/tokenregistry/test/tokenregistry_bg.wasm differ diff --git a/contracts/wasm/tokenregistry/test/tokenregistry_test.go b/contracts/wasm/tokenregistry/test/tokenregistry_test.go index 2583c11e6d..1fe41d8298 100644 --- a/contracts/wasm/tokenregistry/test/tokenregistry_test.go +++ b/contracts/wasm/tokenregistry/test/tokenregistry_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/iotaledger/wasp/contracts/wasm/tokenregistry/go/tokenregistry" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/consts.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/consts.ts index fd519a0bf0..c1db612bdc 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/consts.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "tokenregistry"; export const ScDescription = ""; -export const HScName = new wasmlib.ScHname(0xe1ba0c78); +export const HScName = new wasmtypes.ScHname(0xe1ba0c78); export const ParamColor = "color"; export const ParamDescription = "description"; @@ -23,7 +23,7 @@ export const FuncTransferOwnership = "transferOwnership"; export const FuncUpdateMetadata = "updateMetadata"; export const ViewGetInfo = "getInfo"; -export const HFuncMintSupply = new wasmlib.ScHname(0x564349a7); -export const HFuncTransferOwnership = new wasmlib.ScHname(0xbb9eb5af); -export const HFuncUpdateMetadata = new wasmlib.ScHname(0xa26b23b6); -export const HViewGetInfo = new wasmlib.ScHname(0xcfedba5f); +export const HFuncMintSupply = new wasmtypes.ScHname(0x564349a7); +export const HFuncTransferOwnership = new wasmtypes.ScHname(0xbb9eb5af); +export const HFuncUpdateMetadata = new wasmtypes.ScHname(0xa26b23b6); +export const HViewGetInfo = new wasmtypes.ScHname(0xcfedba5f); diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/contract.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/contract.ts index c0b4241dbc..2f30f7e9f2 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/contract.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/contract.ts @@ -10,66 +10,66 @@ import * as sc from "./index"; export class MintSupplyCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncMintSupply); - params: sc.MutableMintSupplyParams = new sc.MutableMintSupplyParams(); + params: sc.MutableMintSupplyParams = new sc.MutableMintSupplyParams(wasmlib.ScView.nilProxy); } export class MintSupplyContext { - params: sc.ImmutableMintSupplyParams = new sc.ImmutableMintSupplyParams(); - state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(); + params: sc.ImmutableMintSupplyParams = new sc.ImmutableMintSupplyParams(wasmlib.paramsProxy()); + state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(wasmlib.ScState.proxy()); } export class TransferOwnershipCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTransferOwnership); - params: sc.MutableTransferOwnershipParams = new sc.MutableTransferOwnershipParams(); + params: sc.MutableTransferOwnershipParams = new sc.MutableTransferOwnershipParams(wasmlib.ScView.nilProxy); } export class TransferOwnershipContext { - params: sc.ImmutableTransferOwnershipParams = new sc.ImmutableTransferOwnershipParams(); - state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(); + params: sc.ImmutableTransferOwnershipParams = new sc.ImmutableTransferOwnershipParams(wasmlib.paramsProxy()); + state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(wasmlib.ScState.proxy()); } export class UpdateMetadataCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncUpdateMetadata); - params: sc.MutableUpdateMetadataParams = new sc.MutableUpdateMetadataParams(); + params: sc.MutableUpdateMetadataParams = new sc.MutableUpdateMetadataParams(wasmlib.ScView.nilProxy); } export class UpdateMetadataContext { - params: sc.ImmutableUpdateMetadataParams = new sc.ImmutableUpdateMetadataParams(); - state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(); + params: sc.ImmutableUpdateMetadataParams = new sc.ImmutableUpdateMetadataParams(wasmlib.paramsProxy()); + state: sc.MutableTokenRegistryState = new sc.MutableTokenRegistryState(wasmlib.ScState.proxy()); } export class GetInfoCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetInfo); - params: sc.MutableGetInfoParams = new sc.MutableGetInfoParams(); + params: sc.MutableGetInfoParams = new sc.MutableGetInfoParams(wasmlib.ScView.nilProxy); } export class GetInfoContext { - params: sc.ImmutableGetInfoParams = new sc.ImmutableGetInfoParams(); - state: sc.ImmutableTokenRegistryState = new sc.ImmutableTokenRegistryState(); + params: sc.ImmutableGetInfoParams = new sc.ImmutableGetInfoParams(wasmlib.paramsProxy()); + state: sc.ImmutableTokenRegistryState = new sc.ImmutableTokenRegistryState(wasmlib.ScState.proxy()); } export class ScFuncs { - static mintSupply(ctx: wasmlib.ScFuncCallContext): MintSupplyCall { - let f = new MintSupplyCall(); - f.func.setPtrs(f.params, null); - return f; - } + static mintSupply(_ctx: wasmlib.ScFuncCallContext): MintSupplyCall { + const f = new MintSupplyCall(); + f.params = new sc.MutableMintSupplyParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } - static transferOwnership(ctx: wasmlib.ScFuncCallContext): TransferOwnershipCall { - let f = new TransferOwnershipCall(); - f.func.setPtrs(f.params, null); - return f; - } + static transferOwnership(_ctx: wasmlib.ScFuncCallContext): TransferOwnershipCall { + const f = new TransferOwnershipCall(); + f.params = new sc.MutableTransferOwnershipParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } - static updateMetadata(ctx: wasmlib.ScFuncCallContext): UpdateMetadataCall { - let f = new UpdateMetadataCall(); - f.func.setPtrs(f.params, null); - return f; - } + static updateMetadata(_ctx: wasmlib.ScFuncCallContext): UpdateMetadataCall { + const f = new UpdateMetadataCall(); + f.params = new sc.MutableUpdateMetadataParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } - static getInfo(ctx: wasmlib.ScViewCallContext): GetInfoCall { - let f = new GetInfoCall(); - f.func.setPtrs(f.params, null); - return f; - } + static getInfo(_ctx: wasmlib.ScViewCallContext): GetInfoCall { + const f = new GetInfoCall(); + f.params = new sc.MutableGetInfoParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } } diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/index.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/index.ts index ff035c3e66..0a315da2f8 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/index.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/index.ts @@ -9,7 +9,6 @@ export * from "./tokenregistry"; export * from "./consts"; export * from "./contract"; -export * from "./keys"; export * from "./lib"; export * from "./params"; export * from "./state"; diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/keys.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/keys.ts deleted file mode 100644 index 6e20801b3c..0000000000 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/keys.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export const IdxParamColor = 0; -export const IdxParamDescription = 1; -export const IdxParamUserDefined = 2; - - -export const IdxStateColorList = 3; -export const IdxStateRegistry = 4; - -export let keyMap: string[] = [ - sc.ParamColor, - sc.ParamDescription, - sc.ParamUserDefined, - sc.StateColorList, - sc.StateRegistry, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/lib.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/lib.ts index 48b2839424..80fb9baa2a 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/lib.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/lib.ts @@ -8,40 +8,45 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; +const exportMap: wasmlib.ScExportMap = { + names: [ + sc.FuncMintSupply, + sc.FuncTransferOwnership, + sc.FuncUpdateMetadata, + sc.ViewGetInfo, + ], + funcs: [ + funcMintSupplyThunk, + funcTransferOwnershipThunk, + funcUpdateMetadataThunk, + ], + views: [ + viewGetInfoThunk, + ], +}; + export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); - exports.addFunc(sc.FuncMintSupply, funcMintSupplyThunk); - exports.addFunc(sc.FuncTransferOwnership, funcTransferOwnershipThunk); - exports.addFunc(sc.FuncUpdateMetadata, funcUpdateMetadataThunk); - exports.addView(sc.ViewGetInfo, viewGetInfoThunk); - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } function funcMintSupplyThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("tokenregistry.funcMintSupply"); let f = new sc.MintSupplyContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; sc.funcMintSupply(ctx, f); ctx.log("tokenregistry.funcMintSupply ok"); } function funcTransferOwnershipThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("tokenregistry.funcTransferOwnership"); + let f = new sc.TransferOwnershipContext(); // TODO the one who can transfer token ownership ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.TransferOwnershipContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); sc.funcTransferOwnership(ctx, f); ctx.log("tokenregistry.funcTransferOwnership ok"); @@ -49,13 +54,11 @@ function funcTransferOwnershipThunk(ctx: wasmlib.ScFuncContext): void { function funcUpdateMetadataThunk(ctx: wasmlib.ScFuncContext): void { ctx.log("tokenregistry.funcUpdateMetadata"); + let f = new sc.UpdateMetadataContext(); // TODO the one who can change the token info ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission"); - let f = new sc.UpdateMetadataContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); sc.funcUpdateMetadata(ctx, f); ctx.log("tokenregistry.funcUpdateMetadata ok"); @@ -64,8 +67,6 @@ function funcUpdateMetadataThunk(ctx: wasmlib.ScFuncContext): void { function viewGetInfoThunk(ctx: wasmlib.ScViewContext): void { ctx.log("tokenregistry.viewGetInfo"); let f = new sc.GetInfoContext(); - f.params.mapID = wasmlib.OBJ_ID_PARAMS; - f.state.mapID = wasmlib.OBJ_ID_STATE; ctx.require(f.params.color().exists(), "missing mandatory color"); sc.viewGetInfo(ctx, f); ctx.log("tokenregistry.viewGetInfo ok"); diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/params.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/params.ts index 7307270773..96e5bb19e7 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/params.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/params.ts @@ -5,61 +5,61 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ImmutableMintSupplyParams extends wasmlib.ScMapID { - description(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); +export class ImmutableMintSupplyParams extends wasmtypes.ScProxy { + description(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamDescription)); } - userDefined(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamUserDefined)); + userDefined(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamUserDefined)); } } -export class MutableMintSupplyParams extends wasmlib.ScMapID { - description(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); +export class MutableMintSupplyParams extends wasmtypes.ScProxy { + description(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamDescription)); } - userDefined(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamUserDefined)); + userDefined(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamUserDefined)); } } -export class ImmutableTransferOwnershipParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableTransferOwnershipParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutableTransferOwnershipParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableTransferOwnershipParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } -export class ImmutableUpdateMetadataParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableUpdateMetadataParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutableUpdateMetadataParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableUpdateMetadataParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } -export class ImmutableGetInfoParams extends wasmlib.ScMapID { - color(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class ImmutableGetInfoParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamColor)); } } -export class MutableGetInfoParams extends wasmlib.ScMapID { - color(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamColor)); +export class MutableGetInfoParams extends wasmtypes.ScProxy { + color(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamColor)); } } diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/state.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/state.ts index 99141b917a..a3357d0dbf 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/state.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/state.ts @@ -5,99 +5,77 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; -export class ArrayOfImmutableColor { - objID: i32; +export class ArrayOfImmutableColor extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getColor(index: i32): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.objID, new wasmlib.Key32(index)); - } + getColor(index: u32): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.index(index)); + } } -export class MapColorToImmutableToken { - objID: i32; +export class MapColorToImmutableToken extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - getToken(key: wasmlib.ScColor): sc.ImmutableToken { - return new sc.ImmutableToken(this.objID, key.getKeyID()); - } + getToken(key: wasmtypes.ScColor): sc.ImmutableToken { + return new sc.ImmutableToken(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class ImmutableTokenRegistryState extends wasmlib.ScMapID { - colorList(): sc.ArrayOfImmutableColor { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateColorList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_COLOR); - return new sc.ArrayOfImmutableColor(arrID); +export class ImmutableTokenRegistryState extends wasmtypes.ScProxy { + colorList(): sc.ArrayOfImmutableColor { + return new sc.ArrayOfImmutableColor(this.proxy.root(sc.StateColorList)); } - registry(): sc.MapColorToImmutableToken { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateRegistry), wasmlib.TYPE_MAP); - return new sc.MapColorToImmutableToken(mapID); + registry(): sc.MapColorToImmutableToken { + return new sc.MapColorToImmutableToken(this.proxy.root(sc.StateRegistry)); } } -export class ArrayOfMutableColor { - objID: i32; +export class ArrayOfMutableColor extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } + appendColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.append()); + } - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } - getColor(index: i32): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.objID, new wasmlib.Key32(index)); - } + getColor(index: u32): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.index(index)); + } } -export class MapColorToMutableToken { - objID: i32; +export class MapColorToMutableToken extends wasmtypes.ScProxy { - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } - getToken(key: wasmlib.ScColor): sc.MutableToken { - return new sc.MutableToken(this.objID, key.getKeyID()); - } + getToken(key: wasmtypes.ScColor): sc.MutableToken { + return new sc.MutableToken(this.proxy.key(wasmtypes.colorToBytes(key))); + } } -export class MutableTokenRegistryState extends wasmlib.ScMapID { - asImmutable(): sc.ImmutableTokenRegistryState { - const imm = new sc.ImmutableTokenRegistryState(); - imm.mapID = this.mapID; - return imm; +export class MutableTokenRegistryState extends wasmtypes.ScProxy { + asImmutable(): sc.ImmutableTokenRegistryState { + return new sc.ImmutableTokenRegistryState(this.proxy); } - colorList(): sc.ArrayOfMutableColor { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateColorList), wasmlib.TYPE_ARRAY|wasmlib.TYPE_COLOR); - return new sc.ArrayOfMutableColor(arrID); + colorList(): sc.ArrayOfMutableColor { + return new sc.ArrayOfMutableColor(this.proxy.root(sc.StateColorList)); } - registry(): sc.MapColorToMutableToken { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.StateRegistry), wasmlib.TYPE_MAP); - return new sc.MapColorToMutableToken(mapID); + registry(): sc.MapColorToMutableToken { + return new sc.MapColorToMutableToken(this.proxy.root(sc.StateRegistry)); } } diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/structs.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/structs.ts index e7617740b3..02bb1c1cd2 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/structs.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/structs.ts @@ -5,84 +5,70 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export class Token { - created : i64 = 0; // creation timestamp - description : string = ""; // description what minted token represents - mintedBy : wasmlib.ScAgentID = new wasmlib.ScAgentID(); // original minter - owner : wasmlib.ScAgentID = new wasmlib.ScAgentID(); // current owner - supply : i64 = 0; // amount of tokens originally minted - updated : i64 = 0; // last update timestamp - userDefined : string = ""; // any user defined text + created : u64 = 0; // creation timestamp + description : string = ""; // description what minted token represents + mintedBy : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); // original minter + owner : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); // current owner + supply : u64 = 0; // amount of tokens originally minted + updated : u64 = 0; // last update timestamp + userDefined : string = ""; // any user defined text - static fromBytes(bytes: u8[]): Token { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new Token(); - data.created = decode.int64(); - data.description = decode.string(); - data.mintedBy = decode.agentID(); - data.owner = decode.agentID(); - data.supply = decode.int64(); - data.updated = decode.int64(); - data.userDefined = decode.string(); - decode.close(); - return data; - } + static fromBytes(buf: u8[]): Token { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new Token(); + data.created = wasmtypes.uint64Decode(dec); + data.description = wasmtypes.stringDecode(dec); + data.mintedBy = wasmtypes.agentIDDecode(dec); + data.owner = wasmtypes.agentIDDecode(dec); + data.supply = wasmtypes.uint64Decode(dec); + data.updated = wasmtypes.uint64Decode(dec); + data.userDefined = wasmtypes.stringDecode(dec); + dec.close(); + return data; + } - bytes(): u8[] { - return new wasmlib.BytesEncoder(). - int64(this.created). - string(this.description). - agentID(this.mintedBy). - agentID(this.owner). - int64(this.supply). - int64(this.updated). - string(this.userDefined). - data(); - } + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint64Encode(enc, this.created); + wasmtypes.stringEncode(enc, this.description); + wasmtypes.agentIDEncode(enc, this.mintedBy); + wasmtypes.agentIDEncode(enc, this.owner); + wasmtypes.uint64Encode(enc, this.supply); + wasmtypes.uint64Encode(enc, this.updated); + wasmtypes.stringEncode(enc, this.userDefined); + return enc.buf(); + } } -export class ImmutableToken { - objID: i32; - keyID: wasmlib.Key32; +export class ImmutableToken extends wasmtypes.ScProxy { - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } + exists(): bool { + return this.proxy.exists(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } - - value(): Token { - return Token.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Token { + return Token.fromBytes(this.proxy.get()); + } } -export class MutableToken { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class MutableToken extends wasmtypes.ScProxy { - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } - setValue(value: Token): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: Token): void { + this.proxy.set(value.bytes()); + } - value(): Token { - return Token.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): Token { + return Token.fromBytes(this.proxy.get()); + } } diff --git a/contracts/wasm/tokenregistry/ts/tokenregistry/tokenregistry.ts b/contracts/wasm/tokenregistry/ts/tokenregistry/tokenregistry.ts index ab1cb2a2c2..d5cf15e697 100644 --- a/contracts/wasm/tokenregistry/ts/tokenregistry/tokenregistry.ts +++ b/contracts/wasm/tokenregistry/ts/tokenregistry/tokenregistry.ts @@ -7,8 +7,8 @@ import * as sc from "./index"; export function funcMintSupply(ctx: wasmlib.ScFuncContext, f: sc.MintSupplyContext): void { let minted = ctx.minted(); let mintedColors = minted.colors(); - ctx.require(mintedColors.length() == 1, "need single minted color"); - let mintedColor = mintedColors.getColor(0).value(); + ctx.require(mintedColors.length == 1, "need single minted color"); + let mintedColor = mintedColors[0]; let currentToken = f.state.registry().getToken(mintedColor); if (currentToken.exists()) { // should never happen, because transaction id is unique @@ -27,7 +27,7 @@ export function funcMintSupply(ctx: wasmlib.ScFuncContext, f: sc.MintSupplyConte } currentToken.setValue(token); let colorList = f.state.colorList(); - colorList.getColor(colorList.length()).setValue(mintedColor); + colorList.appendColor().setValue(mintedColor); } export function funcTransferOwnership(ctx: wasmlib.ScFuncContext, f: sc.TransferOwnershipContext): void { diff --git a/documentation/docs/contribute.md b/documentation/docs/contribute.md index de1bc72b62..f53a3f8d60 100644 --- a/documentation/docs/contribute.md +++ b/documentation/docs/contribute.md @@ -25,16 +25,42 @@ Before creating the Pull Request ensure that: - all the tests pass: - ```bash + ```shell go test -tags rocksdb,builtin_static ./... ``` + or + + ```shell + make test + ``` + + If the changes are major, please run even the heavy tests: + + ```shell + make test-full + ``` + + Note, that these tests might take longer to run (they timeout after 60 minutes). Also note that `TestSpamOffledger` should only be run with `database.inMemory` set to `false`. See `tools/cluster/tests/spam_test.go` for details. + - there are no linting violations (instructions on how to setup linting below): - ```bash + ```shell golangci-lint run ``` + or + + ```shell + make lint + ``` + + Note, that linter is run each time you run + + ```shell + make + ``` + ### Lint Setup 1. Install golintci: diff --git a/documentation/docs/guide/chains_and_nodes/docker_standalone.md b/documentation/docs/guide/chains_and_nodes/docker_standalone.md index 0f2fd56038..bc32038d4e 100644 --- a/documentation/docs/guide/chains_and_nodes/docker_standalone.md +++ b/documentation/docs/guide/chains_and_nodes/docker_standalone.md @@ -1,15 +1,16 @@ --- -description: How to run a Wasp node in using Docker. Build the image, configure it, run it. +description: How to run a Wasp node in using Docker. Build the image, configure it, run it. image: /img/logo/WASP_logo_dark.png keywords: -- Smart Contracts -- Running a node -- docker -- image -- build -- configure -- arguments + - Smart Contracts + - Running a node + - docker + - image + - build + - configure + - arguments --- + # Docker (Standalone) This page describes the configuration of a single Wasp node in combination with Docker. If you followed the instructions in [Running a Node](running-a-node.md), you can skip to [Configuring wasp-cli](wasp-cli.md). @@ -20,19 +21,19 @@ This page describes the configuration of a single Wasp node in combination with Checkout the project, switch to 'develop' and build the main image: -``` -git clone -b develop https://github.com/iotaledger/wasp.git +```shell +git clone https://github.com/iotaledger/wasp.git cd wasp docker build -t wasp-node . ``` -The build process will copy the docker_config.json file into the image, which will be used when the node gets started. +The build process will copy the docker_config.json file into the image, which will be used when the node gets started. By default, the build process will use `-tags rocksdb,builtin_static` as a build argument. This argument can be modified with `--build-arg BUILD_TAGS=`. Depending on the use case, Wasp requires a different GoShimmer hostname which can be changed at this part inside the [docker_config.json](https://github.com/iotaledger/wasp/blob/develop/docker_config.json) file: -``` +```json "nodeconn": { "address": "goshimmer:5000" }, @@ -40,26 +41,26 @@ Depending on the use case, Wasp requires a different GoShimmer hostname which ca After the build process has finished, you can start your Wasp node by running: -``` +```shell docker run wasp-node ``` ### Configuration -After the build process has been completed, it is still possible to inject a different configuration file into a new container by running: +After the build process has been completed, it is still possible to inject a different configuration file into a new container by running: -``` +```shell docker run -v $(pwd)/alternative_docker_config.json:/etc/wasp_config.json wasp-node ``` You can also add further configuration using arguments: -``` -docker run wasp-node --nodeconn.address=alt_goshimmer:5000 +```shell +docker run wasp-node --nodeconn.address=alt_goshimmer:5000 ``` To get a list of all available arguments, run the node with the argument '--help' -``` +```shell docker run wasp-node --help ``` diff --git a/documentation/docs/guide/chains_and_nodes/running-a-node.md b/documentation/docs/guide/chains_and_nodes/running-a-node.md index 71f89d6936..6ecd3b6707 100644 --- a/documentation/docs/guide/chains_and_nodes/running-a-node.md +++ b/documentation/docs/guide/chains_and_nodes/running-a-node.md @@ -1,22 +1,23 @@ --- -description: How to run a node. Requirements, configuration parameters, dashboard configuration and tests. +description: How to run a node. Requirements, configuration parameters, dashboard configuration and tests. image: /img/logo/WASP_logo_dark.png keywords: -- Smart Contracts -- Running a node -- Go-lang -- GoShimmer -- Requirements -- Configuration -- Dashboard -- Grafana -- Prometheus + - Smart Contracts + - Running a node + - Go-lang + - GoShimmer + - Requirements + - Configuration + - Dashboard + - Grafana + - Prometheus --- # Running a Node -In the following section, you can find information on how to use Wasp by cloning the repository and building the application. -If you prefer, you can also configure a node [using a docker image (standalone)](docker_standalone.md) or [docker (preconfigured)](docker_preconfigured.md) (official images will be provided in the future). +In the following section, you can find information on how to use Wasp by cloning the repository and building the application. The instructions below will build both the Wasp node and the Wasp CLI to interact with the node from the command line. + +If you just want to run a Wasp node, you can also use the [Wasp standalone Docker image](docker_standalone.md) or a pre-configured local [Wasp and GoShimmer node setup using Docker Compose](../development_tools/docker_preconfigured.md). ## Requirements @@ -30,7 +31,7 @@ If you prefer, you can also configure a node [using a docker image (standalone)] - [Go 1.16](https://golang.org/doc/install) - [RocksDB](https://github.com/facebook/rocksdb/blob/master/INSTALL.md) - Access to a [GoShimmer](https://github.com/iotaledger/goshimmer) node for - production operation. + production operation. :::warning @@ -38,7 +39,7 @@ GoShimmer is a developing prototype, so some things are prone to break. For a sm ::: -:::info note +:::info note The Wasp node requires the Goshimmer node to have the [TXStream](https://github.com/iotaledger/goshimmer/tree/master/plugins/txstream) @@ -46,39 +47,64 @@ plugin enabled. Being an experimental plugin, it is currently disabled by defaul be enabled via configuration. ::: + ## Download Wasp You can get the source code of the latest Wasp version from the [official repository](https://github.com/iotaledger/wasp). -```bash +```shell git clone https://github.com/iotaledger/wasp ``` ## Compile -You can build and install both `wasp` and `wasp-cli` by running: +You can build and install both `wasp` and `wasp-cli` by running the following commands. + +:::info + +By default this will place the applications in `$HOME/go/bin` on Linux and Mac and `%USERPROFILE%/go/bin` on Windows. On Windows the Go installation should add this path automatically to your PATH environment variable. On Linux and Mac you can add this location to your PATH by adding the following line to your `$HOME/.profile`: + +```shell +export PATH=$PATH:$(go env GOPATH)/bin +``` + +Changes made to a profile file may not apply until the next time you log into your computer. To apply the changes immediately, just run the shell commands directly or execute them from the profile using a command such as `source $HOME/.profile`. + +::: + +:::note + +As an alternative you could run `make build` instead of `make install`, this would only build the applications and leave them in the repository directory. + +::: ### Linux/macOS -```bash +```shell make install ``` -### Microsoft Windows +### macOS arm64 (M1 Apple Silicon) -```bash -make install-windows +[`wasmtime-go`](https://github.com/bytecodealliance/wasmtime-go) hasn't supported macOS on arm64 yet, so you should build your own wasmtime library. You can follow the README in `wasmtime-go` to build the library. +Once a wasmtime library is built, then you can run the following commands. + +```shell +go mod edit -replace=github.com/bytecodealliance/wasmtime-go= +make install ``` -### Add to Path +### Microsoft Windows -It is recommendable to add `wasp` and `wasp-cli` to your PATH. Please follow the instructions specific to your OS to do this. +```shell +make install-windows +``` #### Microsoft Windows Installation Errors If the `make install-windows` command tells you it cannot find `gcc` you will need to install [MinGW-w64](https://sourceforge.net/projects/mingw-w64/).Make sure -to select *x86_64* architecture instead of the preselected *i686* +to select _x86_64_ architecture instead of the preselected _i686_ architecture during the installation process. After the installation make sure to add the following folder to your PATH variable: @@ -92,16 +118,17 @@ C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin You can run integration and unit test together with the following command: -```bash +```shell go test -tags rocksdb,builtin_static -timeout 20m ./... ``` + Keep in mind that this process may take several minutes. ### Run Unit Tests You can run the unit tests without running integration tests with the following command: -```bash +```shell go test -tags rocksdb,builtin_static -short ./... ``` @@ -110,7 +137,7 @@ This will take significantly less time than [running all tests](#run-all-tests). ## Configuration You can configure your node/s using the [`config.json`](https://github.com/iotaledger/wasp/blob/master/config.json) -configuration file. If you plan to run several nodes in the same host, you will need to adjust the port configuration. +configuration file. If you plan to run several nodes in the same host, you will need to adjust the port configuration. ### Peering @@ -143,25 +170,25 @@ can subscribe to these messages. Each Wasp node publishes important events via a [Nanomsg](https://nanomsg.org/) message stream (just like ZMQ is used in IRI). Possibly, in the future, [ZMQ](https://zeromq.org/) and [MQTT](https://mqtt.org/) publishers will be supported too. - Any Nanomsg client can subscribe to the message stream. In Go, you can use the - `packages/subscribe` package provided in Wasp for this. +Any Nanomsg client can subscribe to the message stream. In Go, you can use the +`packages/subscribe` package provided in Wasp for this. - The Publisher port can be configured in `config.json` with the `nanomsg.port` - setting. +The Publisher port can be configured in `config.json` with the `nanomsg.port` +setting. - The Message format is simply a string consisting of a space-separated list of tokens, and the first token - is the message type. Below is a list of all message types published by Wasp (you can search for - `publisher.Publish` in the code to see the exact places where each message is published). +The Message format is simply a string consisting of a space-separated list of tokens, and the first token +is the message type. Below is a list of all message types published by Wasp (you can search for +`publisher.Publish` in the code to see the exact places where each message is published). - |Message|Format| - |:--- |:--- | - |Chain record has been saved in the registry | `chainrec ` | - |Chain committee has been activated|`active_committee `| - |Chain committee dismissed|`dismissed_committee `| - |A new SC request reached the node|`request_in `| - |SC request has been processed (i.e. corresponding state update was confirmed)|`request_out `| - |State transition (new state has been committed to DB)| `state `| - |Event generated by a SC|`vmmsg ...`| +| Message | Format | +| :---------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------ | +| Chain record has been saved in the registry | `chainrec ` | +| Chain committee has been activated | `active_committee ` | +| Chain committee dismissed | `dismissed_committee ` | +| A new SC request reached the node | `request_in ` | +| SC request has been processed (i.e. corresponding state update was confirmed) | `request_out ` | +| State transition (new state has been committed to DB) | `state ` | +| Event generated by a SC | `vmmsg ...` | @@ -235,14 +262,22 @@ You can verify that your node is running by opening the dashboard with a web bro Repeat this process to launch as many nodes as you want for your committee. -### Accessing Your Node From a Remote Machine +### Accessing Your Node From a Remote Machine If you want to access the Wasp node from outside its local network, you will need to add your public IP to the `webpi.adminWhitelist`. You can do so by adding it to your config file, or running the node with the `webapi.adminWhitelist` flag. -```bash +```shell wasp --webapi.adminWhitelist=127.0.0.1,YOUR_IP ``` ## Video Tutorial - + diff --git a/documentation/docs/guide/chains_and_nodes/testnet.md b/documentation/docs/guide/chains_and_nodes/testnet.md index 99330bfd81..92b4cb5379 100644 --- a/documentation/docs/guide/chains_and_nodes/testnet.md +++ b/documentation/docs/guide/chains_and_nodes/testnet.md @@ -57,46 +57,46 @@ The testnet can be accessed via a series of endpoints that have been made availa You will need to initialize `wasp-cli` in order to create a seed that will be used to generate addresses. -``` +```shell wasp-cli init ``` Now we need to tell `wasp-cli` how to reach our GoShimmer node. -``` +```shell wasp-cli set goshimmer.api https://api.goshimmer.sc.iota.org ``` In order to deploy a smart contract you will need some funds. The wasp-cli tool makes this easy on our testnet. Run the following command to request some funds. -``` +```shell wasp-cli request-funds ``` We need to let _wasp-cli_ know how to reach _Wasp_ by configuring the API address. -``` +```shell wasp-cli set wasp.0.api https://api.wasp.sc.iota.org ``` -Now you need to set the chain ID in _wasp-cli_ so that the correct chain can be found. Yo can find the ChainID by navigating to the (chains)[https://wasp.sc.iota.org/chains] page of the wasp dashboard. Click on the ChainID of the chain you will be able to copy the ChainID from the next page. It will be formatted like `jaSDxeZNtum7kLuRg8oWQ6nXKgYjb3XVq7yiwnvtUG3C`. +Now you need to set the chain ID in _wasp-cli_ so that the correct chain can be found. Yo can find the ChainID by navigating to the [chains](https://wasp.sc.iota.org/chains) page of the wasp dashboard. Click on the ChainID of the chain you will be able to copy the ChainID from the next page. It will be formatted like `jaSDxeZNtum7kLuRg8oWQ6nXKgYjb3XVq7yiwnvtUG3C`. Use the ChainID to tell _wasp-cli_ which chain you want to interact with. -``` +```shell wasp-cli set chains.testchain jaSDxeZNtum7kLuRg8oWQ6nXKgYjb3XVq7yiwnvtUG3C wasp-cli set chain testchain ``` On the __testchain__ we have deployed a FairRoulette game that you can use to make sure your configuration is correct. -``` +```shell wasp-cli --verbose chain post-request fairroulete placeBet string number int 2 ``` For simplicity, here is the full set of commands to configure _wasp-cli_. -``` +```shell wasp-cli init wasp-cli set goshimmer.api https://api.goshimmer.sc.iota.org wasp-cli request-funds diff --git a/documentation/docs/guide/chains_and_nodes/wasp-cli.md b/documentation/docs/guide/chains_and_nodes/wasp-cli.md index d55984c240..6f38cbf87a 100644 --- a/documentation/docs/guide/chains_and_nodes/wasp-cli.md +++ b/documentation/docs/guide/chains_and_nodes/wasp-cli.md @@ -20,7 +20,7 @@ After going through the instructions on [Running a node](./running-a-node.md), y You can create a basic default configuration by running: -```bash +```shell wasp-cli init ```` @@ -41,7 +41,7 @@ wasp-cli set wasp.1.api 127.0.0.1:9091 wasp-cli set wasp.1.nanomsg 127.0.0.1:5551 wasp-cli set wasp.1.peering 127.0.0.1:4001 -... +...shell wasp-cli set wasp.N.api 127.0.0.1:9091 wasp-cli set wasp.N.nanomsg 127.0.0.1:5551 diff --git a/documentation/docs/guide/development_tools/docker_preconfigured.md b/documentation/docs/guide/development_tools/docker_preconfigured.md index b252b26ed5..fccf369e83 100644 --- a/documentation/docs/guide/development_tools/docker_preconfigured.md +++ b/documentation/docs/guide/development_tools/docker_preconfigured.md @@ -1,31 +1,32 @@ --- -description: How to run the preconfigured Docker setup. +description: How to run the preconfigured Docker setup. image: /img/logo/WASP_logo_dark.png keywords: -- ISCP -- Smart Contracts -- Running a node -- docker -- image -- build -- configure -- arguments -- GoShimmer + - ISCP + - Smart Contracts + - Running a node + - docker + - image + - build + - configure + - arguments + - GoShimmer --- + # Preconfigured Development Docker setup -This page describes the usage of the preconfigured developer Docker setup. +This page describes the usage of the preconfigured developer Docker setup. ## Introduction -To diminish the time spent on configuration and research, we have created a docker-compose setup that ships a preconfigured Wasp and GoShimmer (v0.7.7) node, that are connected with each other - ready to run out of the box. +To diminish the time spent on configuration and research, we have created a docker-compose setup that ships a pre-configured Wasp and GoShimmer (v0.7.7) node, that are connected with each other - ready to run out of the box. ## Running the setup -Checkout the project, switch to 'develop' and start with docker-compose: +Checkout the project and start with docker-compose: -``` -git clone -b develop https://github.com/iotaledger/wasp.git +```shell +git clone https://github.com/iotaledger/wasp.git cd tools/devnet docker-compose up ``` @@ -38,10 +39,10 @@ Wasp is configured to allow any connection coming from wasp-cli. This is fine fo Besides this, everything should simply work as expected. Faucet requests will be handled accordingly, you will be able to deploy and run smart contracts. All useful ports such as: -* Wasp Dashboard (7000) -* Wasp API (9090) -* GoShimmer Dashboard (8081) -* GoShimmer API (8080) +- Wasp Dashboard (7000) +- Wasp API (9090) +- GoShimmer Dashboard (8081) +- GoShimmer API (8080) are available to the local machine. @@ -49,7 +50,7 @@ are available to the local machine. As all ports are locally available, this `wasp-cli.json` configuration is to be used: -``` +```json { "goshimmer": { "api": "127.0.0.1:8080", @@ -73,4 +74,4 @@ See [Configuring wasp-cli](/smart-contracts/guide/chains_and_nodes/wasp-cli) for As GoShimmer runs as a standalone node, it establishes no connection to other GoShimmer nodes. Running it in this way is unusual, but fine for development purposes. Warnings about Tangle Time not synced or similar can be ignored. -GoShimmer keeps the tangle tips inside memory only and will lose it after a restart. To recover these tips from the database, a fork was required and is to be found [here](https://github.com/lmoe/goshimmer). It is included in this package. \ No newline at end of file +GoShimmer keeps the tangle tips inside memory only and will lose it after a restart. To recover these tips from the database, a fork was required and is to be found [here](https://github.com/lmoe/goshimmer). It is included in this package. diff --git a/documentation/docs/guide/evm/create-chain.md b/documentation/docs/guide/evm/create-chain.md index 57adfc6031..55e107ee17 100644 --- a/documentation/docs/guide/evm/create-chain.md +++ b/documentation/docs/guide/evm/create-chain.md @@ -30,7 +30,7 @@ If you don't have an IOTA Smart Contracts chain, you should create one. To do so In order to deploy the EVM chain contract, you need to have some IOTA locked on your newly created chain to fund that action. To do this, run: -```bash +```shell wasp-cli chain deposit IOTA:10000 ``` @@ -47,7 +47,7 @@ The most intuitive way to do this is by using [Metamask](https://metamask.io). I Once you have this, you are ready to deploy the EVM chain with the following command: -```bash +```shell wasp-cli chain evm deploy -a mychain --alloc 0x63c00c65BE86463491167eE26958a5A599BEbD2c:1000000000000000000000000 ``` * The `-a` parameter indicates the name of the chain that you want to deploy your EVM chain on top of. `mychain` in this case. @@ -63,7 +63,7 @@ In order to communicate with the EVM contract, you will need to run an additiona To run this server, run the following command: -```bash +```shell wasp-cli chain evm jsonrpc --chainid 1074 ``` diff --git a/documentation/docs/guide/evm/examples/ERC721.md b/documentation/docs/guide/evm/examples/ERC721.md new file mode 100644 index 0000000000..b2e50765ce --- /dev/null +++ b/documentation/docs/guide/evm/examples/ERC721.md @@ -0,0 +1,170 @@ +--- +title: ERC721 Example +keywords: +- IOTA +- Smart Contracts +- EVM +- Solidity +- ERC721 +- eip-721 +- token creation +- mint tokens +description: Create and deploy a Solidity smart contract to mint NFTs using the ERC721 standard. +image: /img/evm/ozw-721.png +--- +# ERC721 Example + +:::info note + +Please keep in mind that this is an EVM only NFT. It's not tied to L1 native assets. Also, these are different from L1 NFTs. + +::: + +Non-fungible tokens or NFTs are a type of token that can represent any unique object including a real world asset on a decentralised network. + + +## Prerequisites + +- What is a token? +- What is a blockchain? +- What are ERCs? +- What is an NFT? +- What is a smart contract? +- How to get started with Solidity? + + +## About ERC721 + +NFTs are most commonly represented with ([ERC721 standard](https://eips.ethereum.org/EIPS/eip-721)). You can use the openzepplin lib [`@openzeppelin/contracts/token/ERC721/ERC721.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol) to simplify. + +You can also use the ([OpenZepplin Contracts Wizard](https://wizard.openzeppelin.com/#erc721)) to generate and customize your smart contract. + +The following is an example NFT Smart Contract called "HuskyArt". + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.2; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; +import "@openzeppelin/contracts/utils/Counters.sol"; + +contract HuskyArt is ERC721, ERC721URIStorage, Ownable { + using Counters for Counters.Counter; + + Counters.Counter private _tokenIdCounter; + + constructor() ERC721("HuskyArt", "HSA") {} + + function _baseURI() internal pure override returns (string memory) { + return "https://example.com/nft/"; + } + + function safeMint(address to, string memory uri) public onlyOwner { + uint256 tokenId = _tokenIdCounter.current(); + _tokenIdCounter.increment(); + _safeMint(to, tokenId); + _setTokenURI(tokenId, uri); + } + + // The following functions are overrides required by Solidity. + + function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { + super._burn(tokenId); + } + + function tokenURI(uint256 tokenId) + public + view + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } +} +``` + +As you can see above, the contract uses standard methods for the most part. You should pay attention to the following: + +- `pragma solidity ^0.8.2;` This line means that the contract uses solidity compiler version 0.8.2 or above. +- `constructor() ERC721("HuskyArt", "HSA") {}` This defines the token name and symbol. You can name it whatever you want. We recommend that you use the same name for the token and the contract. +- `import "@openzeppelin/contracts/utils/Counters.sol";` This lib is used to create auto-incremental ids for the tokens. +- `return "https://example.com/nft/";` You should define the base URI of your NFTs will be. That means the URL you provide here will be used for all your tokens going forward. Since this contract uses auto-incremental token ids, your token URI will look something like `https://example.com/nft/0`, `https://example.com/nft/1`, `https://example.com/nft/2`, and so on. +- `function safeMint(address to, string memory uri) public onlyOwner {` is the safeMint function. This function will require that you manually input a token's `to` address and a `uri` every time you want to mint one. This should work for regular use-cases. +- `// SPDX-License-Identifier: MIT` This line specifies the license type. You do not need to worry about this for this example. If you want to keep it unlicensed, you replace it with `// SPDX-License-Identifier: Unlicensed`. + +![Open Zepplin Wizard](/img/evm/ozw-721.png) + +You can customize your contract further depending on how you would like it to behave. You should consider the following topics and questions: + +1. **Ownership** — Who owns it? How is it stored? +2. **Creation** — Method or Type of Creation. +3. **Transfer & Allowance** — How will tokens be transferred? How will they be available to other addresses and accounts? +4. **Burn** — Do you want to destroy it? If yes, how? + +You can click on **Copy to Clipboard** and paste it in the IDE of your choice, download it, or click on open in Remix directly. This example uses Remix. + + +## Compile + +Compile your Smart Contract to generate the ABI and Bytecode. + +![Remix Compile](/img/evm/remix-721.png) + +You can check `Auto Compile` so that you do not have to compile manually with every change you make. + +After you have successfully compiled your smart contract, you can proceed to [deploy it](#deploy). + + +## Deploy + +### Connect your IDE to the network where you want to deploy the smart contract. + +This example uses the [Remix IDE](https://remix.ethereum.org/) with [Metamask](https://metamask.io/) to handle this task. If you are using hardhat or truffle, you should customize the config file accordingly. + + +### Connect to the ISCP Testnet + + You can find instructions on this in the [devnet endpoints section](https://wiki.iota.org/smart-contracts/guide/chains_and_nodes/testnet#endpoints)).``` + +### Change the Environment to Injected Web3 + +After you have completed the prior steps, please select the `Injected Web3` network as pictured below. + +![Remix VM Select](/img/evm/remix-vm-injected.png) + +Wait for the IDE to sync. If it does not, please refresh and try again. + +## Select Your Smart Contract From the Dropdown + +### Select Your New Smart Contract + +Once you have [changed the environment to injected web3](#change-the-environment-to-injected-web3), you can proceed to select your Smart Contract from the dropdown. Ideally, you will see only one option here. However, since your contract imports quite a few libs, those may show up by default. + +![Remix Deploy](/img/evm/remix-721-deploy.png) + +### Deploy Your Contract + +Click on `Deploy`. This should open Metamask and ask you to sign the transaction. Please do so and wait for confirmation. + +![Remix Deployed](/img/evm/remix-deployed.png) + +If you see something like this, your contract is now deployed. You can also verify this on the explorer or explore more on Metamask. + +![Remix Deployed](/img/evm/remix-metamask-detail.png) + +:::note +The node which was used in this example has `0` gas fees. However, depending on which node you choose to deploy to, there may be some gas fees. +::: + + +## Possible Next Steps + +The above smart contract is generated by OpenZepplin Wizard and is good enough to be used in production environments. However, you may want more conditions or actions added to it. For example, you could add royalty for every transfer done after minting. + + +## Further Reading + +- [OpenZepplin 721 Standard](https://docs.openzeppelin.com/contracts/2.x/api/token/erc721) + diff --git a/documentation/docs/guide/evm/tooling.md b/documentation/docs/guide/evm/tooling.md index e90b4cd2fd..50b2560327 100644 --- a/documentation/docs/guide/evm/tooling.md +++ b/documentation/docs/guide/evm/tooling.md @@ -32,7 +32,7 @@ Re-using an existing Chain ID is not recommended and can be a security risk. For The Wasp CLI has some very basic functionalities to manage an EVM chain. Given the compatibility with existing tooling, only the basics are covered to get started with IOTA Smart Contracts and EVM. You can currently either run a JSON-RPC server, or deploy the EVM Chain itself on an IOTA Smart Contracts chain. To see the available options and configuration parameters simply run: -```bash +```shell wasp-cli chain evm ``` diff --git a/documentation/docs/guide/example_projects/fair_roulette.md b/documentation/docs/guide/example_projects/fair_roulette.md index 4713eae723..bdadc1d09b 100644 --- a/documentation/docs/guide/example_projects/fair_roulette.md +++ b/documentation/docs/guide/example_projects/fair_roulette.md @@ -131,7 +131,7 @@ All state changes such as the `round started` ,`round ended`, `placed bets`, and #### Building the Contract -``` +```shell cd contracts/wasm/fairroulette wasm-pack build ``` @@ -264,12 +264,12 @@ This means that to get a proper value from a view call, you should use `readUInt #### Install Dependencies 1. Go to your frontend directory ( contracts/wasm/fairroulette/frontend for example) - ```bash + ```shell cd contracts/wasm/fairroulette/frontend ``` 2. Install dependencies running: - ```bash + ```shell npm install ``` @@ -277,7 +277,7 @@ This means that to get a proper value from a view call, you should use `readUInt The frontend requires that you create a config file. You can copy the template from `contracts/wasm/fairroulette/frontend/config.dev.sample.js`, and rename it to `config.dev.js` inside the same folder. -```bash +```shell cp config.dev.sample.js config.dev.js ``` @@ -285,7 +285,7 @@ Make sure to update the config values according to your setup. The `chainId` is the chainId which gets defined after [deploying a chain](../chains_and_nodes/setting-up-a-chain.md#deploy-the-iscp-chain). You can get your chain id from your dashboard, or list all chains by running: -```bash +```shell wasp-cli chain list ``` @@ -297,7 +297,7 @@ wasp-cli chain list You can build the frontend by running the following commands: -```bash +```shell cd contracts/wasm/fairroulette/frontend npm run build_worker ``` @@ -313,7 +313,7 @@ You should follow the [Deployment](../chains_and_nodes/setting-up-a-chain.md#dep The deployment of a contract requires funds to be deposited to the **chain**. You can do this by executing the following command from the directory where your Wasp node was configured: -```bash +```shell wasp-cli chain deposit IOTA:10000 ``` @@ -321,6 +321,6 @@ Make sure to [Build](#building-the-contract) the contract before deploying it. Now, you can deploy the contract with a wasmtime configuration. -```bash +```shell wasp-cli chain deploy-contract wasmtime fairroulette "fairroulette" contracts/wasm/fairroulette/pkg/fairroulette_bg.wasm ``` diff --git a/documentation/docs/guide/schema/events.mdx b/documentation/docs/guide/schema/events.mdx index 8ea06c9848..cce5e03f72 100644 --- a/documentation/docs/guide/schema/events.mdx +++ b/documentation/docs/guide/schema/events.mdx @@ -118,7 +118,7 @@ FairRouletteEvents struct: ```go package fairroulette -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type FairRouletteEvents struct{} diff --git a/documentation/docs/guide/schema/funcdesc.mdx b/documentation/docs/guide/schema/funcdesc.mdx index 71f56c0a7d..bf27f3f601 100644 --- a/documentation/docs/guide/schema/funcdesc.mdx +++ b/documentation/docs/guide/schema/funcdesc.mdx @@ -37,7 +37,7 @@ in `contract.xx`: ```go package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" type DivideCall struct { Func *wasmlib.ScFunc diff --git a/documentation/docs/guide/schema/init.mdx b/documentation/docs/guide/schema/init.mdx index 9d6cb2297c..f2798f391f 100644 --- a/documentation/docs/guide/schema/init.mdx +++ b/documentation/docs/guide/schema/init.mdx @@ -57,7 +57,7 @@ first part of the Rust code that implements it, which contains the `'`init`'` fu //nolint:revive package dividend -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" // 'init' is used as a way to initialize a smart contract. It is an optional // function that will automatically be called upon contract deployment. In this diff --git a/documentation/docs/guide/schema/structs.mdx b/documentation/docs/guide/schema/structs.mdx index e1b44f52ca..f239b95296 100644 --- a/documentation/docs/guide/schema/structs.mdx +++ b/documentation/docs/guide/schema/structs.mdx @@ -86,7 +86,7 @@ struct: ```go package betting -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" type Bet struct { Amount int64 // bet amount @@ -311,7 +311,7 @@ The generated code in `state.xx` that implements the state interface is shown he ```go package betting -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" type ArrayOfImmutableBet struct { objID int32 diff --git a/documentation/docs/guide/schema/typedefs.mdx b/documentation/docs/guide/schema/typedefs.mdx index c757ea7058..744654ae50 100644 --- a/documentation/docs/guide/schema/typedefs.mdx +++ b/documentation/docs/guide/schema/typedefs.mdx @@ -76,7 +76,7 @@ The schema tool will generate the following proxies in `typedefs.xx`: ```go package betting -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" type ImmutableBettingRound = ArrayOfImmutableBet @@ -227,7 +227,7 @@ definition in `state.xx`: ```go package betting -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" type ArrayOfImmutableBettingRound struct { objID int32 diff --git a/documentation/docs/guide/schema/usage.mdx b/documentation/docs/guide/schema/usage.mdx index 22811f06d7..c04fbc211c 100644 --- a/documentation/docs/guide/schema/usage.mdx +++ b/documentation/docs/guide/schema/usage.mdx @@ -30,16 +30,16 @@ Once you know what your smart contract will be named, it is time to set up your Simply navigate to the central smart contract folder, and run the schema tool's initialization function: -```bash +```shell schema -init MySmartContract ``` This command will create a subfolder named `mysmartcontract` and generate an initial YAML -schema definition file inside this subfolder. B ecause a YAML file is easier to read and +schema definition file inside this subfolder. Because a YAML file is easier to read and edit manually, YAML is the default configuration file over JSON. If you prefer to use JSON instead, you can run the schema tool like this: -```bash +```shell schema -init MySmartContract -type=json ``` @@ -145,7 +145,7 @@ there to generate the initial code for the desired language: If you want to generate Go code, you should run the schema tool with the `-go` option like this: -```bash +```shell schema -go ``` @@ -155,7 +155,7 @@ schema -go If you want to generate Rust code, you should run the schema tool with the `-rust` option like this: -```bash +```shell schema -rust ``` @@ -165,7 +165,7 @@ schema -rust If you want to generate TypeScript code, you should run the schema tool with the `-ts` option like this: -```bash +```shell schema -ts ``` @@ -175,7 +175,7 @@ schema -ts If you want to generate more than one language your can simply specify multiple options. For example, to generate both Rust and Go code you would specify both options like this: -```bash +```shell schema -rust -go ``` @@ -195,7 +195,7 @@ that will compile successfully into a Wasm code file. You compile these as follo -```bash +```shell tinygo build -target wasm wasmmain/main.go ``` @@ -210,7 +210,7 @@ After generating the Rust code, you should first modify the Cargo.toml file to y liking, and potentially add the new project to a Rust workspace. Cargo.toml will not be regenerated once it already exists. Then build the code as follows: -```bash +```shell wasm-pack build ``` @@ -221,7 +221,7 @@ regenerated and overwritten whenever the schema tool is run again. -```bash +```shell asc lib.ts --binaryFile output_ts.wasm --lib path/to/node_modules ``` @@ -252,7 +252,7 @@ looks like this before you even start modifying it: ```go package mysmartcontract -import "github.com/iotaledger/wasp/packages/vm/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib" func funcInit(ctx wasmlib.ScFuncContext, f *InitContext) { diff --git a/documentation/static/img/evm/ozw-721.png b/documentation/static/img/evm/ozw-721.png new file mode 100644 index 0000000000..fc875e06c6 Binary files /dev/null and b/documentation/static/img/evm/ozw-721.png differ diff --git a/documentation/static/img/evm/remix-721-deploy.png b/documentation/static/img/evm/remix-721-deploy.png new file mode 100644 index 0000000000..fd877ac165 Binary files /dev/null and b/documentation/static/img/evm/remix-721-deploy.png differ diff --git a/documentation/static/img/evm/remix-721.png b/documentation/static/img/evm/remix-721.png new file mode 100644 index 0000000000..56a1a45344 Binary files /dev/null and b/documentation/static/img/evm/remix-721.png differ diff --git a/documentation/static/img/evm/remix-deployed.png b/documentation/static/img/evm/remix-deployed.png new file mode 100644 index 0000000000..1c0fa30d6f Binary files /dev/null and b/documentation/static/img/evm/remix-deployed.png differ diff --git a/documentation/static/img/evm/remix-metamask-detail.png b/documentation/static/img/evm/remix-metamask-detail.png new file mode 100644 index 0000000000..c01a6fa2bf Binary files /dev/null and b/documentation/static/img/evm/remix-metamask-detail.png differ diff --git a/documentation/static/img/evm/remix-vm-injected.png b/documentation/static/img/evm/remix-vm-injected.png new file mode 100644 index 0000000000..6d2e4c8e08 Binary files /dev/null and b/documentation/static/img/evm/remix-vm-injected.png differ diff --git a/documentation/static/img/multichain.png b/documentation/static/img/multichain.png index 39f64a2545..2c761f4586 100644 Binary files a/documentation/static/img/multichain.png and b/documentation/static/img/multichain.png differ diff --git a/documentation/static/img/tutorial/accounts.png b/documentation/static/img/tutorial/accounts.png index d2b586b1c6..e7f84c2032 100644 Binary files a/documentation/static/img/tutorial/accounts.png and b/documentation/static/img/tutorial/accounts.png differ diff --git a/documentation/temp/misc/runwasp.md b/documentation/temp/misc/runwasp.md index 7f2aa995ce..6be5ad9e71 100644 --- a/documentation/temp/misc/runwasp.md +++ b/documentation/temp/misc/runwasp.md @@ -15,6 +15,18 @@ $ cd wasp $ make install ``` +### macOS arm64 (M1 Apple Silicon) + +[`wasmtime-go`](https://github.com/bytecodealliance/wasmtime-go) hasn't supported macOS on arm64 yet, so you should build your own wasmtime library. You can follow the README in `wasmtime-go` to build the library. +Once a wasmtime library is built, then you can run the following commands. + +```shell +$ git clone https://github.com/iotaledger/wasp.git +$ cd wasp +$ go mod edit -replace=github.com/bytecodealliance/wasmtime-go= +$ make install +``` + ## Step 2: Run Goshimmer ### Option 1: follow the official docs diff --git a/documentation/tutorial-examples/Cargo.toml b/documentation/tutorial-examples/Cargo.toml index f8fe8d12c8..04d37ce45d 100644 --- a/documentation/tutorial-examples/Cargo.toml +++ b/documentation/tutorial-examples/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasmlib = { path = "../../packages/vm/wasmlib" } +wasmlib = { path = "../../packages/wasmvm/wasmlib" } #wasmlib = { git = "https://github.com/iotaledger/wasp", branch = "develop" } # The `console_error_panic_hook` crate provides better debugging of panics by diff --git a/documentation/tutorial-examples/src/lib.rs b/documentation/tutorial-examples/src/lib.rs index 4519d685cc..d06191a10b 100644 --- a/documentation/tutorial-examples/src/lib.rs +++ b/documentation/tutorial-examples/src/lib.rs @@ -6,13 +6,29 @@ use wasmlib::*; const PARAM_STRING: &str = "paramString"; const VAR_STRING: &str = "storedString"; +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ + "storeString", + "withdrawIota", + "getString", + ], + funcs: &[ + store_string, + withdraw_iota, + ], + views: &[ + get_string, + ], +}; + +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + #[no_mangle] fn on_load() { - // declare entry points of the smart contract - let exports = ScExports::new(); - exports.add_func("storeString", store_string); - exports.add_view("getString", get_string); - exports.add_func("withdrawIota", withdraw_iota); + ScExports::export(&EXPORT_MAP); } // storeString entry point stores a string provided as parameters @@ -20,14 +36,17 @@ fn on_load() { // panics if parameter is not provided fn store_string(ctx: &ScFuncContext) { // take parameter paramString - let par = ctx.params().get_string(PARAM_STRING); - // require parameter exists - ctx.require(par.exists(), "string parameter not found"); + let params = ctx.params(); + let param_string = string_to_bytes(PARAM_STRING); + ctx.require(params.exists(¶m_string), "string parameter not found"); + let state = ctx.raw_state(); // store the string in "storedString" variable - ctx.state().get_string(VAR_STRING).set_value(&par.value()); - // log the text - let msg = "Message stored: ".to_string() + &par.value(); + let var_string = string_to_bytes(VAR_STRING); + let value = params.get(¶m_string); + state.set(&var_string, &value); + // log the text + let msg = "Message stored: ".to_string() + &string_from_bytes(&value); ctx.log(&msg); } @@ -36,9 +55,14 @@ fn store_string(ctx: &ScFuncContext) { // the returned value in the result is under key 'paramString' fn get_string(ctx: &ScViewContext) { // take the stored string - let s = ctx.state().get_string(VAR_STRING).value(); + let state = ctx.raw_state(); + let var_string = string_to_bytes(VAR_STRING); + let value = state.get(&var_string); // return the string value in the result dictionary - ctx.results().get_string(PARAM_STRING).set_value(&s); + let results = ScDict::new(&[]); + let param_string = string_to_bytes(PARAM_STRING); + results.set(¶m_string, &value); + ctx.results(&results); } // withdraw_iota sends all iotas contained in the contract's account @@ -55,6 +79,6 @@ fn withdraw_iota(ctx: &ScFuncContext) { let bal = ctx.balances().balance(&ScColor::IOTA); if bal > 0 { - ctx.transfer_to_address(&caller.address(), ScTransfers::transfer(&ScColor::IOTA, bal)) + ctx.transfer_to_address(&caller.address(), ScTransfers::iotas(bal)) } } diff --git a/documentation/tutorial-examples/test/example_tutorial_bg.wasm b/documentation/tutorial-examples/test/example_tutorial_bg.wasm index ad488b5f96..9ae064b667 100644 Binary files a/documentation/tutorial-examples/test/example_tutorial_bg.wasm and b/documentation/tutorial-examples/test/example_tutorial_bg.wasm differ diff --git a/go.mod b/go.mod index b34c5c63e6..cdae78a49a 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/PuerkitoBio/goquery v1.6.1 github.com/anthdm/hbbft v0.0.0-20190702061856-0826ffdcf567 github.com/bygui86/multi-profile/v2 v2.1.0 - github.com/bytecodealliance/wasmtime-go v0.32.0 + github.com/bytecodealliance/wasmtime-go v0.34.0 github.com/ethereum/go-ethereum v1.10.10 github.com/iotaledger/goshimmer v0.7.5-0.20210811162925-25c827e8326a github.com/iotaledger/hive.go v0.0.0-20210625103722-68b2cf52ef4e @@ -24,7 +24,7 @@ require ( github.com/pangpanglabs/echoswagger/v2 v2.1.0 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.10.0 - github.com/second-state/WasmEdge-go v0.9.0 // indirect + github.com/second-state/WasmEdge-go v0.9.0 github.com/spf13/cobra v1.1.3 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.7.0 diff --git a/go.sum b/go.sum index bccf796c22..6ed3f6ab95 100644 --- a/go.sum +++ b/go.sum @@ -151,12 +151,10 @@ github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46f github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= github.com/bygui86/multi-profile/v2 v2.1.0 h1:x/jPqeL/6hJqLXoDI/H5zLPsSFbDR6IEbrBbFpkWQdw= github.com/bygui86/multi-profile/v2 v2.1.0/go.mod h1:f4qCZiQo1nnJdwbPoADUtdDXg3hhnpfgZ9iq3/kW4BA= -github.com/bytecodealliance/wasmtime-go v0.21.0 h1:8C6fNmpfzF6QQ9h0PCvGaYORhtgMvANCumafDPDmBSU= -github.com/bytecodealliance/wasmtime-go v0.21.0/go.mod h1:q320gUxqyI8yB+ZqRuaJOEnGkAnHh6WtJjMaT2CW4wI= -github.com/bytecodealliance/wasmtime-go v0.31.0 h1:AbMdV1pwjw/0Ito5yARcGzY366cq5NIiDk5vpy1c2Lw= -github.com/bytecodealliance/wasmtime-go v0.31.0/go.mod h1:q320gUxqyI8yB+ZqRuaJOEnGkAnHh6WtJjMaT2CW4wI= github.com/bytecodealliance/wasmtime-go v0.32.0 h1:/GsrnJz2bfULAIZygN4vUElLYliQrx/o/1opP9X7Gck= github.com/bytecodealliance/wasmtime-go v0.32.0/go.mod h1:q320gUxqyI8yB+ZqRuaJOEnGkAnHh6WtJjMaT2CW4wI= +github.com/bytecodealliance/wasmtime-go v0.34.0 h1:PaWS0DUusaXaU3aNoSYjag6WmuxjyPYBHgkrC4EXips= +github.com/bytecodealliance/wasmtime-go v0.34.0/go.mod h1:q320gUxqyI8yB+ZqRuaJOEnGkAnHh6WtJjMaT2CW4wI= github.com/c-bata/go-prompt v0.2.2/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= github.com/capossele/asset-registry v0.0.0-20210521112927-c9d6e74574e8/go.mod h1:BXwVCA0+rgYcMKC3vVkfjF+2nXYIYq3h/HndbaCuw08= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= @@ -578,8 +576,6 @@ github.com/influxdata/promql/v2 v2.12.0/go.mod h1:fxOPu+DY0bqCTCECchSRtWfc+0X19y github.com/influxdata/roaring v0.4.13-0.20180809181101-fc520f41fab6/go.mod h1:bSgUQ7q5ZLSO+bKBGqJiCBGAl+9DxyW63zLTujjUlOE= github.com/influxdata/tdigest v0.0.0-20181121200506-bf2b5ad3c0a9/go.mod h1:Js0mqiSBE6Ffsg94weZZ2c+v/ciT8QRHFOap7EKDrR0= github.com/influxdata/usage-client v0.0.0-20160829180054-6d3895376368/go.mod h1:Wbbw6tYNvwa5dlB6304Sd+82Z3f7PmVZHVKU637d4po= -github.com/iotaledger/goshimmer v0.7.5-0.20210811162925-25c827e8326a h1:JKIoZ7yxR8b0cLJY/vyKRj2lnEHlYCRkTvMz5V8OZfc= -github.com/iotaledger/goshimmer v0.7.5-0.20210811162925-25c827e8326a/go.mod h1:L4a9tQOOlD37go7UztwlCFMrNlmgwKK9ixaPf45A/8U= github.com/iotaledger/hive.go v0.0.0-20210625103722-68b2cf52ef4e h1:jUHV5HGa/1o9qoPPr8ms3dMueSVUb1ZB2Z1XyJ79qfU= github.com/iotaledger/hive.go v0.0.0-20210625103722-68b2cf52ef4e/go.mod h1:NyBg/Ny7FFAdDs59zdwTVoysU2ZbJVQnRwyLIDFKJYA= github.com/ipfs/go-cid v0.0.1/go.mod h1:GHWU/WuQdMPmIosc4Yn1bcCT7dSeX4lBafM7iqUPQvM= @@ -1294,10 +1290,6 @@ github.com/sasha-s/go-deadlock v0.2.0 h1:lMqc+fUb7RrFS3gQLtoQsJ7/6TV/pAIFvBsqX73 github.com/sasha-s/go-deadlock v0.2.0/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/second-state/WasmEdge-go v0.8.2 h1:dD5+ZKY9Vr+Ye5F9VZGP/WP2MnXfORQocUxXQvXUVE0= -github.com/second-state/WasmEdge-go v0.8.2/go.mod h1:Q3h79fwQs7GUSOm3ZzHXK+j4cKmCFP3SKpGfFNDtqD8= -github.com/second-state/WasmEdge-go v0.9.0-rc3 h1:Ol6KaPguuqyd42vb9W7VCRR4V92yZdVpqUh0MWD07Y4= -github.com/second-state/WasmEdge-go v0.9.0-rc3/go.mod h1:Q3h79fwQs7GUSOm3ZzHXK+j4cKmCFP3SKpGfFNDtqD8= github.com/second-state/WasmEdge-go v0.9.0 h1:CapdsNNP5HG8nIeX8qmRteie8SZC/+BkmNXq+IoQlKE= github.com/second-state/WasmEdge-go v0.9.0/go.mod h1:Q3h79fwQs7GUSOm3ZzHXK+j4cKmCFP3SKpGfFNDtqD8= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= diff --git a/packages/chain/chain.go b/packages/chain/chain.go index eb5dba9e7b..fe596d532b 100644 --- a/packages/chain/chain.go +++ b/packages/chain/chain.go @@ -64,6 +64,7 @@ type ChainRequests interface { type ChainMetrics interface { GetNodeConnectionMetrics() nodeconnmetrics.NodeConnectionMessagesMetrics GetConsensusWorkflowStatus() ConsensusWorkflowStatus + GetConsensusPipeMetrics() ConsensusPipeMetrics } type Chain interface { @@ -158,6 +159,7 @@ type Consensus interface { GetStatusSnapshot() *ConsensusInfo GetWorkflowStatus() ConsensusWorkflowStatus ShouldReceiveMissingRequest(req iscp.Request) bool + GetPipeMetrics() ConsensusPipeMetrics } type Mempool interface { @@ -229,6 +231,17 @@ type ConsensusWorkflowStatus interface { GetTransactionPostedTime() time.Time GetTransactionSeenTime() time.Time GetCompletedTime() time.Time + GetCurrentStateIndex() uint32 +} + +type ConsensusPipeMetrics interface { + GetEventStateTransitionMsgPipeSize() int + GetEventSignedResultMsgPipeSize() int + GetEventSignedResultAckMsgPipeSize() int + GetEventInclusionStateMsgPipeSize() int + GetEventACSMsgPipeSize() int + GetEventVMResultMsgPipeSize() int + GetEventTimerMsgPipeSize() int } type ReadyListRecord struct { diff --git a/packages/chain/chainimpl/metrics.go b/packages/chain/chainimpl/metrics.go index 2b5f338213..425d08be77 100644 --- a/packages/chain/chainimpl/metrics.go +++ b/packages/chain/chainimpl/metrics.go @@ -19,3 +19,10 @@ func (c *chainObj) GetConsensusWorkflowStatus() chain.ConsensusWorkflowStatus { } return c.consensus.GetWorkflowStatus() } + +func (c *chainObj) GetConsensusPipeMetrics() chain.ConsensusPipeMetrics { + if c.consensus == nil { + return nil + } + return c.consensus.GetPipeMetrics() +} diff --git a/packages/chain/consensus/action.go b/packages/chain/consensus/action.go index 0bba2ca6f3..9c802f6d24 100644 --- a/packages/chain/consensus/action.go +++ b/packages/chain/consensus/action.go @@ -345,6 +345,7 @@ func (c *consensus) checkQuorum() { // if it is not state controller rotation, sending message to state manager // Otherwise state manager is not notified c.writeToWAL() + c.workflow.setCurrentStateIndex(c.resultState.BlockIndex()) chainOutputID := chainOutput.ID() c.chain.StateCandidateToStateManager(c.resultState, chainOutputID) c.log.Debugf("checkQuorum: StateCandidateMsg sent for state index %v, approving output ID %v", @@ -679,7 +680,7 @@ func (c *consensus) resetWorkflow() { c.consensusBatch = nil c.contributors = nil c.resultSigAck = c.resultSigAck[:0] - c.workflow = newWorkflowStatus(c.stateOutput != nil) + c.workflow = newWorkflowStatus(c.stateOutput != nil, c.workflow.stateIndex) c.log.Debugf("Workflow reset") } diff --git a/packages/chain/consensus/consensus.go b/packages/chain/consensus/consensus.go index 2f13161618..38eb9fa14d 100644 --- a/packages/chain/consensus/consensus.go +++ b/packages/chain/consensus/consensus.go @@ -299,3 +299,15 @@ func (c *consensus) GetStatusSnapshot() *chain.ConsensusInfo { func (c *consensus) GetWorkflowStatus() chain.ConsensusWorkflowStatus { return c.workflow } + +func (c *consensus) GetPipeMetrics() chain.ConsensusPipeMetrics { + return &pipeMetrics{ + eventStateTransitionMsgPipeSize: c.eventStateTransitionMsgPipe.Len(), + eventSignedResultMsgPipeSize: c.eventSignedResultMsgPipe.Len(), + eventSignedResultAckMsgPipeSize: c.eventSignedResultAckMsgPipe.Len(), + eventInclusionStateMsgPipeSize: c.eventInclusionStateMsgPipe.Len(), + eventTimerMsgPipeSize: c.eventTimerMsgPipe.Len(), + eventVMResultMsgPipeSize: c.eventVMResultMsgPipe.Len(), + eventACSMsgPipeSize: c.eventACSMsgPipe.Len(), + } +} diff --git a/packages/chain/consensus/pipeMetrics.go b/packages/chain/consensus/pipeMetrics.go new file mode 100644 index 0000000000..7fe8907cc8 --- /dev/null +++ b/packages/chain/consensus/pipeMetrics.go @@ -0,0 +1,39 @@ +package consensus + +type pipeMetrics struct { + eventStateTransitionMsgPipeSize int + eventSignedResultMsgPipeSize int + eventSignedResultAckMsgPipeSize int + eventInclusionStateMsgPipeSize int + eventACSMsgPipeSize int + eventVMResultMsgPipeSize int + eventTimerMsgPipeSize int +} + +func (p *pipeMetrics) GetEventStateTransitionMsgPipeSize() int { + return p.eventStateTransitionMsgPipeSize +} + +func (p *pipeMetrics) GetEventSignedResultMsgPipeSize() int { + return p.eventSignedResultMsgPipeSize +} + +func (p *pipeMetrics) GetEventSignedResultAckMsgPipeSize() int { + return p.eventSignedResultAckMsgPipeSize +} + +func (p *pipeMetrics) GetEventInclusionStateMsgPipeSize() int { + return p.eventInclusionStateMsgPipeSize +} + +func (p *pipeMetrics) GetEventACSMsgPipeSize() int { + return p.eventACSMsgPipeSize +} + +func (p *pipeMetrics) GetEventVMResultMsgPipeSize() int { + return p.eventVMResultMsgPipeSize +} + +func (p *pipeMetrics) GetEventTimerMsgPipeSize() int { + return p.eventTimerMsgPipeSize +} diff --git a/packages/chain/consensus/workflow_status.go b/packages/chain/consensus/workflow_status.go index 65726d0178..106536b96b 100644 --- a/packages/chain/consensus/workflow_status.go +++ b/packages/chain/consensus/workflow_status.go @@ -28,14 +28,21 @@ type workflowStatus struct { timeTransactionPosted time.Time timeTransactionSeen time.Time timeCompleted time.Time + + stateIndex uint32 } var _ chain.ConsensusWorkflowStatus = &workflowStatus{} -func newWorkflowStatus(stateReceived bool) *workflowStatus { +func newWorkflowStatus(stateReceived bool, stateIndex ...uint32) *workflowStatus { + var i uint32 + if len(stateIndex) > 0 { + i = stateIndex[0] + } return &workflowStatus{ flagStateReceived: stateReceived, flagInProgress: stateReceived, + stateIndex: i, } } @@ -79,6 +86,10 @@ func (wsT *workflowStatus) setCompleted() { wsT.timeCompleted = time.Now() } +func (wsT *workflowStatus) setCurrentStateIndex(i uint32) { + wsT.stateIndex = i +} + func (wsT *workflowStatus) IsStateReceived() bool { return wsT.flagStateReceived } @@ -146,3 +157,7 @@ func (wsT *workflowStatus) GetTransactionSeenTime() time.Time { func (wsT *workflowStatus) GetCompletedTime() time.Time { return wsT.timeCompleted } + +func (wsT *workflowStatus) GetCurrentStateIndex() uint32 { + return wsT.stateIndex +} diff --git a/packages/dashboard/base.go b/packages/dashboard/base.go index 0248348832..1abe62150b 100644 --- a/packages/dashboard/base.go +++ b/packages/dashboard/base.go @@ -49,6 +49,7 @@ type WaspServices interface { GetChainNodeConnectionMetrics(*iscp.ChainID) (nodeconnmetrics.NodeConnectionMessagesMetrics, error) GetNodeConnectionMetrics() (nodeconnmetrics.NodeConnectionMetrics, error) GetChainConsensusWorkflowStatus(*iscp.ChainID) (chain.ConsensusWorkflowStatus, error) + GetChainConsensusPipeMetrics(*iscp.ChainID) (chain.ConsensusPipeMetrics, error) } type Dashboard struct { diff --git a/packages/dashboard/chainlist.go b/packages/dashboard/chainlist.go index 75ba816a10..3626ae4d2a 100644 --- a/packages/dashboard/chainlist.go +++ b/packages/dashboard/chainlist.go @@ -53,11 +53,17 @@ func (d *Dashboard) fetchChains() ([]*ChainOverview, error) { if err != nil { return nil, err } + var cmtSize int + if cmtInfo == nil { + cmtSize = -1 + } else { + cmtSize = len(cmtInfo.PeerStatus) + } r[i] = &ChainOverview{ ChainID: cr.ChainID, Active: cr.Active, RootInfo: rootInfo, - CommitteeSize: len(cmtInfo.PeerStatus), + CommitteeSize: cmtSize, Error: err, } } diff --git a/packages/dashboard/metrics_chain_consensus.go b/packages/dashboard/metrics_chain_consensus.go index 41c5ab7127..2d50bf8e59 100644 --- a/packages/dashboard/metrics_chain_consensus.go +++ b/packages/dashboard/metrics_chain_consensus.go @@ -1,4 +1,3 @@ -//nolint:dupl package dashboard import ( @@ -38,15 +37,21 @@ func (d *Dashboard) handleMetricsChainConsensus(c echo.Context) error { if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err) } + pipeMetrics, err := d.wasp.GetChainConsensusPipeMetrics(chainID) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, err) + } return c.Render(http.StatusOK, c.Path(), &MetricsChainConsensusTemplateParams{ BaseTemplateParams: d.BaseParams(c, metricsChainBreadcrumb(c.Echo(), chainID), tab), ChainID: chainID.Base58(), Status: status, + PipeMetrics: pipeMetrics, }) } type MetricsChainConsensusTemplateParams struct { BaseTemplateParams - ChainID string - Status chain.ConsensusWorkflowStatus + ChainID string + Status chain.ConsensusWorkflowStatus + PipeMetrics chain.ConsensusPipeMetrics } diff --git a/packages/dashboard/metrics_chain_nodeconn.go b/packages/dashboard/metrics_chain_nodeconn.go index b1c0cd88bc..3bcb0c6c1c 100644 --- a/packages/dashboard/metrics_chain_nodeconn.go +++ b/packages/dashboard/metrics_chain_nodeconn.go @@ -1,4 +1,3 @@ -//nolint:dupl package dashboard import ( diff --git a/packages/dashboard/mock_test.go b/packages/dashboard/mock_test.go index 7c274c7efe..53ad369c11 100644 --- a/packages/dashboard/mock_test.go +++ b/packages/dashboard/mock_test.go @@ -148,6 +148,10 @@ func (w *waspServicesMock) GetChainConsensusWorkflowStatus(chainID *iscp.ChainID panic("Not implemented") } +func (w *waspServicesMock) GetChainConsensusPipeMetrics(chainID *iscp.ChainID) (chain.ConsensusPipeMetrics, error) { + panic("Not implemented") +} + type dashboardTestEnv struct { wasp *waspServicesMock echo *echo.Echo diff --git a/packages/dashboard/templates/chainlist.tmpl b/packages/dashboard/templates/chainlist.tmpl index df232753b4..68f265b64e 100644 --- a/packages/dashboard/templates/chainlist.tmpl +++ b/packages/dashboard/templates/chainlist.tmpl @@ -20,7 +20,7 @@ {{ if not $c.Error }}{{ $id }}{{ else }}{{ $id }}{{ end }} {{ trim 50 $c.RootInfo.Description }} {{- if $c.Error }}
{{ $c.Error }}
{{ end }} - {{if not $c.Error}}{{ $c.CommitteeSize }}{{ end }} + {{if not $c.Error}}{{ if lt $c.CommitteeSize 0 }} N/A {{ else }} {{ $c.CommitteeSize }} {{ end }}{{ end }} {{if not $c.Error}}{{ len $c.RootInfo.Contracts }}{{ end }} {{ if $c.Active }} yes {{ else }} no {{ end }} diff --git a/packages/dashboard/templates/metrics.tmpl b/packages/dashboard/templates/metrics.tmpl index 8c5c429eb5..c8a138c676 100644 --- a/packages/dashboard/templates/metrics.tmpl +++ b/packages/dashboard/templates/metrics.tmpl @@ -10,7 +10,7 @@

Chain metrics

    {{range $_, $c := .Chains}} - {{ $id := $c.ChainRecord.ChainID.Base58 }} + {{ $id := $c.ChainID.Base58 }}
  • {{ $id }} {{template "metricsChainAll" (args $id)}} diff --git a/packages/dashboard/templates/metrics_chain_consensus.tmpl b/packages/dashboard/templates/metrics_chain_consensus.tmpl index ca40c2d5c7..dc69b12de5 100644 --- a/packages/dashboard/templates/metrics_chain_consensus.tmpl +++ b/packages/dashboard/templates/metrics_chain_consensus.tmpl @@ -2,62 +2,102 @@ {{define "body"}}
    -

    Workflow

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Flag nameStatusTriger time
    State received{{ template "booleanValue" (.Status.IsStateReceived) }}
    Batch proposal sent{{ template "booleanValue" (.Status.IsBatchProposalSent) }}{{ (formatTimestampOrNever (.Status.GetBatchProposalSentTime)) }}
    Consensus on batch reached{{ template "booleanValue" (.Status.IsConsensusBatchKnown) }}{{ (formatTimestampOrNever (.Status.GetConsensusBatchKnownTime)) }}
    Virtual machine started{{ template "booleanValue" (.Status.IsVMStarted) }}{{ (formatTimestampOrNever (.Status.GetVMStartedTime)) }}
    Virtual machine result signed{{ template "booleanValue" (.Status.IsVMResultSigned) }}{{ (formatTimestampOrNever (.Status.GetVMResultSignedTime)) }}
    Transaction finalized{{ template "booleanValue" (.Status.IsTransactionFinalized) }}{{ (formatTimestampOrNever (.Status.GetTransactionFinalizedTime)) }}
    Transaction posted to L1{{ template "booleanValue" (.Status.IsTransactionPosted) }}{{ (formatTimestampOrNever (.Status.GetTransactionPostedTime)) }}
    Transaction seen by L1{{ template "booleanValue" (.Status.IsTransactionSeen) }}{{ (formatTimestampOrNever (.Status.GetTransactionSeenTime)) }}
    Consensus is completed{{ template "booleanValue" (not (.Status.IsInProgress)) }}{{ (formatTimestampOrNever (.Status.GetCompletedTime)) }}
    + {{if (.Status) }} +

    Workflow

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Flag nameStatusTriger time
    State received{{ template "booleanValue" (.Status.IsStateReceived) }}
    Batch proposal sent{{ template "booleanValue" (.Status.IsBatchProposalSent) }}{{ (formatTimestampOrNever (.Status.GetBatchProposalSentTime)) }}
    Consensus on batch reached{{ template "booleanValue" (.Status.IsConsensusBatchKnown) }}{{ (formatTimestampOrNever (.Status.GetConsensusBatchKnownTime)) }}
    Virtual machine started{{ template "booleanValue" (.Status.IsVMStarted) }}{{ (formatTimestampOrNever (.Status.GetVMStartedTime)) }}
    Virtual machine result signed{{ template "booleanValue" (.Status.IsVMResultSigned) }}{{ (formatTimestampOrNever (.Status.GetVMResultSignedTime)) }}
    Transaction finalized{{ template "booleanValue" (.Status.IsTransactionFinalized) }}{{ (formatTimestampOrNever (.Status.GetTransactionFinalizedTime)) }}
    Transaction posted to L1{{ template "booleanValue" (.Status.IsTransactionPosted) }}{{ (formatTimestampOrNever (.Status.GetTransactionPostedTime)) }}
    Transaction seen by L1{{ template "booleanValue" (.Status.IsTransactionSeen) }}{{ (formatTimestampOrNever (.Status.GetTransactionSeenTime)) }}
    Consensus is completed{{ template "booleanValue" (not (.Status.IsInProgress)) }}{{ (formatTimestampOrNever (.Status.GetCompletedTime)) }}
    Current state index{{ .Status.GetCurrentStateIndex }}
    Event state transition message pipe size{{ .PipeMetrics.GetEventStateTransitionMsgPipeSize }}
    Event signed result msg pipe size{{ .PipeMetrics.GetEventSignedResultMsgPipeSize }}
    Event signed result ack message pipe size{{ .PipeMetrics.GetEventSignedResultAckMsgPipeSize }}
    Event inclusion state message pipe size{{ .PipeMetrics.GetEventInclusionStateMsgPipeSize }}
    Event vm result message pipe size{{ .PipeMetrics.GetEventVMResultMsgPipeSize }}
    Event timer message pipe size{{ .PipeMetrics.GetEventTimerMsgPipeSize }}
    + {{else}} +

    Warning

    +

    Consensus hasn't been started

    + {{end}}
    {{end}} diff --git a/packages/kv/collections/array16.go b/packages/kv/collections/array16.go index 2c19c8ecba..cdd5a8681f 100644 --- a/packages/kv/collections/array16.go +++ b/packages/kv/collections/array16.go @@ -1,4 +1,3 @@ -//nolint:dupl package collections import ( @@ -6,7 +5,6 @@ import ( "fmt" "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/util" ) // Array16 represents a dynamic array stored in a kv.KVStore @@ -37,27 +35,15 @@ func NewArray16ReadOnly(kvReader kv.KVStoreReader, name string) *ImmutableArray1 const array16ElemKeyCode = byte('#') -func (a *Array16) Immutable() *ImmutableArray16 { - return a.ImmutableArray16 -} - -func (a *ImmutableArray16) getSizeKey() kv.Key { - return array16SizeKey(a.name) -} - func array16SizeKey(name string) kv.Key { return kv.Key(name) } -func (a *ImmutableArray16) getArray16ElemKey(idx uint16) kv.Key { - return array16ElemKey(a.name, idx) -} - func array16ElemKey(name string, idx uint16) kv.Key { var buf bytes.Buffer buf.Write([]byte(name)) buf.WriteByte(array16ElemKeyCode) - _ = util.WriteUint16(&buf, idx) + buf.Write(uint16ToBytes(idx)) return kv.Key(buf.Bytes()) } @@ -73,11 +59,45 @@ func Array16RangeKeys(name string, length, from, to uint16) []kv.Key { return keys } +// use ULEB128 decoding so that WasmLib can use it as well +func bytesToUint16(buf []byte) uint16 { + if (buf[0] & 0x80) == 0 { + return uint16(buf[0]) + } + if (buf[1] & 0x80) == 0 { + return (uint16(buf[1]) << 7) | uint16(buf[0]&0x7f) + } + return (uint16(buf[2]) << 14) | (uint16(buf[1]&0x7f) << 7) | uint16(buf[0]&0x7f) +} + +// use ULEB128 encoding so that WasmLib can decode it as well +func uint16ToBytes(value uint16) []byte { + if value < 128 { + return []byte{byte(value)} + } + if value < 16384 { + return []byte{byte(value | 0x80), byte(value >> 7)} + } + return []byte{byte(value | 0x80), byte((value >> 7) | 0x80), byte(value >> 14)} +} + +func (a *Array16) Immutable() *ImmutableArray16 { + return a.ImmutableArray16 +} + +func (a *ImmutableArray16) getSizeKey() kv.Key { + return array16SizeKey(a.name) +} + +func (a *ImmutableArray16) getArray16ElemKey(idx uint16) kv.Key { + return array16ElemKey(a.name, idx) +} + func (a *Array16) setSize(n uint16) { if n == 0 { a.kvw.Del(a.getSizeKey()) } else { - a.kvw.Set(a.getSizeKey(), util.Uint16To2Bytes(n)) + a.kvw.Set(a.getSizeKey(), uint16ToBytes(n)) } } @@ -99,7 +119,7 @@ func (a *ImmutableArray16) Len() (uint16, error) { if v == nil { return 0, nil } - return util.MustUint16From2Bytes(v), nil + return bytesToUint16(v), nil } func (a *ImmutableArray16) MustLen() uint16 { diff --git a/packages/kv/collections/array32.go b/packages/kv/collections/array32.go index 436f947817..685822061a 100644 --- a/packages/kv/collections/array32.go +++ b/packages/kv/collections/array32.go @@ -1,4 +1,3 @@ -//nolint:dupl package collections import ( @@ -6,7 +5,6 @@ import ( "fmt" "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/util" ) // Array32 represents a dynamic array stored in a kv.KVStore @@ -37,27 +35,15 @@ func NewArray32ReadOnly(kvReader kv.KVStoreReader, name string) *ImmutableArray3 const array32ElemKeyCode = byte('#') -func (a *Array32) Immutable() *ImmutableArray32 { - return a.ImmutableArray32 -} - -func (a *ImmutableArray32) getSizeKey() kv.Key { - return array32SizeKey(a.name) -} - func array32SizeKey(name string) kv.Key { return kv.Key(name) } -func (a *ImmutableArray32) getArray32ElemKey(idx uint32) kv.Key { - return array32ElemKey(a.name, idx) -} - func array32ElemKey(name string, idx uint32) kv.Key { var buf bytes.Buffer buf.Write([]byte(name)) buf.WriteByte(array32ElemKeyCode) - _ = util.WriteUint32(&buf, idx) + buf.Write(uint32ToBytes(idx)) return kv.Key(buf.Bytes()) } @@ -73,11 +59,48 @@ func Array32RangeKeys(name string, length, from, to uint32) []kv.Key { return keys } +// use ULEB128 decoding so that WasmLib can use it as well +func bytesToUint32(buf []byte) uint32 { + value := uint32(buf[0] & 0x7f) + i := 0 + for s := 7; (buf[i] & 0x80) != 0; s += 7 { + i++ + value |= uint32(buf[i]&0x7f) << s + } + return value +} + +// use ULEB128 encoding so that WasmLib can decode it as well +func uint32ToBytes(value uint32) []byte { + buf := make([]byte, 0, 5) + b := byte(value) + value >>= 7 + for value != 0 { + buf = append(buf, b|0x80) + b = byte(value) + value >>= 7 + } + buf = append(buf, b) + return buf +} + +func (a *Array32) Immutable() *ImmutableArray32 { + return a.ImmutableArray32 +} + +func (a *ImmutableArray32) getSizeKey() kv.Key { + return array32SizeKey(a.name) +} + +func (a *ImmutableArray32) getArray32ElemKey(idx uint32) kv.Key { + return array32ElemKey(a.name, idx) +} + func (a *Array32) setSize(n uint32) { if n == 0 { a.kvw.Del(a.getSizeKey()) } else { - a.kvw.Set(a.getSizeKey(), util.Uint32To4Bytes(n)) + a.kvw.Set(a.getSizeKey(), uint32ToBytes(n)) } } @@ -99,7 +122,7 @@ func (a *ImmutableArray32) Len() (uint32, error) { if v == nil { return 0, nil } - return util.MustUint32From4Bytes(v), nil + return bytesToUint32(v), nil } func (a *ImmutableArray32) MustLen() uint32 { diff --git a/packages/solo/solo.go b/packages/solo/solo.go index b6607b1840..0330d31c27 100644 --- a/packages/solo/solo.go +++ b/packages/solo/solo.go @@ -33,7 +33,7 @@ import ( "github.com/iotaledger/wasp/packages/vm/runvm" _ "github.com/iotaledger/wasp/packages/vm/sandbox" "github.com/iotaledger/wasp/packages/vm/vmtypes" - "github.com/iotaledger/wasp/packages/vm/wasmproc" + "github.com/iotaledger/wasp/packages/wasmvm/wasmhost" "github.com/stretchr/testify/require" "go.uber.org/atomic" "go.uber.org/zap/zapcore" @@ -151,7 +151,7 @@ func NewWithLogger(t TestContext, log *logger.Logger, seedOpt ...*ed25519.Seed) processorConfig := processors.NewConfig() err := processorConfig.RegisterVMType(vmtypes.WasmTime, func(binary []byte) (iscp.VMProcessor, error) { - return wasmproc.GetProcessor(binary, log) + return wasmhost.GetProcessor(binary, log) }) require.NoError(t, err) diff --git a/packages/vm/core/governance/governanceimpl/chaininfo.go b/packages/vm/core/governance/governanceimpl/chaininfo.go index 8b2c8f3a64..aa8f81be36 100644 --- a/packages/vm/core/governance/governanceimpl/chaininfo.go +++ b/packages/vm/core/governance/governanceimpl/chaininfo.go @@ -40,7 +40,7 @@ func getChainInfo(ctx iscp.SandboxView) (dict.Dict, error) { // - ParamValidatorFee - int64 non-negative value of the contract fee. func setChainInfo(ctx iscp.Sandbox) (dict.Dict, error) { a := assert.NewAssert(ctx.Log()) - a.Require(governance.CheckAuthorizationByChainOwner(ctx.State(), ctx.Caller()), "governance.setContractFee: not authorized") + a.Require(governance.CheckAuthorizationByChainOwner(ctx.State(), ctx.Caller()), "governance.setChainInfo: not authorized") params := kvdecoder.New(ctx.Params(), ctx.Log()) diff --git a/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm b/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm index 4c5b2af584..354d8cdd06 100644 Binary files a/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm and b/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm differ diff --git a/packages/vm/wasmhost/kvstorehost.go b/packages/vm/wasmhost/kvstorehost.go deleted file mode 100644 index 98a2cd25da..0000000000 --- a/packages/vm/wasmhost/kvstorehost.go +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmhost - -import ( - "encoding/binary" - "fmt" - - "github.com/iotaledger/goshimmer/packages/ledgerstate" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/mr-tron/base58" -) - -// all type id values should exactly match their counterpart values on the client! - -//nolint:revive -const ( - OBJTYPE_ARRAY int32 = 0x20 - OBJTYPE_ARRAY16 int32 = 0x60 - OBJTYPE_CALL int32 = 0x80 - OBJTYPE_TYPEMASK int32 = 0x1f - - OBJTYPE_ADDRESS int32 = 1 - OBJTYPE_AGENT_ID int32 = 2 - OBJTYPE_BOOL int32 = 3 - OBJTYPE_BYTES int32 = 4 - OBJTYPE_CHAIN_ID int32 = 5 - OBJTYPE_COLOR int32 = 6 - OBJTYPE_HASH int32 = 7 - OBJTYPE_HNAME int32 = 8 - OBJTYPE_INT8 int32 = 9 - OBJTYPE_INT16 int32 = 10 - OBJTYPE_INT32 int32 = 11 - OBJTYPE_INT64 int32 = 12 - OBJTYPE_MAP int32 = 13 - OBJTYPE_REQUEST_ID int32 = 14 - OBJTYPE_STRING int32 = 15 - - OBJID_NULL int32 = 0 - OBJID_ROOT int32 = 1 - OBJID_STATE int32 = 2 - OBJID_PARAMS int32 = 3 - OBJID_RESULTS int32 = 4 -) - -// flag to indicate that this key id originally comes from a bytes key -// this allows us to display better readable tracing information -const KeyFromBytes int32 = 0x4000 - -var TypeSizes = [...]int{0, 33, 37, 1, 0, 33, 32, 32, 4, 1, 2, 4, 8, 0, 34, 0} - -type HostObject interface { - CallFunc(keyID int32, params []byte) []byte - DelKey(keyID, typeID int32) - Exists(keyID, typeID int32) bool - GetBytes(keyID, typeID int32) []byte - GetObjectID(keyID, typeID int32) int32 - GetTypeID(keyID int32) int32 - SetBytes(keyID, typeID int32, bytes []byte) -} - -// KvStoreHost implements WaspLib.client.ScHost interface -// it allows WasmGoVM to bypass Wasm and access the sandbox directly -// so that it is possible to debug into SC code that was written in Go -type KvStoreHost struct { - scKeys *KvStoreHost - keyIDToKey [][]byte - keyToKeyID map[string]int32 - objIDToObj []HostObject -} - -func (h *KvStoreHost) Init(scKeys *KvStoreHost) { - h.scKeys = scKeys - h.keyIDToKey = [][]byte{[]byte("")} - h.keyToKeyID = make(map[string]int32) - h.objIDToObj = make([]HostObject, 0, 16) -} - -func (h *KvStoreHost) CallFunc(objID, keyID int32, params []byte) []byte { - return h.FindObject(objID).CallFunc(keyID, params) -} - -func (h *KvStoreHost) DelKey(objID, keyID, typeID int32) { - h.FindObject(objID).DelKey(keyID, typeID) -} - -func (h *KvStoreHost) Exists(objID, keyID, typeID int32) bool { - return h.FindObject(objID).Exists(keyID, typeID) -} - -func (h *KvStoreHost) FindObject(objID int32) HostObject { - if objID < 0 || objID >= int32(len(h.objIDToObj)) { - h.Panicf("FindObject: invalid objID") - } - return h.objIDToObj[objID] -} - -func (h *KvStoreHost) GetBytes(objID, keyID, typeID int32) []byte { - obj := h.FindObject(objID) - if !obj.Exists(keyID, typeID) { - h.Tracef("GetBytes o%d k%d missing key", objID, keyID) - return nil - } - bytes := obj.GetBytes(keyID, typeID) - switch typeID { - case OBJTYPE_INT8: - val8, err := codec.DecodeInt8(bytes, 0) - if err != nil { - h.Panicf("GetBytes: invalid int8") - } - h.Tracef("GetBytes o%d k%d = %db", objID, keyID, val8) - case OBJTYPE_INT16: - val16, err := codec.DecodeInt16(bytes, 0) - if err != nil { - h.Panicf("GetBytes: invalid int16") - } - h.Tracef("GetBytes o%d k%d = %ds", objID, keyID, val16) - case OBJTYPE_INT32: - val32, err := codec.DecodeInt32(bytes, 0) - if err != nil { - h.Panicf("GetBytes: invalid int32") - } - h.Tracef("GetBytes o%d k%d = %di", objID, keyID, val32) - case OBJTYPE_INT64: - val64, err := codec.DecodeInt64(bytes, 0) - if err != nil { - h.Panicf("GetBytes: invalid int64") - } - h.Tracef("GetBytes o%d k%d = %dl", objID, keyID, val64) - case OBJTYPE_STRING: - h.Tracef("GetBytes o%d k%d = '%s'", objID, keyID, string(bytes)) - default: - h.Tracef("GetBytes o%d k%d = '%s'", objID, keyID, base58.Encode(bytes)) - } - return bytes -} - -func (h *KvStoreHost) getKeyFromID(keyID int32) []byte { - if keyID < 0 { - return predefinedKeys[-keyID] - } - - // find user-defined key - keyID &= ^KeyFromBytes - if h.scKeys != nil { - // get common SC user-defined keys count (skip null) - scKeysLen := int32(len(h.scKeys.keyIDToKey)) - 1 - - // find common SC user-defined key - if keyID <= scKeysLen { - return h.scKeys.keyIDToKey[keyID] - } - - // correct for SC keys count - keyID -= scKeysLen - } - - // user-defined key must be local - return h.keyIDToKey[keyID] -} - -func (h *KvStoreHost) GetKeyFromID(keyID int32) []byte { - h.TraceAllf("GetKeyFromID(k%d)", keyID) - key := h.getKeyFromID(keyID) - if (keyID & (KeyFromBytes | -0x80000000)) == KeyFromBytes { - // originally a byte slice key - h.Tracef("GetKeyFromID k%d='%s'", keyID, base58.Encode(key)) - return key - } - // originally a string key - h.Tracef("GetKeyFromID k%d='%s'", keyID, string(key)) - return key -} - -func (h *KvStoreHost) getKeyID(key []byte, fromBytes bool) int32 { - // cannot use []byte as key in maps - // so we will convert to (non-utf8) string - // most will have started out as string anyway - keyString := string(key) - - var scKeysLen int32 - if h.scKeys != nil { - // check common SC user-defined keys - keyID, ok := h.scKeys.keyToKeyID[keyString] - if ok { - return keyID - } - - // get common SC user-defined keys count (skip null) - scKeysLen = int32(len(h.scKeys.keyIDToKey)) - 1 - } - - // check local user-defined keys - keyID, ok := h.keyToKeyID[keyString] - if ok { - return keyID - } - - // unknown key, add it to local user-defined keys - keyID = int32(len(h.keyIDToKey)) + scKeysLen - if fromBytes { - keyID |= KeyFromBytes - } - h.keyToKeyID[keyString] = keyID - h.keyIDToKey = append(h.keyIDToKey, key) - return keyID -} - -func (h *KvStoreHost) GetKeyIDFromBytes(bytes []byte) int32 { - keyID := h.getKeyID(bytes, true) - h.Tracef("GetKeyIDFromBytes '%s'=k%d", base58.Encode(bytes), keyID) - return keyID -} - -func (h *KvStoreHost) GetKeyIDFromString(key string) int32 { - keyID := h.getKeyID([]byte(key), false) - h.Tracef("GetKeyIDFromString '%s'=k%d", key, keyID) - return keyID -} - -func (h *KvStoreHost) GetKeyStringFromID(keyID int32) string { - return string(h.GetKeyFromID(keyID)) -} - -func (h *KvStoreHost) GetObjectID(objID, keyID, typeID int32) int32 { - h.TraceAllf("GetObjectID(o%d,k%d,t%d)", objID, keyID, typeID) - subID := h.FindObject(objID).GetObjectID(keyID, typeID) - h.Tracef("GetObjectID o%d k%d t%d = o%d", objID, keyID, typeID, subID) - return subID -} - -func (h *KvStoreHost) Panicf(format string, args ...interface{}) { - err := fmt.Errorf(format, args...) - h.Tracef(err.Error()) - panic(err) -} - -func (h *KvStoreHost) SetBytes(objID, keyID, typeID int32, bytes []byte) { - h.FindObject(objID).SetBytes(keyID, typeID, bytes) - switch typeID { - case OBJTYPE_INT8: - val8, err := codec.DecodeInt8(bytes, 0) - if err != nil { - h.Panicf("SetBytes: invalid int8") - } - h.Tracef("SetBytes o%d k%d v=%db", objID, keyID, val8) - case OBJTYPE_INT16: - val16, err := codec.DecodeInt16(bytes, 0) - if err != nil { - h.Panicf("SetBytes: invalid int16") - } - h.Tracef("SetBytes o%d k%d v=%ds", objID, keyID, val16) - case OBJTYPE_INT32: - val32, err := codec.DecodeInt32(bytes, 0) - if err != nil { - h.Panicf("SetBytes: invalid int32") - } - h.Tracef("SetBytes o%d k%d v=%di", objID, keyID, val32) - case OBJTYPE_INT64: - val64, err := codec.DecodeInt64(bytes, 0) - if err != nil { - h.Panicf("SetBytes: invalid int64") - } - h.Tracef("SetBytes o%d k%d v=%dl", objID, keyID, val64) - case OBJTYPE_STRING: - if keyID != KeyTrace { - h.Tracef("SetBytes o%d k%d v='%s'", objID, keyID, string(bytes)) - } - default: - h.Tracef("SetBytes o%d k%d v='%s'", objID, keyID, base58.Encode(bytes)) - } -} - -func (h *KvStoreHost) Tracef(format string, a ...interface{}) { - if HostTracing { - text := fmt.Sprintf(format, a...) - h.SetBytes(OBJID_ROOT, KeyTrace, OBJTYPE_STRING, []byte(text)) - } -} - -func (h *KvStoreHost) TraceAllf(format string, a ...interface{}) { - if HostTracingAll { - h.Tracef(format, a...) - } -} - -func (h *KvStoreHost) TrackObject(obj HostObject) int32 { - objID := int32(len(h.objIDToObj)) - h.objIDToObj = append(h.objIDToObj, obj) - return objID -} - -func (h *KvStoreHost) TypeCheck(typeID int32, bytes []byte) { - typeSize := TypeSizes[typeID] - if typeSize != 0 && typeSize != len(bytes) { - h.Panicf("TypeCheck: invalid type size") - } - switch typeID { - case OBJTYPE_ADDRESS: - // address bytes must start with valid address type - if ledgerstate.AddressType(bytes[0]) > ledgerstate.AliasAddressType { - h.Panicf("TypeCheck: invalid address type") - } - case OBJTYPE_AGENT_ID: - // address bytes in agent id must start with valid address type - if ledgerstate.AddressType(bytes[0]) > ledgerstate.AliasAddressType { - h.Panicf("TypeCheck: invalid agent id address type") - } - case OBJTYPE_CHAIN_ID: - // chain id must be alias address - if ledgerstate.AddressType(bytes[0]) != ledgerstate.AliasAddressType { - h.Panicf("TypeCheck: invalid chain id address type") - } - case OBJTYPE_REQUEST_ID: - outputIndex := binary.LittleEndian.Uint16(bytes[ledgerstate.TransactionIDLength:]) - if outputIndex > ledgerstate.MaxOutputCount { - h.Panicf("TypeCheck: invalid request id output index") - } - } -} diff --git a/packages/vm/wasmhost/wasmhost.go b/packages/vm/wasmhost/wasmhost.go deleted file mode 100644 index 7e5145eacb..0000000000 --- a/packages/vm/wasmhost/wasmhost.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmhost - -import ( - "errors" - - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" -) - -type WasmStore interface { - GetKvStore(id int32) *KvStoreHost -} - -type WasmHost struct { - codeToFunc map[uint32]string - funcToCode map[string]uint32 - funcToIndex map[string]int32 - funcs []wasmlib.ScFuncContextFunction - views []wasmlib.ScViewContextFunction - store WasmStore - vm WasmVM -} - -func (host *WasmHost) AddFunc(f wasmlib.ScFuncContextFunction) []wasmlib.ScFuncContextFunction { - if f != nil { - host.funcs = append(host.funcs, f) - } - return host.funcs -} - -func (host *WasmHost) AddView(v wasmlib.ScViewContextFunction) []wasmlib.ScViewContextFunction { - if v != nil { - host.views = append(host.views, v) - } - return host.views -} - -func (host *WasmHost) getKvStore(id int32) *KvStoreHost { - return host.store.GetKvStore(id) -} - -func (host *WasmHost) InitVM(vm WasmVM, store WasmStore) error { - host.store = store - return vm.LinkHost(vm, host) -} - -func (host *WasmHost) Init() { - host.codeToFunc = make(map[uint32]string) - host.funcToCode = make(map[string]uint32) - host.funcToIndex = make(map[string]int32) -} - -func (host *WasmHost) FunctionFromCode(code uint32) string { - return host.codeToFunc[code] -} - -func (host *WasmHost) Instantiate() error { - return host.vm.Instantiate() -} - -func (host *WasmHost) IsView(function string) bool { - return (host.funcToIndex[function] & 0x8000) != 0 -} - -func (host *WasmHost) LoadWasm(wasmData []byte) error { - return host.vm.LoadWasm(wasmData) -} - -func (host *WasmHost) NewInstance() WasmVM { - return host.vm.NewInstance() -} - -func (host *WasmHost) RunFunction(functionName string, args ...interface{}) (err error) { - return host.vm.RunFunction(functionName, args...) -} - -func (host *WasmHost) RunScFunction(functionName string) (err error) { - index, ok := host.funcToIndex[functionName] - if !ok { - return errors.New("unknown SC function name: " + functionName) - } - return host.vm.RunScFunction(index) -} - -func (host *WasmHost) SetExport(index int32, functionName string) { - if index < 0 { - // double check that predefined keys are in sync - if index == KeyZzzzzzz { - return - } - panic("SetExport: predefined key value mismatch") - } - - funcIndex, ok := host.funcToIndex[functionName] - if ok { - if funcIndex != index { - panic("SetExport: duplicate function name") - } - return - } - - hn := iscp.Hn(functionName) - hashedName := uint32(hn) - _, ok = host.codeToFunc[hashedName] - if ok { - panic("SetExport: duplicate hashed name") - } - host.codeToFunc[hashedName] = functionName - host.funcToCode[functionName] = hashedName - host.funcToIndex[functionName] = index -} diff --git a/packages/vm/wasmhost/wasmkeys.go b/packages/vm/wasmhost/wasmkeys.go deleted file mode 100644 index c925cdb123..0000000000 --- a/packages/vm/wasmhost/wasmkeys.go +++ /dev/null @@ -1,108 +0,0 @@ -package wasmhost - -// all predefined key id values should exactly match their counterpart values on the client! -// note that predefined key ids are negative values to distinguish them from indexes -// this allows us to use them to initiate special functionality -// for example array[KeyLength] returns the array length - -const ( - KeyAccountID = int32(-1) - KeyAddress = int32(-2) - KeyBalances = int32(-3) - KeyBase58Decode = int32(-4) - KeyBase58Encode = int32(-5) - KeyBlsAddress = int32(-6) - KeyBlsAggregate = int32(-7) - KeyBlsValid = int32(-8) - KeyCall = int32(-9) - KeyCaller = int32(-10) - KeyChainID = int32(-11) - KeyChainOwnerID = int32(-12) - KeyColor = int32(-13) - KeyContract = int32(-14) - KeyContractCreator = int32(-15) - KeyDeploy = int32(-16) - KeyEd25519Address = int32(-17) - KeyEd25519Valid = int32(-18) - KeyEvent = int32(-19) - KeyExports = int32(-20) - KeyHashBlake2b = int32(-21) - KeyHashSha3 = int32(-22) - KeyHname = int32(-23) - KeyIncoming = int32(-24) - KeyLength = int32(-25) - KeyLog = int32(-26) - KeyMaps = int32(-27) - KeyMinted = int32(-28) - KeyPanic = int32(-29) - KeyParams = int32(-30) - KeyPost = int32(-31) - KeyRandom = int32(-32) - KeyRequestID = int32(-33) - KeyResults = int32(-34) - KeyReturn = int32(-35) - KeyState = int32(-36) - KeyTimestamp = int32(-37) - KeyTrace = int32(-38) - KeyTransfers = int32(-39) - KeyUtility = int32(-40) - - // KeyZzzzzzz is treated like a version number. - // When anything changes to the keys give this one a different value - // and make sure that the client side is updated accordingly - KeyZzzzzzz = int32(-41) -) - -// associate names with predefined key ids -var predefinedKeyMap = map[string]int32{ - "$accountID": KeyAccountID, - "$address": KeyAddress, - "$balances": KeyBalances, - "$base58Bytes": KeyBase58Decode, - "$base58String": KeyBase58Encode, - "$blsAddress": KeyBlsAddress, - "$blsAggregate": KeyBlsAggregate, - "$blsValid": KeyBlsValid, - "$call": KeyCall, - "$caller": KeyCaller, - "$chainID": KeyChainID, - "$chainOwnerID": KeyChainOwnerID, - "$color": KeyColor, - "$contract": KeyContract, - "$contractCreator": KeyContractCreator, - "$deploy": KeyDeploy, - "$ed25519Address": KeyEd25519Address, - "$ed25519Valid": KeyEd25519Valid, - "$event": KeyEvent, - "$exports": KeyExports, - "$hashBlake2b": KeyHashBlake2b, - "$hashSha3": KeyHashSha3, - "$hname": KeyHname, - "$incoming": KeyIncoming, - "$length": KeyLength, - "$log": KeyLog, - "$maps": KeyMaps, - "$minted": KeyMinted, - "$panic": KeyPanic, - "$params": KeyParams, - "$post": KeyPost, - "$random": KeyRandom, - "$requestID": KeyRequestID, - "$results": KeyResults, - "$return": KeyReturn, - "$state": KeyState, - "$timestamp": KeyTimestamp, - "$trace": KeyTrace, - "$transfers": KeyTransfers, - "$utility": KeyUtility, -} - -var predefinedKeys = initKeyMap() - -func initKeyMap() [][]byte { - keys := make([][]byte, len(predefinedKeyMap)+1) - for k, v := range predefinedKeyMap { - keys[-v] = []byte(k) - } - return keys -} diff --git a/packages/vm/wasmlib/go/wasmlib/bytes.go b/packages/vm/wasmlib/go/wasmlib/bytes.go deleted file mode 100644 index cb7fd62f4e..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/bytes.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -type BytesDecoder struct { - data []byte -} - -func NewBytesDecoder(data []byte) *BytesDecoder { - if len(data) == 0 { - panic("cannot decode empty byte array, use exist()") - } - return &BytesDecoder{data: data} -} - -func (d *BytesDecoder) Address() ScAddress { - return NewScAddressFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) AgentID() ScAgentID { - return NewScAgentIDFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) Bool() bool { - return d.Uint8() != 0 -} - -func (d *BytesDecoder) Bytes() []byte { - size := d.Uint32() - if uint32(len(d.data)) < size { - panic("insufficient bytes") - } - value := d.data[:size] - d.data = d.data[size:] - return value -} - -func (d *BytesDecoder) ChainID() ScChainID { - return NewScChainIDFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) Color() ScColor { - return NewScColorFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) Close() { - if len(d.data) != 0 { - panic("extra bytes") - } -} - -func (d *BytesDecoder) Hash() ScHash { - return NewScHashFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) Hname() ScHname { - return NewScHnameFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) Int8() int8 { - return int8(d.Uint8()) -} - -func (d *BytesDecoder) Int16() int16 { - return int16(d.leb128Decode(16)) -} - -func (d *BytesDecoder) Int32() int32 { - return int32(d.leb128Decode(32)) -} - -func (d *BytesDecoder) Int64() int64 { - return d.leb128Decode(64) -} - -// leb128 decoder -func (d *BytesDecoder) leb128Decode(bits int) int64 { - val := int64(0) - s := 0 - for { - if len(d.data) == 0 { - panic("insufficient bytes") - } - b := int8(d.data[0]) - d.data = d.data[1:] - val |= int64(b&0x7f) << s - if (b & -0x80) == 0 { - if int8(val>>s)&0x7f != b&0x7f { - panic("integer too large") - } - - // extend int7 sign to int8 - b |= (b & 0x40) << 1 - - // extend int8 sign to int64 - return val | (int64(b) << s) - } - s += 7 - if s >= bits { - panic("integer representation too long") - } - } -} - -func (d *BytesDecoder) RequestID() ScRequestID { - return NewScRequestIDFromBytes(d.Bytes()) -} - -func (d *BytesDecoder) String() string { - return string(d.Bytes()) -} - -func (d *BytesDecoder) Uint8() uint8 { - if len(d.data) == 0 { - panic("insufficient bytes") - } - value := d.data[0] - d.data = d.data[1:] - return value -} - -func (d *BytesDecoder) Uint16() uint16 { - return uint16(d.Int16()) -} - -func (d *BytesDecoder) Uint32() uint32 { - return uint32(d.Int32()) -} - -func (d *BytesDecoder) Uint64() uint64 { - return uint64(d.Int64()) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type BytesEncoder struct { - data []byte -} - -func NewBytesEncoder() *BytesEncoder { - return &BytesEncoder{data: make([]byte, 0, 128)} -} - -func (e *BytesEncoder) Address(value ScAddress) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) AgentID(value ScAgentID) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) Bool(value bool) *BytesEncoder { - if value { - return e.Uint8(1) - } - return e.Uint8(0) -} - -func (e *BytesEncoder) Bytes(value []byte) *BytesEncoder { - e.Uint32(uint32(len(value))) - e.data = append(e.data, value...) - return e -} - -func (e *BytesEncoder) ChainID(value ScChainID) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) Color(value ScColor) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) Data() []byte { - return e.data -} - -func (e *BytesEncoder) Hash(value ScHash) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) Hname(value ScHname) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) Int8(value int8) *BytesEncoder { - return e.Uint8(uint8(value)) -} - -func (e *BytesEncoder) Int16(value int16) *BytesEncoder { - return e.leb128Encode(int64(value)) -} - -func (e *BytesEncoder) Int32(value int32) *BytesEncoder { - return e.leb128Encode(int64(value)) -} - -func (e *BytesEncoder) Int64(value int64) *BytesEncoder { - return e.leb128Encode(value) -} - -// leb128 encoder -func (e *BytesEncoder) leb128Encode(value int64) *BytesEncoder { - for { - b := byte(value) - s := b & 0x40 - value >>= 7 - if (value == 0 && s == 0) || (value == -1 && s != 0) { - e.data = append(e.data, b&0x7f) - return e - } - e.data = append(e.data, b|0x80) - } -} - -func (e *BytesEncoder) RequestID(value ScRequestID) *BytesEncoder { - return e.Bytes(value.Bytes()) -} - -func (e *BytesEncoder) String(value string) *BytesEncoder { - return e.Bytes([]byte(value)) -} - -func (e *BytesEncoder) Uint8(value uint8) *BytesEncoder { - e.data = append(e.data, value) - return e -} - -func (e *BytesEncoder) Uint16(value uint16) *BytesEncoder { - return e.Int16(int16(value)) -} - -func (e *BytesEncoder) Uint32(value uint32) *BytesEncoder { - return e.Int32(int32(value)) -} - -func (e *BytesEncoder) Uint64(value uint64) *BytesEncoder { - return e.Int64(int64(value)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/context.go b/packages/vm/wasmlib/go/wasmlib/context.go deleted file mode 100644 index e3fd8571ad..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/context.go +++ /dev/null @@ -1,380 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// encapsulates standard host entities into a simple interface - -package wasmlib - -import ( - "encoding/binary" - "strconv" -) - -// used to retrieve any information that is related to colored token balances -type ScBalances struct { - balances ScImmutableMap -} - -// retrieve the balance for the specified token color -func (ctx ScBalances) Balance(color ScColor) int64 { - return ctx.balances.GetInt64(color).Value() -} - -// retrieve a list of all token colors that have a non-zero balance -func (ctx ScBalances) Colors() ScImmutableColorArray { - return ctx.balances.GetColorArray(KeyColor) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScTransfers struct { - transfers ScMutableMap -} - -// create a new transfers object ready to add token transfers -func NewScTransfers() ScTransfers { - return ScTransfers{transfers: *NewScMutableMap()} -} - -// create a new transfers object from a balances object -func NewScTransfersFromBalances(balances ScBalances) ScTransfers { - transfers := NewScTransfers() - colors := balances.Colors() - length := colors.Length() - for i := int32(0); i < length; i++ { - color := colors.GetColor(i).Value() - transfers.Set(color, balances.Balance(color)) - } - return transfers -} - -// create a new transfers object and initialize it with the specified amount of iotas -func NewScTransferIotas(amount int64) ScTransfers { - return NewScTransfer(IOTA, amount) -} - -// create a new transfers object and initialize it with the specified token transfer -func NewScTransfer(color ScColor, amount int64) ScTransfers { - transfer := NewScTransfers() - transfer.Set(color, amount) - return transfer -} - -// set the specified colored token transfer in the transfers object -// note that this will overwrite any previous amount for the specified color -func (ctx ScTransfers) Set(color ScColor, amount int64) { - ctx.transfers.GetInt64(color).SetValue(amount) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScUtility struct { - utility ScMutableMap -} - -// decodes the specified base58-encoded string value to its original bytes -func (ctx ScUtility) Base58Decode(value string) []byte { - return ctx.utility.CallFunc(KeyBase58Decode, []byte(value)) -} - -// encodes the specified bytes to a base-58-encoded string -func (ctx ScUtility) Base58Encode(value []byte) string { - return string(ctx.utility.CallFunc(KeyBase58Encode, value)) -} - -func (ctx ScUtility) BlsAddressFromPubKey(pubKey []byte) ScAddress { - result := ctx.utility.CallFunc(KeyBlsAddress, pubKey) - return NewScAddressFromBytes(result) -} - -func (ctx ScUtility) BlsAggregateSignatures(pubKeys, sigs [][]byte) ([]byte, []byte) { - encode := NewBytesEncoder() - encode.Int32(int32(len(pubKeys))) - for _, pubKey := range pubKeys { - encode.Bytes(pubKey) - } - encode.Int32(int32(len(sigs))) - for _, sig := range sigs { - encode.Bytes(sig) - } - result := ctx.utility.CallFunc(KeyBlsAggregate, encode.Data()) - decode := NewBytesDecoder(result) - return decode.Bytes(), decode.Bytes() -} - -func (ctx ScUtility) BlsValidSignature(data, pubKey, signature []byte) bool { - encode := NewBytesEncoder().Bytes(data).Bytes(pubKey).Bytes(signature) - result := ctx.utility.CallFunc(KeyBlsValid, encode.Data()) - return len(result) != 0 -} - -func (ctx ScUtility) Ed25519AddressFromPubKey(pubKey []byte) ScAddress { - result := ctx.utility.CallFunc(KeyEd25519Address, pubKey) - return NewScAddressFromBytes(result) -} - -func (ctx ScUtility) Ed25519ValidSignature(data, pubKey, signature []byte) bool { - encode := NewBytesEncoder().Bytes(data).Bytes(pubKey).Bytes(signature) - result := ctx.utility.CallFunc(KeyEd25519Valid, encode.Data()) - return len(result) != 0 -} - -// hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash -func (ctx ScUtility) HashBlake2b(value []byte) ScHash { - result := ctx.utility.CallFunc(KeyHashBlake2b, value) - return NewScHashFromBytes(result) -} - -// hashes the specified value bytes using sha3 hashing and returns the resulting 32-byte hash -func (ctx ScUtility) HashSha3(value []byte) ScHash { - result := ctx.utility.CallFunc(KeyHashSha3, value) - return NewScHashFromBytes(result) -} - -// hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash -func (ctx ScUtility) Hname(value string) ScHname { - result := ctx.utility.CallFunc(KeyHname, []byte(value)) - return NewScHnameFromBytes(result) -} - -// converts an integer to its string representation -func (ctx ScUtility) String(value int64) string { - return strconv.FormatInt(value, 10) -} - -// wrapper for simplified use by hashtypes -func base58Encode(bytes []byte) string { - return ScFuncContext{}.Utility().Base58Encode(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// shared interface part of ScFuncContext and ScViewContext -type ScBaseContext struct{} - -// retrieve the agent id of this contract account -func (ctx ScBaseContext) AccountID() ScAgentID { - return Root.GetAgentID(KeyAccountID).Value() -} - -// access the current balances for all token colors -func (ctx ScBaseContext) Balances() ScBalances { - return ScBalances{Root.GetMap(KeyBalances).Immutable()} -} - -// retrieve the chain id of the chain this contract lives on -func (ctx ScBaseContext) ChainID() ScChainID { - return Root.GetChainID(KeyChainID).Value() -} - -// retrieve the agent id of the owner of the chain this contract lives on -func (ctx ScBaseContext) ChainOwnerID() ScAgentID { - return Root.GetAgentID(KeyChainOwnerID).Value() -} - -// retrieve the hname of this contract -func (ctx ScBaseContext) Contract() ScHname { - return Root.GetHname(KeyContract).Value() -} - -// retrieve the agent id of the creator of this contract -func (ctx ScBaseContext) ContractCreator() ScAgentID { - return Root.GetAgentID(KeyContractCreator).Value() -} - -// logs informational text message -func (ctx ScBaseContext) Log(text string) { - Log(text) -} - -// logs error text message and then panics -func (ctx ScBaseContext) Panic(text string) { - Panic(text) -} - -// retrieve parameters passed to the smart contract function that was called -func (ctx ScBaseContext) Params() ScImmutableMap { - return Root.GetMap(KeyParams).Immutable() -} - -// panics if condition is not satisfied -func (ctx ScBaseContext) Require(cond bool, msg string) { - if !cond { - Panic(msg) - } -} - -// any results returned by the smart contract function call are returned here -func (ctx ScBaseContext) Results() ScMutableMap { - return Root.GetMap(KeyResults) -} - -// deterministic time stamp fixed at the moment of calling the smart contract -func (ctx ScBaseContext) Timestamp() int64 { - return Root.GetInt64(KeyTimestamp).Value() -} - -// logs debugging trace text message -func (ctx ScBaseContext) Trace(text string) { - Trace(text) -} - -// access diverse utility functions -func (ctx ScBaseContext) Utility() ScUtility { - return ScUtility{Root.GetMap(KeyUtility)} -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract interface with mutable access to state -type ScFuncContext struct { - ScBaseContext -} - -var _ ScFuncCallContext = &ScFuncContext{} - -// calls a smart contract function -func (ctx ScFuncContext) Call(hContract, hFunction ScHname, params *ScMutableMap, transfer *ScTransfers) ScImmutableMap { - encode := NewBytesEncoder() - encode.Hname(hContract) - encode.Hname(hFunction) - if params != nil { - encode.Int32(params.objID) - } else { - encode.Int32(0) - } - if transfer != nil { - encode.Int32(transfer.transfers.objID) - } else { - encode.Int32(0) - } - Root.GetBytes(KeyCall).SetValue(encode.Data()) - return Root.GetMap(KeyReturn).Immutable() -} - -// retrieve the agent id of the caller of the smart contract -func (ctx ScFuncContext) Caller() ScAgentID { - return Root.GetAgentID(KeyCaller).Value() -} - -// deploys a smart contract -func (ctx ScFuncContext) Deploy(programHash ScHash, name, description string, params *ScMutableMap) { - encode := NewBytesEncoder() - encode.Hash(programHash) - encode.String(name) - encode.String(description) - if params != nil { - encode.Int32(params.objID) - } else { - encode.Int32(0) - } - Root.GetBytes(KeyDeploy).SetValue(encode.Data()) -} - -// signals an event on the node that external entities can subscribe to -func (ctx ScFuncContext) Event(text string) { - Root.GetString(KeyEvent).SetValue(text) -} - -func (ctx ScFuncContext) Host() ScHost { - return nil -} - -// access the incoming balances for all token colors -func (ctx ScFuncContext) Incoming() ScBalances { - return ScBalances{Root.GetMap(KeyIncoming).Immutable()} -} - -func (ctx ScFuncContext) InitFuncCallContext() { -} - -func (ctx ScFuncContext) InitViewCallContext() { -} - -// retrieve the tokens that were minted in this transaction -func (ctx ScFuncContext) Minted() ScBalances { - return ScBalances{Root.GetMap(KeyMinted).Immutable()} -} - -// (delayed) posts a smart contract function -func (ctx ScFuncContext) Post(chainID ScChainID, hContract, hFunction ScHname, params *ScMutableMap, transfer ScTransfers, delay int32) { - encode := NewBytesEncoder() - encode.ChainID(chainID) - encode.Hname(hContract) - encode.Hname(hFunction) - if params != nil { - encode.Int32(params.objID) - } else { - encode.Int32(0) - } - encode.Int32(transfer.transfers.objID) - encode.Int32(delay) - Root.GetBytes(KeyPost).SetValue(encode.Data()) -} - -// TODO expose Entropy function - -// generates a random value from 0 to max (exclusive max) using a deterministic RNG -func (ctx ScFuncContext) Random(max int64) int64 { - if max == 0 { - ctx.Panic("random: max parameter should be non-zero") - } - state := ScMutableMap{objID: OBJ_ID_STATE} - rnd := state.GetBytes(KeyRandom) - seed := rnd.Value() - if len(seed) == 0 { - seed = Root.GetBytes(KeyRandom).Value() - } - rnd.SetValue(ctx.Utility().HashSha3(seed).Bytes()) - return int64(binary.LittleEndian.Uint64(seed[:8]) % uint64(max)) -} - -// retrieve the request id of this transaction -func (ctx ScFuncContext) RequestID() ScRequestID { - return Root.GetRequestID(KeyRequestID).Value() -} - -// access to mutable state storage -func (ctx ScFuncContext) State() ScMutableMap { - return Root.GetMap(KeyState) -} - -// transfer colored token amounts to the specified Tangle ledger address -func (ctx ScFuncContext) TransferToAddress(address ScAddress, transfer ScTransfers) { - transfers := Root.GetMapArray(KeyTransfers) - tx := transfers.GetMap(transfers.Length()) - tx.GetAddress(KeyAddress).SetValue(address) - tx.GetInt32(KeyBalances).SetValue(transfer.transfers.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract interface with immutable access to state -type ScViewContext struct { - ScBaseContext -} - -var _ ScViewCallContext = &ScViewContext{} - -// calls a smart contract function -func (ctx ScViewContext) Call(contract, function ScHname, params *ScMutableMap) ScImmutableMap { - encode := NewBytesEncoder() - encode.Hname(contract) - encode.Hname(function) - if params != nil { - encode.Int32(params.objID) - } else { - encode.Int32(0) - } - encode.Int32(0) - Root.GetBytes(KeyCall).SetValue(encode.Data()) - return Root.GetMap(KeyReturn).Immutable() -} - -func (ctx ScViewContext) InitViewCallContext() { -} - -// access to immutable state storage -func (ctx ScViewContext) State() ScImmutableMap { - return Root.GetMap(KeyState).Immutable() -} diff --git a/packages/vm/wasmlib/go/wasmlib/contract.go b/packages/vm/wasmlib/go/wasmlib/contract.go deleted file mode 100644 index 5fcb4a8637..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/contract.go +++ /dev/null @@ -1,177 +0,0 @@ -package wasmlib - -type ScFuncCallContext interface { - InitFuncCallContext() -} - -type ScViewCallContext interface { - InitViewCallContext() -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScView struct { - hContract ScHname - hFunction ScHname - paramsID *int32 - resultsID *int32 -} - -func NewScView(ctx ScViewCallContext, hContract, hFunction ScHname) *ScView { - ctx.InitViewCallContext() - return &ScView{hContract, hFunction, nil, nil} -} - -func (v *ScView) SetPtrs(paramsID, resultsID *int32) { - v.paramsID = paramsID - v.resultsID = resultsID - if paramsID != nil { - *paramsID = NewScMutableMap().MapID() - } -} - -func (v *ScView) Call() { - v.call(0) -} - -func (v *ScView) call(transferID int32) { - encode := NewBytesEncoder() - encode.Hname(v.hContract) - encode.Hname(v.hFunction) - encode.Int32(paramsID(v.paramsID)) - encode.Int32(transferID) - Root.GetBytes(KeyCall).SetValue(encode.Data()) - if v.resultsID != nil { - *v.resultsID = GetObjectID(OBJ_ID_ROOT, KeyReturn, TYPE_MAP) - } -} - -func (v *ScView) OfContract(hContract ScHname) *ScView { - v.hContract = hContract - return v -} - -func paramsID(id *int32) int32 { - if id == nil { - return 0 - } - return *id -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScInitFunc struct { - ScView - keys []Key - indexes []Key32 - oldIndexes []Key32 - host ScHost -} - -func NewScInitFunc(ctx ScFuncCallContext, hContract, hFunction ScHname, keys []Key, indexes []Key32) *ScInitFunc { - f := &ScInitFunc{} - f.hContract = hContract - f.hFunction = hFunction - if ctx != nil { - ctx.InitFuncCallContext() - return f - } - - // Special initialization for SoloContext usage - // Note that we do not have a contract context that can talk to the host - // until *after* deployment of the contract, so we cannot use the normal - // params proxy to pass parameters because it does not exist yet. - // Instead, we use a special temporary host implementation that knows - // just enough to gather the parameter data and pass it correctly to - // solo's contract deployment function, which in turn passes it to the - // contract's init() function - f.keys = keys - f.oldIndexes = append(f.oldIndexes, indexes...) - f.indexes = indexes - for i := 0; i < len(indexes); i++ { - indexes[i] = Key32(i) - } - f.host = ConnectHost(NewInitHost()) - return f -} - -func (f *ScInitFunc) Call() { - Panic("cannot call init") -} - -func (f *ScInitFunc) OfContract(hContract ScHname) *ScInitFunc { - f.hContract = hContract - return f -} - -func (f *ScInitFunc) Params() []interface{} { - if f.keys == nil { - Panic("cannot call params") - } - - var params []interface{} - for k, v := range host.(*InitHost).params { - params = append(params, string(f.keys[k])) - params = append(params, v) - } - copy(f.indexes, f.oldIndexes) - ConnectHost(f.host) - return params -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScFunc struct { - ScView - delay int32 - transferID int32 -} - -func NewScFunc(ctx ScFuncCallContext, hContract, hFunction ScHname) *ScFunc { - ctx.InitFuncCallContext() - return &ScFunc{ScView{hContract, hFunction, nil, nil}, 0, 0} -} - -func (f *ScFunc) Call() { - if f.delay != 0 { - Panic("cannot delay a call") - } - f.call(f.transferID) -} - -func (f *ScFunc) Delay(seconds int32) *ScFunc { - f.delay = seconds - return f -} - -func (f *ScFunc) OfContract(hContract ScHname) *ScFunc { - f.hContract = hContract - return f -} - -func (f *ScFunc) Post() { - f.PostToChain(Root.GetChainID(KeyChainID).Value()) -} - -func (f *ScFunc) PostToChain(chainID ScChainID) { - encode := NewBytesEncoder() - encode.ChainID(chainID) - encode.Hname(f.hContract) - encode.Hname(f.hFunction) - encode.Int32(paramsID(f.paramsID)) - encode.Int32(f.transferID) - encode.Int32(f.delay) - Root.GetBytes(KeyPost).SetValue(encode.Data()) - if f.resultsID != nil { - *f.resultsID = GetObjectID(OBJ_ID_ROOT, KeyReturn, TYPE_MAP) - } -} - -func (f *ScFunc) Transfer(transfer ScTransfers) *ScFunc { - f.transferID = transfer.transfers.MapID() - return f -} - -func (f *ScFunc) TransferIotas(amount int64) *ScFunc { - return f.Transfer(NewScTransferIotas(amount)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreaccounts/params.go b/packages/vm/wasmlib/go/wasmlib/coreaccounts/params.go deleted file mode 100644 index 9c17692cec..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreaccounts/params.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreaccounts - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableDepositParams struct { - id int32 -} - -func (s ImmutableDepositParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} - -type MutableDepositParams struct { - id int32 -} - -func (s MutableDepositParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} - -type ImmutableHarvestParams struct { - id int32 -} - -func (s ImmutableHarvestParams) WithdrawAmount() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamWithdrawAmount)) -} - -func (s ImmutableHarvestParams) WithdrawColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamWithdrawColor)) -} - -type MutableHarvestParams struct { - id int32 -} - -func (s MutableHarvestParams) WithdrawAmount() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamWithdrawAmount)) -} - -func (s MutableHarvestParams) WithdrawColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamWithdrawColor)) -} - -type ImmutableBalanceParams struct { - id int32 -} - -func (s ImmutableBalanceParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} - -type MutableBalanceParams struct { - id int32 -} - -func (s MutableBalanceParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} - -type ImmutableGetAccountNonceParams struct { - id int32 -} - -func (s ImmutableGetAccountNonceParams) AgentID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} - -type MutableGetAccountNonceParams struct { - id int32 -} - -func (s MutableGetAccountNonceParams) AgentID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamAgentID)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreaccounts/results.go b/packages/vm/wasmlib/go/wasmlib/coreaccounts/results.go deleted file mode 100644 index 2dd3a316ec..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreaccounts/results.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreaccounts - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type MapAgentIDToImmutableBytes struct { - objID int32 -} - -func (m MapAgentIDToImmutableBytes) GetBytes(key wasmlib.ScAgentID) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(m.objID, key.KeyID()) -} - -type ImmutableAccountsResults struct { - id int32 -} - -func (s ImmutableAccountsResults) Agents() MapAgentIDToImmutableBytes { - return MapAgentIDToImmutableBytes{objID: s.id} -} - -type MapAgentIDToMutableBytes struct { - objID int32 -} - -func (m MapAgentIDToMutableBytes) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapAgentIDToMutableBytes) GetBytes(key wasmlib.ScAgentID) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(m.objID, key.KeyID()) -} - -type MutableAccountsResults struct { - id int32 -} - -func (s MutableAccountsResults) Agents() MapAgentIDToMutableBytes { - return MapAgentIDToMutableBytes{objID: s.id} -} - -type MapColorToImmutableInt64 struct { - objID int32 -} - -func (m MapColorToImmutableInt64) GetInt64(key wasmlib.ScColor) wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(m.objID, key.KeyID()) -} - -type ImmutableBalanceResults struct { - id int32 -} - -func (s ImmutableBalanceResults) Balances() MapColorToImmutableInt64 { - return MapColorToImmutableInt64{objID: s.id} -} - -type MapColorToMutableInt64 struct { - objID int32 -} - -func (m MapColorToMutableInt64) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapColorToMutableInt64) GetInt64(key wasmlib.ScColor) wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(m.objID, key.KeyID()) -} - -type MutableBalanceResults struct { - id int32 -} - -func (s MutableBalanceResults) Balances() MapColorToMutableInt64 { - return MapColorToMutableInt64{objID: s.id} -} - -type ImmutableGetAccountNonceResults struct { - id int32 -} - -func (s ImmutableGetAccountNonceResults) AccountNonce() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultAccountNonce)) -} - -type MutableGetAccountNonceResults struct { - id int32 -} - -func (s MutableGetAccountNonceResults) AccountNonce() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultAccountNonce)) -} - -type ImmutableTotalAssetsResults struct { - id int32 -} - -func (s ImmutableTotalAssetsResults) Balances() MapColorToImmutableInt64 { - return MapColorToImmutableInt64{objID: s.id} -} - -type MutableTotalAssetsResults struct { - id int32 -} - -func (s MutableTotalAssetsResults) Balances() MapColorToMutableInt64 { - return MapColorToMutableInt64{objID: s.id} -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblob/params.go b/packages/vm/wasmlib/go/wasmlib/coreblob/params.go deleted file mode 100644 index 4a93f14cdb..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreblob/params.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreblob - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type MapStringToImmutableBytes struct { - objID int32 -} - -func (m MapStringToImmutableBytes) GetBytes(key string) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(m.objID, wasmlib.Key(key).KeyID()) -} - -type ImmutableStoreBlobParams struct { - id int32 -} - -func (s ImmutableStoreBlobParams) Blobs() MapStringToImmutableBytes { - return MapStringToImmutableBytes{objID: s.id} -} - -type MapStringToMutableBytes struct { - objID int32 -} - -func (m MapStringToMutableBytes) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapStringToMutableBytes) GetBytes(key string) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(m.objID, wasmlib.Key(key).KeyID()) -} - -type MutableStoreBlobParams struct { - id int32 -} - -func (s MutableStoreBlobParams) Blobs() MapStringToMutableBytes { - return MapStringToMutableBytes{objID: s.id} -} - -type ImmutableGetBlobFieldParams struct { - id int32 -} - -func (s ImmutableGetBlobFieldParams) Field() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamField)) -} - -func (s ImmutableGetBlobFieldParams) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamHash)) -} - -type MutableGetBlobFieldParams struct { - id int32 -} - -func (s MutableGetBlobFieldParams) Field() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamField)) -} - -func (s MutableGetBlobFieldParams) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamHash)) -} - -type ImmutableGetBlobInfoParams struct { - id int32 -} - -func (s ImmutableGetBlobInfoParams) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamHash)) -} - -type MutableGetBlobInfoParams struct { - id int32 -} - -func (s MutableGetBlobInfoParams) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamHash)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblob/results.go b/packages/vm/wasmlib/go/wasmlib/coreblob/results.go deleted file mode 100644 index 8a24de4245..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreblob/results.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreblob - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableStoreBlobResults struct { - id int32 -} - -func (s ImmutableStoreBlobResults) Hash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ResultHash)) -} - -type MutableStoreBlobResults struct { - id int32 -} - -func (s MutableStoreBlobResults) Hash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ResultHash)) -} - -type ImmutableGetBlobFieldResults struct { - id int32 -} - -func (s ImmutableGetBlobFieldResults) Bytes() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultBytes)) -} - -type MutableGetBlobFieldResults struct { - id int32 -} - -func (s MutableGetBlobFieldResults) Bytes() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultBytes)) -} - -type MapStringToImmutableInt32 struct { - objID int32 -} - -func (m MapStringToImmutableInt32) GetInt32(key string) wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(m.objID, wasmlib.Key(key).KeyID()) -} - -type ImmutableGetBlobInfoResults struct { - id int32 -} - -func (s ImmutableGetBlobInfoResults) BlobSizes() MapStringToImmutableInt32 { - return MapStringToImmutableInt32{objID: s.id} -} - -type MapStringToMutableInt32 struct { - objID int32 -} - -func (m MapStringToMutableInt32) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapStringToMutableInt32) GetInt32(key string) wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(m.objID, wasmlib.Key(key).KeyID()) -} - -type MutableGetBlobInfoResults struct { - id int32 -} - -func (s MutableGetBlobInfoResults) BlobSizes() MapStringToMutableInt32 { - return MapStringToMutableInt32{objID: s.id} -} - -type MapHashToImmutableInt32 struct { - objID int32 -} - -func (m MapHashToImmutableInt32) GetInt32(key wasmlib.ScHash) wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(m.objID, key.KeyID()) -} - -type ImmutableListBlobsResults struct { - id int32 -} - -func (s ImmutableListBlobsResults) BlobSizes() MapHashToImmutableInt32 { - return MapHashToImmutableInt32{objID: s.id} -} - -type MapHashToMutableInt32 struct { - objID int32 -} - -func (m MapHashToMutableInt32) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapHashToMutableInt32) GetInt32(key wasmlib.ScHash) wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(m.objID, key.KeyID()) -} - -type MutableListBlobsResults struct { - id int32 -} - -func (s MutableListBlobsResults) BlobSizes() MapHashToMutableInt32 { - return MapHashToMutableInt32{objID: s.id} -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblocklog/params.go b/packages/vm/wasmlib/go/wasmlib/coreblocklog/params.go deleted file mode 100644 index b67570e3b1..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreblocklog/params.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreblocklog - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableGetBlockInfoParams struct { - id int32 -} - -func (s ImmutableGetBlockInfoParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type MutableGetBlockInfoParams struct { - id int32 -} - -func (s MutableGetBlockInfoParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type ImmutableGetEventsForBlockParams struct { - id int32 -} - -func (s ImmutableGetEventsForBlockParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type MutableGetEventsForBlockParams struct { - id int32 -} - -func (s MutableGetEventsForBlockParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type ImmutableGetEventsForContractParams struct { - id int32 -} - -func (s ImmutableGetEventsForContractParams) ContractHname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamContractHname)) -} - -func (s ImmutableGetEventsForContractParams) FromBlock() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamFromBlock)) -} - -func (s ImmutableGetEventsForContractParams) ToBlock() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamToBlock)) -} - -type MutableGetEventsForContractParams struct { - id int32 -} - -func (s MutableGetEventsForContractParams) ContractHname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamContractHname)) -} - -func (s MutableGetEventsForContractParams) FromBlock() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamFromBlock)) -} - -func (s MutableGetEventsForContractParams) ToBlock() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamToBlock)) -} - -type ImmutableGetEventsForRequestParams struct { - id int32 -} - -func (s ImmutableGetEventsForRequestParams) RequestID() wasmlib.ScImmutableRequestID { - return wasmlib.NewScImmutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} - -type MutableGetEventsForRequestParams struct { - id int32 -} - -func (s MutableGetEventsForRequestParams) RequestID() wasmlib.ScMutableRequestID { - return wasmlib.NewScMutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} - -type ImmutableGetRequestIDsForBlockParams struct { - id int32 -} - -func (s ImmutableGetRequestIDsForBlockParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type MutableGetRequestIDsForBlockParams struct { - id int32 -} - -func (s MutableGetRequestIDsForBlockParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type ImmutableGetRequestReceiptParams struct { - id int32 -} - -func (s ImmutableGetRequestReceiptParams) RequestID() wasmlib.ScImmutableRequestID { - return wasmlib.NewScImmutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} - -type MutableGetRequestReceiptParams struct { - id int32 -} - -func (s MutableGetRequestReceiptParams) RequestID() wasmlib.ScMutableRequestID { - return wasmlib.NewScMutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} - -type ImmutableGetRequestReceiptsForBlockParams struct { - id int32 -} - -func (s ImmutableGetRequestReceiptsForBlockParams) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type MutableGetRequestReceiptsForBlockParams struct { - id int32 -} - -func (s MutableGetRequestReceiptsForBlockParams) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamBlockIndex)) -} - -type ImmutableIsRequestProcessedParams struct { - id int32 -} - -func (s ImmutableIsRequestProcessedParams) RequestID() wasmlib.ScImmutableRequestID { - return wasmlib.NewScImmutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} - -type MutableIsRequestProcessedParams struct { - id int32 -} - -func (s MutableIsRequestProcessedParams) RequestID() wasmlib.ScMutableRequestID { - return wasmlib.NewScMutableRequestID(s.id, wasmlib.KeyID(ParamRequestID)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblocklog/results.go b/packages/vm/wasmlib/go/wasmlib/coreblocklog/results.go deleted file mode 100644 index 6fee94382e..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreblocklog/results.go +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreblocklog - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableControlAddressesResults struct { - id int32 -} - -func (s ImmutableControlAddressesResults) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s ImmutableControlAddressesResults) GoverningAddress() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ResultGoverningAddress)) -} - -func (s ImmutableControlAddressesResults) StateControllerAddress() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ResultStateControllerAddress)) -} - -type MutableControlAddressesResults struct { - id int32 -} - -func (s MutableControlAddressesResults) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s MutableControlAddressesResults) GoverningAddress() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ResultGoverningAddress)) -} - -func (s MutableControlAddressesResults) StateControllerAddress() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ResultStateControllerAddress)) -} - -type ImmutableGetBlockInfoResults struct { - id int32 -} - -func (s ImmutableGetBlockInfoResults) BlockInfo() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultBlockInfo)) -} - -type MutableGetBlockInfoResults struct { - id int32 -} - -func (s MutableGetBlockInfoResults) BlockInfo() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultBlockInfo)) -} - -type ArrayOfImmutableBytes struct { - objID int32 -} - -func (a ArrayOfImmutableBytes) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfImmutableBytes) GetBytes(index int32) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(a.objID, wasmlib.Key32(index)) -} - -type ImmutableGetEventsForBlockResults struct { - id int32 -} - -func (s ImmutableGetEventsForBlockResults) Event() ArrayOfImmutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBytes{objID: arrID} -} - -type ArrayOfMutableBytes struct { - objID int32 -} - -func (a ArrayOfMutableBytes) Clear() { - wasmlib.Clear(a.objID) -} - -func (a ArrayOfMutableBytes) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfMutableBytes) GetBytes(index int32) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(a.objID, wasmlib.Key32(index)) -} - -type MutableGetEventsForBlockResults struct { - id int32 -} - -func (s MutableGetEventsForBlockResults) Event() ArrayOfMutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfMutableBytes{objID: arrID} -} - -type ImmutableGetEventsForContractResults struct { - id int32 -} - -func (s ImmutableGetEventsForContractResults) Event() ArrayOfImmutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBytes{objID: arrID} -} - -type MutableGetEventsForContractResults struct { - id int32 -} - -func (s MutableGetEventsForContractResults) Event() ArrayOfMutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfMutableBytes{objID: arrID} -} - -type ImmutableGetEventsForRequestResults struct { - id int32 -} - -func (s ImmutableGetEventsForRequestResults) Event() ArrayOfImmutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBytes{objID: arrID} -} - -type MutableGetEventsForRequestResults struct { - id int32 -} - -func (s MutableGetEventsForRequestResults) Event() ArrayOfMutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfMutableBytes{objID: arrID} -} - -type ImmutableGetLatestBlockInfoResults struct { - id int32 -} - -func (s ImmutableGetLatestBlockInfoResults) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s ImmutableGetLatestBlockInfoResults) BlockInfo() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultBlockInfo)) -} - -type MutableGetLatestBlockInfoResults struct { - id int32 -} - -func (s MutableGetLatestBlockInfoResults) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s MutableGetLatestBlockInfoResults) BlockInfo() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultBlockInfo)) -} - -type ArrayOfImmutableRequestID struct { - objID int32 -} - -func (a ArrayOfImmutableRequestID) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfImmutableRequestID) GetRequestID(index int32) wasmlib.ScImmutableRequestID { - return wasmlib.NewScImmutableRequestID(a.objID, wasmlib.Key32(index)) -} - -type ImmutableGetRequestIDsForBlockResults struct { - id int32 -} - -func (s ImmutableGetRequestIDsForBlockResults) RequestID() ArrayOfImmutableRequestID { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultRequestID), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_REQUEST_ID) - return ArrayOfImmutableRequestID{objID: arrID} -} - -type ArrayOfMutableRequestID struct { - objID int32 -} - -func (a ArrayOfMutableRequestID) Clear() { - wasmlib.Clear(a.objID) -} - -func (a ArrayOfMutableRequestID) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfMutableRequestID) GetRequestID(index int32) wasmlib.ScMutableRequestID { - return wasmlib.NewScMutableRequestID(a.objID, wasmlib.Key32(index)) -} - -type MutableGetRequestIDsForBlockResults struct { - id int32 -} - -func (s MutableGetRequestIDsForBlockResults) RequestID() ArrayOfMutableRequestID { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultRequestID), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_REQUEST_ID) - return ArrayOfMutableRequestID{objID: arrID} -} - -type ImmutableGetRequestReceiptResults struct { - id int32 -} - -func (s ImmutableGetRequestReceiptResults) BlockIndex() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s ImmutableGetRequestReceiptResults) RequestIndex() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ResultRequestIndex)) -} - -func (s ImmutableGetRequestReceiptResults) RequestRecord() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultRequestRecord)) -} - -type MutableGetRequestReceiptResults struct { - id int32 -} - -func (s MutableGetRequestReceiptResults) BlockIndex() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultBlockIndex)) -} - -func (s MutableGetRequestReceiptResults) RequestIndex() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ResultRequestIndex)) -} - -func (s MutableGetRequestReceiptResults) RequestRecord() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultRequestRecord)) -} - -type ImmutableGetRequestReceiptsForBlockResults struct { - id int32 -} - -func (s ImmutableGetRequestReceiptsForBlockResults) RequestRecord() ArrayOfImmutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultRequestRecord), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBytes{objID: arrID} -} - -type MutableGetRequestReceiptsForBlockResults struct { - id int32 -} - -func (s MutableGetRequestReceiptsForBlockResults) RequestRecord() ArrayOfMutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultRequestRecord), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfMutableBytes{objID: arrID} -} - -type ImmutableIsRequestProcessedResults struct { - id int32 -} - -func (s ImmutableIsRequestProcessedResults) RequestProcessed() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultRequestProcessed)) -} - -type MutableIsRequestProcessedResults struct { - id int32 -} - -func (s MutableIsRequestProcessedResults) RequestProcessed() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultRequestProcessed)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coregovernance/params.go b/packages/vm/wasmlib/go/wasmlib/coregovernance/params.go deleted file mode 100644 index 41e3e62ea2..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coregovernance/params.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coregovernance - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableAddAllowedStateControllerAddressParams struct { - id int32 -} - -func (s ImmutableAddAllowedStateControllerAddressParams) ChainOwner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamChainOwner)) -} - -func (s ImmutableAddAllowedStateControllerAddressParams) FeeColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ParamFeeColor)) -} - -func (s ImmutableAddAllowedStateControllerAddressParams) StateControllerAddress() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type MutableAddAllowedStateControllerAddressParams struct { - id int32 -} - -func (s MutableAddAllowedStateControllerAddressParams) ChainOwner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamChainOwner)) -} - -func (s MutableAddAllowedStateControllerAddressParams) FeeColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ParamFeeColor)) -} - -func (s MutableAddAllowedStateControllerAddressParams) StateControllerAddress() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type ImmutableDelegateChainOwnershipParams struct { - id int32 -} - -func (s ImmutableDelegateChainOwnershipParams) ChainOwner() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamChainOwner)) -} - -type MutableDelegateChainOwnershipParams struct { - id int32 -} - -func (s MutableDelegateChainOwnershipParams) ChainOwner() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamChainOwner)) -} - -type ImmutableRemoveAllowedStateControllerAddressParams struct { - id int32 -} - -func (s ImmutableRemoveAllowedStateControllerAddressParams) StateControllerAddress() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type MutableRemoveAllowedStateControllerAddressParams struct { - id int32 -} - -func (s MutableRemoveAllowedStateControllerAddressParams) StateControllerAddress() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type ImmutableRotateStateControllerParams struct { - id int32 -} - -func (s ImmutableRotateStateControllerParams) StateControllerAddress() wasmlib.ScImmutableAddress { - return wasmlib.NewScImmutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type MutableRotateStateControllerParams struct { - id int32 -} - -func (s MutableRotateStateControllerParams) StateControllerAddress() wasmlib.ScMutableAddress { - return wasmlib.NewScMutableAddress(s.id, wasmlib.KeyID(ParamStateControllerAddress)) -} - -type ImmutableSetChainInfoParams struct { - id int32 -} - -func (s ImmutableSetChainInfoParams) MaxBlobSize() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ParamMaxBlobSize)) -} - -func (s ImmutableSetChainInfoParams) MaxEventSize() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ParamMaxEventSize)) -} - -func (s ImmutableSetChainInfoParams) MaxEventsPerReq() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ParamMaxEventsPerReq)) -} - -func (s ImmutableSetChainInfoParams) OwnerFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s ImmutableSetChainInfoParams) ValidatorFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type MutableSetChainInfoParams struct { - id int32 -} - -func (s MutableSetChainInfoParams) MaxBlobSize() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ParamMaxBlobSize)) -} - -func (s MutableSetChainInfoParams) MaxEventSize() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ParamMaxEventSize)) -} - -func (s MutableSetChainInfoParams) MaxEventsPerReq() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ParamMaxEventsPerReq)) -} - -func (s MutableSetChainInfoParams) OwnerFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s MutableSetChainInfoParams) ValidatorFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type ImmutableSetContractFeeParams struct { - id int32 -} - -func (s ImmutableSetContractFeeParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) -} - -func (s ImmutableSetContractFeeParams) OwnerFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s ImmutableSetContractFeeParams) ValidatorFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type MutableSetContractFeeParams struct { - id int32 -} - -func (s MutableSetContractFeeParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) -} - -func (s MutableSetContractFeeParams) OwnerFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s MutableSetContractFeeParams) ValidatorFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type ImmutableSetDefaultFeeParams struct { - id int32 -} - -func (s ImmutableSetDefaultFeeParams) OwnerFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s ImmutableSetDefaultFeeParams) ValidatorFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type MutableSetDefaultFeeParams struct { - id int32 -} - -func (s MutableSetDefaultFeeParams) OwnerFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamOwnerFee)) -} - -func (s MutableSetDefaultFeeParams) ValidatorFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ParamValidatorFee)) -} - -type ImmutableGetFeeInfoParams struct { - id int32 -} - -func (s ImmutableGetFeeInfoParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) -} - -type MutableGetFeeInfoParams struct { - id int32 -} - -func (s MutableGetFeeInfoParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coregovernance/results.go b/packages/vm/wasmlib/go/wasmlib/coregovernance/results.go deleted file mode 100644 index c322210258..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coregovernance/results.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coregovernance - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ArrayOfImmutableBytes struct { - objID int32 -} - -func (a ArrayOfImmutableBytes) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfImmutableBytes) GetBytes(index int32) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(a.objID, wasmlib.Key32(index)) -} - -type ImmutableGetAllowedStateControllerAddressesResults struct { - id int32 -} - -func (s ImmutableGetAllowedStateControllerAddressesResults) AllowedStateControllerAddresses() ArrayOfImmutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultAllowedStateControllerAddresses), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfImmutableBytes{objID: arrID} -} - -type ArrayOfMutableBytes struct { - objID int32 -} - -func (a ArrayOfMutableBytes) Clear() { - wasmlib.Clear(a.objID) -} - -func (a ArrayOfMutableBytes) Length() int32 { - return wasmlib.GetLength(a.objID) -} - -func (a ArrayOfMutableBytes) GetBytes(index int32) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(a.objID, wasmlib.Key32(index)) -} - -type MutableGetAllowedStateControllerAddressesResults struct { - id int32 -} - -func (s MutableGetAllowedStateControllerAddressesResults) AllowedStateControllerAddresses() ArrayOfMutableBytes { - arrID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultAllowedStateControllerAddresses), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES) - return ArrayOfMutableBytes{objID: arrID} -} - -type ImmutableGetChainInfoResults struct { - id int32 -} - -func (s ImmutableGetChainInfoResults) ChainID() wasmlib.ScImmutableChainID { - return wasmlib.NewScImmutableChainID(s.id, wasmlib.KeyID(ResultChainID)) -} - -func (s ImmutableGetChainInfoResults) ChainOwnerID() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) -} - -func (s ImmutableGetChainInfoResults) DefaultOwnerFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultDefaultOwnerFee)) -} - -func (s ImmutableGetChainInfoResults) DefaultValidatorFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultDefaultValidatorFee)) -} - -func (s ImmutableGetChainInfoResults) Description() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ResultDescription)) -} - -func (s ImmutableGetChainInfoResults) FeeColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ResultFeeColor)) -} - -func (s ImmutableGetChainInfoResults) MaxBlobSize() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultMaxBlobSize)) -} - -func (s ImmutableGetChainInfoResults) MaxEventSize() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ResultMaxEventSize)) -} - -func (s ImmutableGetChainInfoResults) MaxEventsPerReq() wasmlib.ScImmutableInt16 { - return wasmlib.NewScImmutableInt16(s.id, wasmlib.KeyID(ResultMaxEventsPerReq)) -} - -type MutableGetChainInfoResults struct { - id int32 -} - -func (s MutableGetChainInfoResults) ChainID() wasmlib.ScMutableChainID { - return wasmlib.NewScMutableChainID(s.id, wasmlib.KeyID(ResultChainID)) -} - -func (s MutableGetChainInfoResults) ChainOwnerID() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ResultChainOwnerID)) -} - -func (s MutableGetChainInfoResults) DefaultOwnerFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultDefaultOwnerFee)) -} - -func (s MutableGetChainInfoResults) DefaultValidatorFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultDefaultValidatorFee)) -} - -func (s MutableGetChainInfoResults) Description() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ResultDescription)) -} - -func (s MutableGetChainInfoResults) FeeColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ResultFeeColor)) -} - -func (s MutableGetChainInfoResults) MaxBlobSize() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultMaxBlobSize)) -} - -func (s MutableGetChainInfoResults) MaxEventSize() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ResultMaxEventSize)) -} - -func (s MutableGetChainInfoResults) MaxEventsPerReq() wasmlib.ScMutableInt16 { - return wasmlib.NewScMutableInt16(s.id, wasmlib.KeyID(ResultMaxEventsPerReq)) -} - -type ImmutableGetFeeInfoResults struct { - id int32 -} - -func (s ImmutableGetFeeInfoResults) FeeColor() wasmlib.ScImmutableColor { - return wasmlib.NewScImmutableColor(s.id, wasmlib.KeyID(ResultFeeColor)) -} - -func (s ImmutableGetFeeInfoResults) OwnerFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultOwnerFee)) -} - -func (s ImmutableGetFeeInfoResults) ValidatorFee() wasmlib.ScImmutableInt64 { - return wasmlib.NewScImmutableInt64(s.id, wasmlib.KeyID(ResultValidatorFee)) -} - -type MutableGetFeeInfoResults struct { - id int32 -} - -func (s MutableGetFeeInfoResults) FeeColor() wasmlib.ScMutableColor { - return wasmlib.NewScMutableColor(s.id, wasmlib.KeyID(ResultFeeColor)) -} - -func (s MutableGetFeeInfoResults) OwnerFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultOwnerFee)) -} - -func (s MutableGetFeeInfoResults) ValidatorFee() wasmlib.ScMutableInt64 { - return wasmlib.NewScMutableInt64(s.id, wasmlib.KeyID(ResultValidatorFee)) -} - -type ImmutableGetMaxBlobSizeResults struct { - id int32 -} - -func (s ImmutableGetMaxBlobSizeResults) MaxBlobSize() wasmlib.ScImmutableInt32 { - return wasmlib.NewScImmutableInt32(s.id, wasmlib.KeyID(ResultMaxBlobSize)) -} - -type MutableGetMaxBlobSizeResults struct { - id int32 -} - -func (s MutableGetMaxBlobSizeResults) MaxBlobSize() wasmlib.ScMutableInt32 { - return wasmlib.NewScMutableInt32(s.id, wasmlib.KeyID(ResultMaxBlobSize)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreroot/params.go b/packages/vm/wasmlib/go/wasmlib/coreroot/params.go deleted file mode 100644 index f302c05d5c..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreroot/params.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreroot - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableDeployContractParams struct { - id int32 -} - -func (s ImmutableDeployContractParams) Description() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamDescription)) -} - -func (s ImmutableDeployContractParams) Name() wasmlib.ScImmutableString { - return wasmlib.NewScImmutableString(s.id, wasmlib.KeyID(ParamName)) -} - -func (s ImmutableDeployContractParams) ProgramHash() wasmlib.ScImmutableHash { - return wasmlib.NewScImmutableHash(s.id, wasmlib.KeyID(ParamProgramHash)) -} - -type MutableDeployContractParams struct { - id int32 -} - -func (s MutableDeployContractParams) Description() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamDescription)) -} - -func (s MutableDeployContractParams) Name() wasmlib.ScMutableString { - return wasmlib.NewScMutableString(s.id, wasmlib.KeyID(ParamName)) -} - -func (s MutableDeployContractParams) ProgramHash() wasmlib.ScMutableHash { - return wasmlib.NewScMutableHash(s.id, wasmlib.KeyID(ParamProgramHash)) -} - -type ImmutableGrantDeployPermissionParams struct { - id int32 -} - -func (s ImmutableGrantDeployPermissionParams) Deployer() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamDeployer)) -} - -type MutableGrantDeployPermissionParams struct { - id int32 -} - -func (s MutableGrantDeployPermissionParams) Deployer() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamDeployer)) -} - -type ImmutableRevokeDeployPermissionParams struct { - id int32 -} - -func (s ImmutableRevokeDeployPermissionParams) Deployer() wasmlib.ScImmutableAgentID { - return wasmlib.NewScImmutableAgentID(s.id, wasmlib.KeyID(ParamDeployer)) -} - -type MutableRevokeDeployPermissionParams struct { - id int32 -} - -func (s MutableRevokeDeployPermissionParams) Deployer() wasmlib.ScMutableAgentID { - return wasmlib.NewScMutableAgentID(s.id, wasmlib.KeyID(ParamDeployer)) -} - -type ImmutableFindContractParams struct { - id int32 -} - -func (s ImmutableFindContractParams) Hname() wasmlib.ScImmutableHname { - return wasmlib.NewScImmutableHname(s.id, wasmlib.KeyID(ParamHname)) -} - -type MutableFindContractParams struct { - id int32 -} - -func (s MutableFindContractParams) Hname() wasmlib.ScMutableHname { - return wasmlib.NewScMutableHname(s.id, wasmlib.KeyID(ParamHname)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/coreroot/results.go b/packages/vm/wasmlib/go/wasmlib/coreroot/results.go deleted file mode 100644 index 7108487a19..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/coreroot/results.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -package coreroot - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -type ImmutableFindContractResults struct { - id int32 -} - -func (s ImmutableFindContractResults) ContractFound() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultContractFound)) -} - -func (s ImmutableFindContractResults) ContractRecData() wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(s.id, wasmlib.KeyID(ResultContractRecData)) -} - -type MutableFindContractResults struct { - id int32 -} - -func (s MutableFindContractResults) ContractFound() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultContractFound)) -} - -func (s MutableFindContractResults) ContractRecData() wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(s.id, wasmlib.KeyID(ResultContractRecData)) -} - -type MapHnameToImmutableBytes struct { - objID int32 -} - -func (m MapHnameToImmutableBytes) GetBytes(key wasmlib.ScHname) wasmlib.ScImmutableBytes { - return wasmlib.NewScImmutableBytes(m.objID, key.KeyID()) -} - -type ImmutableGetContractRecordsResults struct { - id int32 -} - -func (s ImmutableGetContractRecordsResults) ContractRegistry() MapHnameToImmutableBytes { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultContractRegistry), wasmlib.TYPE_MAP) - return MapHnameToImmutableBytes{objID: mapID} -} - -type MapHnameToMutableBytes struct { - objID int32 -} - -func (m MapHnameToMutableBytes) Clear() { - wasmlib.Clear(m.objID) -} - -func (m MapHnameToMutableBytes) GetBytes(key wasmlib.ScHname) wasmlib.ScMutableBytes { - return wasmlib.NewScMutableBytes(m.objID, key.KeyID()) -} - -type MutableGetContractRecordsResults struct { - id int32 -} - -func (s MutableGetContractRecordsResults) ContractRegistry() MapHnameToMutableBytes { - mapID := wasmlib.GetObjectID(s.id, wasmlib.KeyID(ResultContractRegistry), wasmlib.TYPE_MAP) - return MapHnameToMutableBytes{objID: mapID} -} diff --git a/packages/vm/wasmlib/go/wasmlib/events.go b/packages/vm/wasmlib/go/wasmlib/events.go deleted file mode 100644 index feabb505c5..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/events.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -import ( - "strconv" -) - -// encodes separate entities into a byte buffer -type EventEncoder struct { - event string -} - -func NewEventEncoder(eventName string) *EventEncoder { - e := &EventEncoder{event: eventName} - timestamp := Root.GetInt64(KeyTimestamp).Value() - // convert nanoseconds to seconds - return e.Int64(timestamp / 1_000_000_000) -} - -func (e *EventEncoder) Address(value ScAddress) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) AgentID(value ScAgentID) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) Bool(value bool) *EventEncoder { - if value { - return e.Uint8(1) - } - return e.Uint8(0) -} - -func (e *EventEncoder) Bytes(value []byte) *EventEncoder { - return e.String(base58Encode(value)) -} - -func (e *EventEncoder) ChainID(value ScChainID) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) Color(value ScColor) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) Emit() { - Root.GetString(KeyEvent).SetValue(e.event) -} - -func (e *EventEncoder) Hash(value ScHash) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) Hname(value ScHname) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) Int8(value int8) *EventEncoder { - return e.Int64(int64(value)) -} - -func (e *EventEncoder) Int16(value int16) *EventEncoder { - return e.Int64(int64(value)) -} - -func (e *EventEncoder) Int32(value int32) *EventEncoder { - return e.Int64(int64(value)) -} - -func (e *EventEncoder) Int64(value int64) *EventEncoder { - return e.String(strconv.FormatInt(value, 10)) -} - -func (e *EventEncoder) RequestID(value ScRequestID) *EventEncoder { - return e.String(value.String()) -} - -func (e *EventEncoder) String(value string) *EventEncoder { - // TODO encode potential vertical bars that are present in the value string - e.event += "|" + value - return e -} - -func (e *EventEncoder) Uint8(value uint8) *EventEncoder { - return e.Uint64(uint64(value)) -} - -func (e *EventEncoder) Uint16(value uint16) *EventEncoder { - return e.Uint64(uint64(value)) -} - -func (e *EventEncoder) Uint32(value uint32) *EventEncoder { - return e.Uint64(uint64(value)) -} - -func (e *EventEncoder) Uint64(value uint64) *EventEncoder { - return e.String(strconv.FormatUint(value, 10)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/exports.go b/packages/vm/wasmlib/go/wasmlib/exports.go deleted file mode 100644 index 5787959311..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/exports.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -//export on_call -func OnCall(index int32) { - ctx := ScFuncContext{} - ctx.Require(GetObjectID(OBJ_ID_ROOT, KeyState, TYPE_MAP) == OBJ_ID_STATE, "object id mismatch") - ctx.Require(GetObjectID(OBJ_ID_ROOT, KeyParams, TYPE_MAP) == OBJ_ID_PARAMS, "object id mismatch") - ctx.Require(GetObjectID(OBJ_ID_ROOT, KeyResults, TYPE_MAP) == OBJ_ID_RESULTS, "object id mismatch") - - if (index & 0x8000) == 0 { - AddFunc(nil)[index](ctx) - return - } - - AddView(nil)[index&0x7fff](ScViewContext{}) -} - -func FuncError(ctx ScFuncContext) { - Panic("Invalid core func call") -} - -func ViewError(ctx ScViewContext) { - Panic("Invalid core view call") -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScExports struct { - exports ScMutableStringArray -} - -func NewScExports() ScExports { - exports := Root.GetStringArray(KeyExports) - // tell host what our highest predefined key is - // this helps detect missing or extra keys - exports.GetString(int32(KeyZzzzzzz)).SetValue("Go:KEY_ZZZZZZZ") - return ScExports{exports: exports} -} - -func (ctx ScExports) AddFunc(name string, f ScFuncContextFunction) { - index := int32(len(AddFunc(f))) - 1 - ctx.exports.GetString(index).SetValue(name) -} - -func (ctx ScExports) AddView(name string, v ScViewContextFunction) { - index := int32(len(AddView(v))) - 1 - ctx.exports.GetString(index | 0x8000).SetValue(name) -} diff --git a/packages/vm/wasmlib/go/wasmlib/hashtypes.go b/packages/vm/wasmlib/go/wasmlib/hashtypes.go deleted file mode 100644 index 70b0904930..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/hashtypes.go +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -import ( - "encoding/binary" -) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScAddress struct { - id [33]byte -} - -func NewScAddressFromBytes(bytes []byte) ScAddress { - o := ScAddress{} - if len(bytes) != len(o.id) { - Panic("invalid address id length") - } - copy(o.id[:], bytes) - return o -} - -func (o ScAddress) AsAgentID() ScAgentID { - a := ScAgentID{} - // agent id is address padded with zeroes - copy(a.id[:], o.id[:]) - return a -} - -func (o ScAddress) Bytes() []byte { - return o.id[:] -} - -func (o ScAddress) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScAddress) String() string { - return base58Encode(o.id[:]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScAgentID struct { - id [37]byte -} - -func NewScAgentID(address ScAddress, hContract ScHname) ScAgentID { - o := ScAgentID{} - copy(o.id[:], address.Bytes()) - copy(o.id[33:], hContract.Bytes()) - return o -} - -func NewScAgentIDFromBytes(bytes []byte) ScAgentID { - o := ScAgentID{} - if len(bytes) != len(o.id) { - Panic("invalid agent id length") - } - copy(o.id[:], bytes) - return o -} - -func (o ScAgentID) Address() ScAddress { - a := ScAddress{} - copy(a.id[:], o.id[:]) - return a -} - -func (o ScAgentID) Bytes() []byte { - return o.id[:] -} - -func (o ScAgentID) Hname() ScHname { - return NewScHnameFromBytes(o.id[33:]) -} - -func (o ScAgentID) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScAgentID) IsAddress() bool { - return o.Hname() == ScHname(0) -} - -func (o ScAgentID) String() string { - return base58Encode(o.id[:]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScChainID struct { - id [33]byte -} - -func NewScChainIDFromBytes(bytes []byte) ScChainID { - o := ScChainID{} - if len(bytes) != len(o.id) { - Panic("invalid chain id length") - } - copy(o.id[:], bytes) - return o -} - -func (o ScChainID) Address() ScAddress { - a := ScAddress{} - copy(a.id[:], o.id[:]) - return a -} - -func (o ScChainID) Bytes() []byte { - return o.id[:] -} - -func (o ScChainID) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScChainID) String() string { - return base58Encode(o.id[:]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScColor struct { - id [32]byte -} - -var ( - IOTA = ScColor{} - MINT = ScColor{} -) - -func init() { - for i := range MINT.id { - MINT.id[i] = 0xff - } -} - -func NewScColorFromBytes(bytes []byte) ScColor { - o := ScColor{} - if len(bytes) != len(o.id) { - Panic("invalid color id length") - } - copy(o.id[:], bytes) - return o -} - -func NewScColorFromRequestID(requestID ScRequestID) ScColor { - o := ScColor{} - copy(o.id[:], requestID.Bytes()) - return o -} - -func (o ScColor) Bytes() []byte { - return o.id[:] -} - -func (o ScColor) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScColor) String() string { - return base58Encode(o.id[:]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScHash struct { - id [32]byte -} - -func NewScHashFromBytes(bytes []byte) ScHash { - o := ScHash{} - if len(bytes) != len(o.id) { - Panic("invalid hash id length") - } - copy(o.id[:], bytes) - return o -} - -func (o ScHash) Bytes() []byte { - return o.id[:] -} - -func (o ScHash) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScHash) String() string { - return base58Encode(o.id[:]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScHname uint32 - -func NewScHname(name string) ScHname { - return ScFuncContext{}.Utility().Hname(name) -} - -func NewScHnameFromBytes(bytes []byte) ScHname { - return ScHname(binary.LittleEndian.Uint32(bytes)) -} - -func (hn ScHname) Bytes() []byte { - bytes := make([]byte, 4) - binary.LittleEndian.PutUint32(bytes, uint32(hn)) - return bytes -} - -func (hn ScHname) KeyID() Key32 { - return GetKeyIDFromBytes(hn.Bytes()) -} - -func (hn ScHname) String() string { - const hex = "0123456789abcdef" - res := make([]byte, 8) - val := hn - for i := 0; i < 8; i++ { - res[7-i] = hex[val&0x0f] - val >>= 4 - } - return string(res) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScRequestID struct { - id [34]byte -} - -func NewScRequestIDFromBytes(bytes []byte) ScRequestID { - o := ScRequestID{} - if len(bytes) != len(o.id) { - Panic("invalid request id length") - } - copy(o.id[:], bytes) - return o -} - -func (o ScRequestID) Bytes() []byte { - return o.id[:] -} - -func (o ScRequestID) KeyID() Key32 { - return GetKeyIDFromBytes(o.id[:]) -} - -func (o ScRequestID) String() string { - return base58Encode(o.id[:]) -} diff --git a/packages/vm/wasmlib/go/wasmlib/host.go b/packages/vm/wasmlib/go/wasmlib/host.go deleted file mode 100644 index 8955e1401a..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/host.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -import "encoding/binary" - -//nolint:revive -const ( - // all TYPE_* values should exactly match the counterpart OBJTYPE_* values on the host! - TYPE_ARRAY int32 = 0x20 - TYPE_ARRAY16 int32 = 0x60 - TYPE_CALL int32 = 0x80 - TYPE_MASK int32 = 0x1f - - TYPE_ADDRESS int32 = 1 - TYPE_AGENT_ID int32 = 2 - TYPE_BOOL int32 = 3 - TYPE_BYTES int32 = 4 - TYPE_CHAIN_ID int32 = 5 - TYPE_COLOR int32 = 6 - TYPE_HASH int32 = 7 - TYPE_HNAME int32 = 8 - TYPE_INT8 int32 = 9 - TYPE_INT16 int32 = 10 - TYPE_INT32 int32 = 11 - TYPE_INT64 int32 = 12 - TYPE_MAP int32 = 13 - TYPE_REQUEST_ID int32 = 14 - TYPE_STRING int32 = 15 - - OBJ_ID_NULL int32 = 0 - OBJ_ID_ROOT int32 = 1 - OBJ_ID_STATE int32 = 2 - OBJ_ID_PARAMS int32 = 3 - OBJ_ID_RESULTS int32 = 4 -) - -var TypeSizes = [...]uint8{0, 33, 37, 1, 0, 33, 32, 32, 4, 1, 2, 4, 8, 0, 34, 0} - -type ( - ScFuncContextFunction func(ScFuncContext) - ScViewContextFunction func(ScViewContext) - - ScHost interface { - AddFunc(f ScFuncContextFunction) []ScFuncContextFunction - AddView(v ScViewContextFunction) []ScViewContextFunction - CallFunc(objID, keyID int32, params []byte) []byte - DelKey(objID, keyID, typeID int32) - Exists(objID, keyID, typeID int32) bool - GetBytes(objID, keyID, typeID int32) []byte - GetKeyIDFromBytes(bytes []byte) int32 - GetKeyIDFromString(key string) int32 - GetObjectID(objID, keyID, typeID int32) int32 - SetBytes(objID, keyID, typeID int32, value []byte) - } -) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -var host ScHost - -func AddFunc(f ScFuncContextFunction) []ScFuncContextFunction { - return host.AddFunc(f) -} - -func AddView(v ScViewContextFunction) []ScViewContextFunction { - return host.AddView(v) -} - -func ConnectHost(h ScHost) ScHost { - oldHost := host - host = h - return oldHost -} - -func CallFunc(objID int32, keyID Key32, params []byte) []byte { - return host.CallFunc(objID, int32(keyID), params) -} - -func Clear(objID int32) { - var zero [4]byte - SetBytes(objID, KeyLength, TYPE_INT32, zero[:]) -} - -func DelKey(objID int32, keyID Key32, typeID int32) { - host.DelKey(objID, int32(keyID), typeID) -} - -func Exists(objID int32, keyID Key32, typeID int32) bool { - return host.Exists(objID, int32(keyID), typeID) -} - -func GetBytes(objID int32, keyID Key32, typeID int32) []byte { - bytes := host.GetBytes(objID, int32(keyID), typeID) - if len(bytes) == 0 { - return make([]byte, TypeSizes[typeID]) - } - return bytes -} - -func GetKeyIDFromBytes(bytes []byte) Key32 { - return Key32(host.GetKeyIDFromBytes(bytes)) -} - -func GetKeyIDFromString(key string) Key32 { - return Key32(host.GetKeyIDFromString(key)) -} - -func GetKeyIDFromUint64(value uint64, nrOfBytes int) Key32 { - bytes := make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, value) - return GetKeyIDFromBytes(bytes[:nrOfBytes]) -} - -func GetLength(objID int32) int32 { - bytes := GetBytes(objID, KeyLength, TYPE_INT32) - return int32(binary.LittleEndian.Uint32(bytes)) -} - -func GetObjectID(objID int32, keyID Key32, typeID int32) int32 { - return host.GetObjectID(objID, int32(keyID), typeID) -} - -func Log(text string) { - SetBytes(1, KeyLog, TYPE_STRING, []byte(text)) -} - -func Panic(text string) { - SetBytes(1, KeyPanic, TYPE_STRING, []byte(text)) -} - -func SetBytes(objID int32, keyID Key32, typeID int32, value []byte) { - host.SetBytes(objID, int32(keyID), typeID, value) -} - -func Trace(text string) { - SetBytes(1, KeyTrace, TYPE_STRING, []byte(text)) -} diff --git a/packages/vm/wasmlib/go/wasmlib/immutable.go b/packages/vm/wasmlib/go/wasmlib/immutable.go deleted file mode 100644 index 2dbc8ea7de..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/immutable.go +++ /dev/null @@ -1,890 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -import ( - "encoding/binary" - "strconv" -) - -type ScImmutableAddress struct { - objID int32 - keyID Key32 -} - -func NewScImmutableAddress(objID int32, keyID Key32) ScImmutableAddress { - return ScImmutableAddress{objID: objID, keyID: keyID} -} - -func (o ScImmutableAddress) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_ADDRESS) -} - -func (o ScImmutableAddress) String() string { - return o.Value().String() -} - -func (o ScImmutableAddress) Value() ScAddress { - return NewScAddressFromBytes(GetBytes(o.objID, o.keyID, TYPE_ADDRESS)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableAddressArray struct { - objID int32 -} - -func (o ScImmutableAddressArray) GetAddress(index int32) ScImmutableAddress { - return ScImmutableAddress{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableAddressArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableAgentID struct { - objID int32 - keyID Key32 -} - -func NewScImmutableAgentID(objID int32, keyID Key32) ScImmutableAgentID { - return ScImmutableAgentID{objID: objID, keyID: keyID} -} - -func (o ScImmutableAgentID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_AGENT_ID) -} - -func (o ScImmutableAgentID) String() string { - return o.Value().String() -} - -func (o ScImmutableAgentID) Value() ScAgentID { - return NewScAgentIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_AGENT_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableAgentIDArray struct { - objID int32 -} - -func (o ScImmutableAgentIDArray) GetAgentID(index int32) ScImmutableAgentID { - return ScImmutableAgentID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableAgentIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableBool struct { - objID int32 - keyID Key32 -} - -func NewScImmutableBool(objID int32, keyID Key32) ScImmutableBool { - return ScImmutableBool{objID: objID, keyID: keyID} -} - -func (o ScImmutableBool) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_BOOL) -} - -func (o ScImmutableBool) String() string { - if o.Value() { - return "1" - } - return "0" -} - -func (o ScImmutableBool) Value() bool { - bytes := GetBytes(o.objID, o.keyID, TYPE_BOOL) - return bytes[0] != 0 -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableBoolArray struct { - objID int32 -} - -func (o ScImmutableBoolArray) GetBool(index int32) ScImmutableBool { - return ScImmutableBool{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableBoolArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableBytes struct { - objID int32 - keyID Key32 -} - -func NewScImmutableBytes(objID int32, keyID Key32) ScImmutableBytes { - return ScImmutableBytes{objID: objID, keyID: keyID} -} - -func (o ScImmutableBytes) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_BYTES) -} - -func (o ScImmutableBytes) String() string { - return base58Encode(o.Value()) -} - -func (o ScImmutableBytes) Value() []byte { - return GetBytes(o.objID, o.keyID, TYPE_BYTES) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableBytesArray struct { - objID int32 -} - -func (o ScImmutableBytesArray) GetBytes(index int32) ScImmutableBytes { - return ScImmutableBytes{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableBytesArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableChainID struct { - objID int32 - keyID Key32 -} - -func NewScImmutableChainID(objID int32, keyID Key32) ScImmutableChainID { - return ScImmutableChainID{objID: objID, keyID: keyID} -} - -func (o ScImmutableChainID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_CHAIN_ID) -} - -func (o ScImmutableChainID) String() string { - return o.Value().String() -} - -func (o ScImmutableChainID) Value() ScChainID { - return NewScChainIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_CHAIN_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableChainIDArray struct { - objID int32 -} - -func (o ScImmutableChainIDArray) GetChainID(index int32) ScImmutableChainID { - return ScImmutableChainID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableChainIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableColor struct { - objID int32 - keyID Key32 -} - -func NewScImmutableColor(objID int32, keyID Key32) ScImmutableColor { - return ScImmutableColor{objID: objID, keyID: keyID} -} - -func (o ScImmutableColor) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_COLOR) -} - -func (o ScImmutableColor) String() string { - return o.Value().String() -} - -func (o ScImmutableColor) Value() ScColor { - return NewScColorFromBytes(GetBytes(o.objID, o.keyID, TYPE_COLOR)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableColorArray struct { - objID int32 -} - -func (o ScImmutableColorArray) GetColor(index int32) ScImmutableColor { - return ScImmutableColor{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableColorArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableHash struct { - objID int32 - keyID Key32 -} - -func NewScImmutableHash(objID int32, keyID Key32) ScImmutableHash { - return ScImmutableHash{objID: objID, keyID: keyID} -} - -func (o ScImmutableHash) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_HASH) -} - -func (o ScImmutableHash) String() string { - return o.Value().String() -} - -func (o ScImmutableHash) Value() ScHash { - return NewScHashFromBytes(GetBytes(o.objID, o.keyID, TYPE_HASH)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableHashArray struct { - objID int32 -} - -func (o ScImmutableHashArray) GetHash(index int32) ScImmutableHash { - return ScImmutableHash{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableHashArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableHname struct { - objID int32 - keyID Key32 -} - -func NewScImmutableHname(objID int32, keyID Key32) ScImmutableHname { - return ScImmutableHname{objID: objID, keyID: keyID} -} - -func (o ScImmutableHname) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_HNAME) -} - -func (o ScImmutableHname) String() string { - return o.Value().String() -} - -func (o ScImmutableHname) Value() ScHname { - return NewScHnameFromBytes(GetBytes(o.objID, o.keyID, TYPE_HNAME)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableHnameArray struct { - objID int32 -} - -func (o ScImmutableHnameArray) GetHname(index int32) ScImmutableHname { - return ScImmutableHname{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableHnameArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt8 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableInt8(objID int32, keyID Key32) ScImmutableInt8 { - return ScImmutableInt8{objID: objID, keyID: keyID} -} - -func (o ScImmutableInt8) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScImmutableInt8) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScImmutableInt8) Value() int8 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT8) - return int8(bytes[0]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt8Array struct { - objID int32 -} - -func (o ScImmutableInt8Array) GetInt8(index int32) ScImmutableInt8 { - return ScImmutableInt8{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableInt8Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt16 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableInt16(objID int32, keyID Key32) ScImmutableInt16 { - return ScImmutableInt16{objID: objID, keyID: keyID} -} - -func (o ScImmutableInt16) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScImmutableInt16) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScImmutableInt16) Value() int16 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT16) - return int16(binary.LittleEndian.Uint16(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt16Array struct { - objID int32 -} - -func (o ScImmutableInt16Array) GetInt16(index int32) ScImmutableInt16 { - return ScImmutableInt16{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableInt16Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt32 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableInt32(objID int32, keyID Key32) ScImmutableInt32 { - return ScImmutableInt32{objID: objID, keyID: keyID} -} - -func (o ScImmutableInt32) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScImmutableInt32) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScImmutableInt32) Value() int32 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT32) - return int32(binary.LittleEndian.Uint32(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt32Array struct { - objID int32 -} - -func (o ScImmutableInt32Array) GetInt32(index int32) ScImmutableInt32 { - return ScImmutableInt32{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableInt32Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt64 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableInt64(objID int32, keyID Key32) ScImmutableInt64 { - return ScImmutableInt64{objID: objID, keyID: keyID} -} - -func (o ScImmutableInt64) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScImmutableInt64) String() string { - return strconv.FormatInt(o.Value(), 10) -} - -func (o ScImmutableInt64) Value() int64 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT64) - return int64(binary.LittleEndian.Uint64(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableInt64Array struct { - objID int32 -} - -func (o ScImmutableInt64Array) GetInt64(index int32) ScImmutableInt64 { - return ScImmutableInt64{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableInt64Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableMap struct { - objID int32 -} - -func (o ScImmutableMap) CallFunc(keyID Key32, params []byte) []byte { - return CallFunc(o.objID, keyID, params) -} - -func (o ScImmutableMap) GetAddress(key MapKey) ScImmutableAddress { - return ScImmutableAddress{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetAddressArray(key MapKey) ScImmutableAddressArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_ADDRESS|TYPE_ARRAY) - return ScImmutableAddressArray{objID: arrID} -} - -func (o ScImmutableMap) GetAgentID(key MapKey) ScImmutableAgentID { - return ScImmutableAgentID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetAgentIDArray(key MapKey) ScImmutableAgentIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_AGENT_ID|TYPE_ARRAY) - return ScImmutableAgentIDArray{objID: arrID} -} - -func (o ScImmutableMap) GetBool(key MapKey) ScImmutableBool { - return ScImmutableBool{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetBoolArray(key MapKey) ScImmutableBoolArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_BOOL|TYPE_ARRAY) - return ScImmutableBoolArray{objID: arrID} -} - -func (o ScImmutableMap) GetBytes(key MapKey) ScImmutableBytes { - return ScImmutableBytes{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetBytesArray(key MapKey) ScImmutableBytesArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_BYTES|TYPE_ARRAY) - return ScImmutableBytesArray{objID: arrID} -} - -func (o ScImmutableMap) GetChainID(key MapKey) ScImmutableChainID { - return ScImmutableChainID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetChainIDArray(key MapKey) ScImmutableChainIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_CHAIN_ID|TYPE_ARRAY) - return ScImmutableChainIDArray{objID: arrID} -} - -func (o ScImmutableMap) GetColor(key MapKey) ScImmutableColor { - return ScImmutableColor{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetColorArray(key MapKey) ScImmutableColorArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_COLOR|TYPE_ARRAY) - return ScImmutableColorArray{objID: arrID} -} - -func (o ScImmutableMap) GetHash(key MapKey) ScImmutableHash { - return ScImmutableHash{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetHashArray(key MapKey) ScImmutableHashArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_HASH|TYPE_ARRAY) - return ScImmutableHashArray{objID: arrID} -} - -func (o ScImmutableMap) GetHname(key MapKey) ScImmutableHname { - return ScImmutableHname{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetHnameArray(key MapKey) ScImmutableHnameArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_HNAME|TYPE_ARRAY) - return ScImmutableHnameArray{objID: arrID} -} - -func (o ScImmutableMap) GetInt8(key MapKey) ScImmutableInt8 { - return ScImmutableInt8{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetInt8Array(key MapKey) ScImmutableInt8Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT8|TYPE_ARRAY) - return ScImmutableInt8Array{objID: arrID} -} - -func (o ScImmutableMap) GetInt16(key MapKey) ScImmutableInt16 { - return ScImmutableInt16{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetInt16Array(key MapKey) ScImmutableInt16Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT16|TYPE_ARRAY) - return ScImmutableInt16Array{objID: arrID} -} - -func (o ScImmutableMap) GetInt32(key MapKey) ScImmutableInt32 { - return ScImmutableInt32{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetInt32Array(key MapKey) ScImmutableInt32Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT32|TYPE_ARRAY) - return ScImmutableInt32Array{objID: arrID} -} - -func (o ScImmutableMap) GetInt64(key MapKey) ScImmutableInt64 { - return ScImmutableInt64{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetInt64Array(key MapKey) ScImmutableInt64Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT64|TYPE_ARRAY) - return ScImmutableInt64Array{objID: arrID} -} - -func (o ScImmutableMap) GetMap(key MapKey) ScImmutableMap { - mapID := GetObjectID(o.objID, key.KeyID(), TYPE_MAP) - return ScImmutableMap{objID: mapID} -} - -func (o ScImmutableMap) GetMapArray(key MapKey) ScImmutableMapArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_MAP|TYPE_ARRAY) - return ScImmutableMapArray{objID: arrID} -} - -func (o ScImmutableMap) GetRequestID(key MapKey) ScImmutableRequestID { - return ScImmutableRequestID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetRequestIDArray(key MapKey) ScImmutableRequestIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_REQUEST_ID|TYPE_ARRAY) - return ScImmutableRequestIDArray{objID: arrID} -} - -func (o ScImmutableMap) GetString(key MapKey) ScImmutableString { - return ScImmutableString{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetStringArray(key MapKey) ScImmutableStringArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_STRING|TYPE_ARRAY) - return ScImmutableStringArray{objID: arrID} -} - -func (o ScImmutableMap) GetUint8(key MapKey) ScImmutableUint8 { - return ScImmutableUint8{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetUint8Array(key MapKey) ScImmutableUint8Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT8|TYPE_ARRAY) - return ScImmutableUint8Array{objID: arrID} -} - -func (o ScImmutableMap) GetUint16(key MapKey) ScImmutableUint16 { - return ScImmutableUint16{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetUint16Array(key MapKey) ScImmutableUint16Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT16|TYPE_ARRAY) - return ScImmutableUint16Array{objID: arrID} -} - -func (o ScImmutableMap) GetUint32(key MapKey) ScImmutableUint32 { - return ScImmutableUint32{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetUint32Array(key MapKey) ScImmutableUint32Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT32|TYPE_ARRAY) - return ScImmutableUint32Array{objID: arrID} -} - -func (o ScImmutableMap) GetUint64(key MapKey) ScImmutableUint64 { - return ScImmutableUint64{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScImmutableMap) GetUint64Array(key MapKey) ScImmutableUint64Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT64|TYPE_ARRAY) - return ScImmutableUint64Array{objID: arrID} -} - -func (o ScImmutableMap) MapID() int32 { - return o.objID -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableMapArray struct { - objID int32 -} - -func (o ScImmutableMapArray) GetMap(index int32) ScImmutableMap { - mapID := GetObjectID(o.objID, Key32(index), TYPE_MAP) - return ScImmutableMap{objID: mapID} -} - -func (o ScImmutableMapArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableRequestID struct { - objID int32 - keyID Key32 -} - -func NewScImmutableRequestID(objID int32, keyID Key32) ScImmutableRequestID { - return ScImmutableRequestID{objID: objID, keyID: keyID} -} - -func (o ScImmutableRequestID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_REQUEST_ID) -} - -func (o ScImmutableRequestID) String() string { - return o.Value().String() -} - -func (o ScImmutableRequestID) Value() ScRequestID { - return NewScRequestIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_REQUEST_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableRequestIDArray struct { - objID int32 -} - -func (o ScImmutableRequestIDArray) GetRequestID(index int32) ScImmutableRequestID { - return ScImmutableRequestID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableRequestIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableString struct { - objID int32 - keyID Key32 -} - -func NewScImmutableString(objID int32, keyID Key32) ScImmutableString { - return ScImmutableString{objID: objID, keyID: keyID} -} - -func (o ScImmutableString) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_STRING) -} - -func (o ScImmutableString) String() string { - return o.Value() -} - -func (o ScImmutableString) Value() string { - bytes := GetBytes(o.objID, o.keyID, TYPE_STRING) - if bytes == nil { - return "" - } - return string(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableStringArray struct { - objID int32 -} - -func (o ScImmutableStringArray) GetString(index int32) ScImmutableString { - return ScImmutableString{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableStringArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint8 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableUint8(objID int32, keyID Key32) ScImmutableUint8 { - return ScImmutableUint8{objID: objID, keyID: keyID} -} - -func (o ScImmutableUint8) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScImmutableUint8) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScImmutableUint8) Value() uint8 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT8) - return bytes[0] -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint8Array struct { - objID int32 -} - -func (o ScImmutableUint8Array) GetUint8(index int32) ScImmutableUint8 { - return ScImmutableUint8{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableUint8Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint16 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableUint16(objID int32, keyID Key32) ScImmutableUint16 { - return ScImmutableUint16{objID: objID, keyID: keyID} -} - -func (o ScImmutableUint16) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScImmutableUint16) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScImmutableUint16) Value() uint16 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT16) - return binary.LittleEndian.Uint16(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint16Array struct { - objID int32 -} - -func (o ScImmutableUint16Array) GetUint16(index int32) ScImmutableUint16 { - return ScImmutableUint16{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableUint16Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint32 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableUint32(objID int32, keyID Key32) ScImmutableUint32 { - return ScImmutableUint32{objID: objID, keyID: keyID} -} - -func (o ScImmutableUint32) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScImmutableUint32) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScImmutableUint32) Value() uint32 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT32) - return binary.LittleEndian.Uint32(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint32Array struct { - objID int32 -} - -func (o ScImmutableUint32Array) GetUint32(index int32) ScImmutableUint32 { - return ScImmutableUint32{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableUint32Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint64 struct { - objID int32 - keyID Key32 -} - -func NewScImmutableUint64(objID int32, keyID Key32) ScImmutableUint64 { - return ScImmutableUint64{objID: objID, keyID: keyID} -} - -func (o ScImmutableUint64) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScImmutableUint64) String() string { - return strconv.FormatUint(o.Value(), 10) -} - -func (o ScImmutableUint64) Value() uint64 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT64) - return binary.LittleEndian.Uint64(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScImmutableUint64Array struct { - objID int32 -} - -func (o ScImmutableUint64Array) GetUint64(index int32) ScImmutableUint64 { - return ScImmutableUint64{objID: o.objID, keyID: Key32(index)} -} - -func (o ScImmutableUint64Array) Length() int32 { - return GetLength(o.objID) -} diff --git a/packages/vm/wasmlib/go/wasmlib/inithost.go b/packages/vm/wasmlib/go/wasmlib/inithost.go deleted file mode 100644 index 8b34c0b1fa..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/inithost.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -type InitHost struct { - funcs []ScFuncContextFunction - views []ScViewContextFunction - params map[int32][]byte -} - -var _ ScHost = &InitHost{} - -func NewInitHost() *InitHost { - return &InitHost{params: make(map[int32][]byte)} -} - -func (h InitHost) AddFunc(f ScFuncContextFunction) []ScFuncContextFunction { - if f != nil { - h.funcs = append(h.funcs, f) - } - return h.funcs -} - -func (h InitHost) AddView(v ScViewContextFunction) []ScViewContextFunction { - if v != nil { - h.views = append(h.views, v) - } - return h.views -} - -func (h InitHost) CallFunc(objID, keyID int32, params []byte) []byte { - Panic("InitHost::CallFunc") - return nil -} - -func (h InitHost) DelKey(objID, keyID, typeID int32) { - Panic("InitHost::DelKey") -} - -func (h InitHost) Exists(objID, keyID, typeID int32) bool { - if objID == int32(KeyParams) { - _, exists := h.params[keyID] - return exists - } - Panic("InitHost::Exists") - return false -} - -func (h InitHost) GetBytes(objID, keyID, typeID int32) []byte { - if objID == int32(KeyMaps) && keyID == int32(KeyLength) { - return nil - } - if objID == int32(KeyParams) { - return h.params[keyID] - } - Panic("InitHost::GetBytes") - return nil -} - -func (h InitHost) GetKeyIDFromBytes(bytes []byte) int32 { - Panic("InitHost::GetKeyIDFromBytes") - return 0 -} - -func (h InitHost) GetKeyIDFromString(key string) int32 { - Panic("InitHost::GetKeyIDFromString") - return 0 -} - -func (h InitHost) GetObjectID(objID, keyID, typeID int32) int32 { - if objID == 1 && keyID == int32(KeyMaps) { - return keyID - } - if objID == int32(KeyMaps) && keyID == 0 { - return int32(KeyParams) - } - Panic("InitHost::GetObjectID") - return 0 -} - -func (h InitHost) SetBytes(objID, keyID, typeID int32, value []byte) { - if objID == 1 && keyID == int32(KeyPanic) { - panic(string(value)) - } - if objID == int32(KeyParams) { - h.params[keyID] = value - return - } - Panic("InitHost::SetBytes") -} diff --git a/packages/vm/wasmlib/go/wasmlib/keys.go b/packages/vm/wasmlib/go/wasmlib/keys.go deleted file mode 100644 index 62c5ccbba0..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/keys.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -type MapKey interface { - KeyID() Key32 -} - -type Key string - -func (key Key) KeyID() Key32 { - return GetKeyIDFromString(string(key)) -} - -func KeyID(key string) Key32 { - return Key(key).KeyID() -} - -type Key32 int32 - -func (key Key32) KeyID() Key32 { - return key -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -const ( - KeyAccountID = Key32(-1) - KeyAddress = Key32(-2) - KeyBalances = Key32(-3) - KeyBase58Decode = Key32(-4) - KeyBase58Encode = Key32(-5) - KeyBlsAddress = Key32(-6) - KeyBlsAggregate = Key32(-7) - KeyBlsValid = Key32(-8) - KeyCall = Key32(-9) - KeyCaller = Key32(-10) - KeyChainID = Key32(-11) - KeyChainOwnerID = Key32(-12) - KeyColor = Key32(-13) - KeyContract = Key32(-14) - KeyContractCreator = Key32(-15) - KeyDeploy = Key32(-16) - KeyEd25519Address = Key32(-17) - KeyEd25519Valid = Key32(-18) - KeyEvent = Key32(-19) - KeyExports = Key32(-20) - KeyHashBlake2b = Key32(-21) - KeyHashSha3 = Key32(-22) - KeyHname = Key32(-23) - KeyIncoming = Key32(-24) - KeyLength = Key32(-25) - KeyLog = Key32(-26) - KeyMaps = Key32(-27) - KeyMinted = Key32(-28) - KeyPanic = Key32(-29) - KeyParams = Key32(-30) - KeyPost = Key32(-31) - KeyRandom = Key32(-32) - KeyRequestID = Key32(-33) - KeyResults = Key32(-34) - KeyReturn = Key32(-35) - KeyState = Key32(-36) - KeyTimestamp = Key32(-37) - KeyTrace = Key32(-38) - KeyTransfers = Key32(-39) - KeyUtility = Key32(-40) - KeyZzzzzzz = Key32(-41) -) diff --git a/packages/vm/wasmlib/go/wasmlib/mutable.go b/packages/vm/wasmlib/go/wasmlib/mutable.go deleted file mode 100644 index e9c8f909e2..0000000000 --- a/packages/vm/wasmlib/go/wasmlib/mutable.go +++ /dev/null @@ -1,1223 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmlib - -import ( - "encoding/binary" - "strconv" -) - -var Root = ScMutableMap{objID: OBJ_ID_ROOT} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableAddress struct { - objID int32 - keyID Key32 -} - -func NewScMutableAddress(objID int32, keyID Key32) ScMutableAddress { - return ScMutableAddress{objID: objID, keyID: keyID} -} - -func (o ScMutableAddress) Delete() { - DelKey(o.objID, o.keyID, TYPE_ADDRESS) -} - -func (o ScMutableAddress) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_ADDRESS) -} - -func (o ScMutableAddress) SetValue(value ScAddress) { - SetBytes(o.objID, o.keyID, TYPE_ADDRESS, value.Bytes()) -} - -func (o ScMutableAddress) String() string { - return o.Value().String() -} - -func (o ScMutableAddress) Value() ScAddress { - return NewScAddressFromBytes(GetBytes(o.objID, o.keyID, TYPE_ADDRESS)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableAddressArray struct { - objID int32 -} - -func (o ScMutableAddressArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableAddressArray) GetAddress(index int32) ScMutableAddress { - return ScMutableAddress{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableAddressArray) Immutable() ScImmutableAddressArray { - return ScImmutableAddressArray(o) -} - -func (o ScMutableAddressArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableAgentID struct { - objID int32 - keyID Key32 -} - -func NewScMutableAgentID(objID int32, keyID Key32) ScMutableAgentID { - return ScMutableAgentID{objID: objID, keyID: keyID} -} - -func (o ScMutableAgentID) Delete() { - DelKey(o.objID, o.keyID, TYPE_AGENT_ID) -} - -func (o ScMutableAgentID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_AGENT_ID) -} - -func (o ScMutableAgentID) SetValue(value ScAgentID) { - SetBytes(o.objID, o.keyID, TYPE_AGENT_ID, value.Bytes()) -} - -func (o ScMutableAgentID) String() string { - return o.Value().String() -} - -func (o ScMutableAgentID) Value() ScAgentID { - return NewScAgentIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_AGENT_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableAgentIDArray struct { - objID int32 -} - -func (o ScMutableAgentIDArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableAgentIDArray) GetAgentID(index int32) ScMutableAgentID { - return ScMutableAgentID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableAgentIDArray) Immutable() ScImmutableAgentIDArray { - return ScImmutableAgentIDArray(o) -} - -func (o ScMutableAgentIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableBool struct { - objID int32 - keyID Key32 -} - -func NewScMutableBool(objID int32, keyID Key32) ScMutableBool { - return ScMutableBool{objID: objID, keyID: keyID} -} - -func (o ScMutableBool) Delete() { - DelKey(o.objID, o.keyID, TYPE_BOOL) -} - -func (o ScMutableBool) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_BOOL) -} - -func (o ScMutableBool) SetValue(value bool) { - bytes := make([]byte, 1) - if value { - bytes[0] = 1 - } - SetBytes(o.objID, o.keyID, TYPE_BOOL, bytes) -} - -func (o ScMutableBool) String() string { - if o.Value() { - return "1" - } - return "0" -} - -func (o ScMutableBool) Value() bool { - bytes := GetBytes(o.objID, o.keyID, TYPE_BOOL) - return bytes[0] != 0 -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableBoolArray struct { - objID int32 -} - -func (o ScMutableBoolArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableBoolArray) GetBool(index int32) ScMutableBool { - return ScMutableBool{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableBoolArray) Immutable() ScImmutableBoolArray { - return ScImmutableBoolArray(o) -} - -func (o ScMutableBoolArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableBytes struct { - objID int32 - keyID Key32 -} - -func NewScMutableBytes(objID int32, keyID Key32) ScMutableBytes { - return ScMutableBytes{objID: objID, keyID: keyID} -} - -func (o ScMutableBytes) Delete() { - DelKey(o.objID, o.keyID, TYPE_BYTES) -} - -func (o ScMutableBytes) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_BYTES) -} - -func (o ScMutableBytes) SetValue(value []byte) { - SetBytes(o.objID, o.keyID, TYPE_BYTES, value) -} - -func (o ScMutableBytes) String() string { - return base58Encode(o.Value()) -} - -func (o ScMutableBytes) Value() []byte { - return GetBytes(o.objID, o.keyID, TYPE_BYTES) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableBytesArray struct { - objID int32 -} - -func (o ScMutableBytesArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableBytesArray) GetBytes(index int32) ScMutableBytes { - return ScMutableBytes{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableBytesArray) Immutable() ScImmutableBytesArray { - return ScImmutableBytesArray(o) -} - -func (o ScMutableBytesArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableChainID struct { - objID int32 - keyID Key32 -} - -func NewScMutableChainID(objID int32, keyID Key32) ScMutableChainID { - return ScMutableChainID{objID: objID, keyID: keyID} -} - -func (o ScMutableChainID) Delete() { - DelKey(o.objID, o.keyID, TYPE_CHAIN_ID) -} - -func (o ScMutableChainID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_CHAIN_ID) -} - -func (o ScMutableChainID) SetValue(value ScChainID) { - SetBytes(o.objID, o.keyID, TYPE_CHAIN_ID, value.Bytes()) -} - -func (o ScMutableChainID) String() string { - return o.Value().String() -} - -func (o ScMutableChainID) Value() ScChainID { - return NewScChainIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_CHAIN_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableChainIDArray struct { - objID int32 -} - -func (o ScMutableChainIDArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableChainIDArray) GetChainID(index int32) ScMutableChainID { - return ScMutableChainID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableChainIDArray) Immutable() ScImmutableChainIDArray { - return ScImmutableChainIDArray(o) -} - -func (o ScMutableChainIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableColor struct { - objID int32 - keyID Key32 -} - -func NewScMutableColor(objID int32, keyID Key32) ScMutableColor { - return ScMutableColor{objID: objID, keyID: keyID} -} - -func (o ScMutableColor) Delete() { - DelKey(o.objID, o.keyID, TYPE_COLOR) -} - -func (o ScMutableColor) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_COLOR) -} - -func (o ScMutableColor) SetValue(value ScColor) { - SetBytes(o.objID, o.keyID, TYPE_COLOR, value.Bytes()) -} - -func (o ScMutableColor) String() string { - return o.Value().String() -} - -func (o ScMutableColor) Value() ScColor { - return NewScColorFromBytes(GetBytes(o.objID, o.keyID, TYPE_COLOR)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableColorArray struct { - objID int32 -} - -func (o ScMutableColorArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableColorArray) GetColor(index int32) ScMutableColor { - return ScMutableColor{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableColorArray) Immutable() ScImmutableColorArray { - return ScImmutableColorArray(o) -} - -func (o ScMutableColorArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableHash struct { - objID int32 - keyID Key32 -} - -func NewScMutableHash(objID int32, keyID Key32) ScMutableHash { - return ScMutableHash{objID: objID, keyID: keyID} -} - -func (o ScMutableHash) Delete() { - DelKey(o.objID, o.keyID, TYPE_HASH) -} - -func (o ScMutableHash) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_HASH) -} - -func (o ScMutableHash) SetValue(value ScHash) { - SetBytes(o.objID, o.keyID, TYPE_HASH, value.Bytes()) -} - -func (o ScMutableHash) String() string { - return o.Value().String() -} - -func (o ScMutableHash) Value() ScHash { - return NewScHashFromBytes(GetBytes(o.objID, o.keyID, TYPE_HASH)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableHashArray struct { - objID int32 -} - -func (o ScMutableHashArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableHashArray) GetHash(index int32) ScMutableHash { - return ScMutableHash{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableHashArray) Immutable() ScImmutableHashArray { - return ScImmutableHashArray(o) -} - -func (o ScMutableHashArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableHname struct { - objID int32 - keyID Key32 -} - -func NewScMutableHname(objID int32, keyID Key32) ScMutableHname { - return ScMutableHname{objID: objID, keyID: keyID} -} - -func (o ScMutableHname) Delete() { - DelKey(o.objID, o.keyID, TYPE_HNAME) -} - -func (o ScMutableHname) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_HNAME) -} - -func (o ScMutableHname) SetValue(value ScHname) { - SetBytes(o.objID, o.keyID, TYPE_HNAME, value.Bytes()) -} - -func (o ScMutableHname) String() string { - return o.Value().String() -} - -func (o ScMutableHname) Value() ScHname { - return NewScHnameFromBytes(GetBytes(o.objID, o.keyID, TYPE_HNAME)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableHnameArray struct { - objID int32 -} - -func (o ScMutableHnameArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableHnameArray) GetHname(index int32) ScMutableHname { - return ScMutableHname{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableHnameArray) Immutable() ScImmutableHnameArray { - return ScImmutableHnameArray(o) -} - -func (o ScMutableHnameArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt8 struct { - objID int32 - keyID Key32 -} - -func NewScMutableInt8(objID int32, keyID Key32) ScMutableInt8 { - return ScMutableInt8{objID: objID, keyID: keyID} -} - -func (o ScMutableInt8) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScMutableInt8) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScMutableInt8) SetValue(value int8) { - bytes := make([]byte, 1) - bytes[0] = byte(value) - SetBytes(o.objID, o.keyID, TYPE_INT8, bytes) -} - -func (o ScMutableInt8) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScMutableInt8) Value() int8 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT8) - return int8(bytes[0]) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt8Array struct { - objID int32 -} - -func (o ScMutableInt8Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableInt8Array) GetInt8(index int32) ScMutableInt8 { - return ScMutableInt8{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableInt8Array) Immutable() ScImmutableInt8Array { - return ScImmutableInt8Array(o) -} - -func (o ScMutableInt8Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt16 struct { - objID int32 - keyID Key32 -} - -func NewScMutableInt16(objID int32, keyID Key32) ScMutableInt16 { - return ScMutableInt16{objID: objID, keyID: keyID} -} - -func (o ScMutableInt16) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScMutableInt16) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScMutableInt16) SetValue(value int16) { - bytes := make([]byte, 2) - binary.LittleEndian.PutUint16(bytes, uint16(value)) - SetBytes(o.objID, o.keyID, TYPE_INT16, bytes) -} - -func (o ScMutableInt16) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScMutableInt16) Value() int16 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT16) - return int16(binary.LittleEndian.Uint16(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt16Array struct { - objID int32 -} - -func (o ScMutableInt16Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableInt16Array) GetInt16(index int32) ScMutableInt16 { - return ScMutableInt16{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableInt16Array) Immutable() ScImmutableInt16Array { - return ScImmutableInt16Array(o) -} - -func (o ScMutableInt16Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt32 struct { - objID int32 - keyID Key32 -} - -func NewScMutableInt32(objID int32, keyID Key32) ScMutableInt32 { - return ScMutableInt32{objID: objID, keyID: keyID} -} - -func (o ScMutableInt32) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScMutableInt32) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScMutableInt32) SetValue(value int32) { - bytes := make([]byte, 4) - binary.LittleEndian.PutUint32(bytes, uint32(value)) - SetBytes(o.objID, o.keyID, TYPE_INT32, bytes) -} - -func (o ScMutableInt32) String() string { - return strconv.FormatInt(int64(o.Value()), 10) -} - -func (o ScMutableInt32) Value() int32 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT32) - return int32(binary.LittleEndian.Uint32(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt32Array struct { - objID int32 -} - -func (o ScMutableInt32Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableInt32Array) GetInt32(index int32) ScMutableInt32 { - return ScMutableInt32{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableInt32Array) Immutable() ScImmutableInt32Array { - return ScImmutableInt32Array(o) -} - -func (o ScMutableInt32Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt64 struct { - objID int32 - keyID Key32 -} - -func NewScMutableInt64(objID int32, keyID Key32) ScMutableInt64 { - return ScMutableInt64{objID: objID, keyID: keyID} -} - -func (o ScMutableInt64) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScMutableInt64) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScMutableInt64) SetValue(value int64) { - bytes := make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, uint64(value)) - SetBytes(o.objID, o.keyID, TYPE_INT64, bytes) -} - -func (o ScMutableInt64) String() string { - return strconv.FormatInt(o.Value(), 10) -} - -func (o ScMutableInt64) Value() int64 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT64) - return int64(binary.LittleEndian.Uint64(bytes)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableInt64Array struct { - objID int32 -} - -func (o ScMutableInt64Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableInt64Array) GetInt64(index int32) ScMutableInt64 { - return ScMutableInt64{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableInt64Array) Immutable() ScImmutableInt64Array { - return ScImmutableInt64Array(o) -} - -func (o ScMutableInt64Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableMap struct { - objID int32 -} - -func NewScMutableMap() *ScMutableMap { - maps := Root.GetMapArray(KeyMaps) - return &ScMutableMap{objID: maps.GetMap(maps.Length()).objID} -} - -func (o ScMutableMap) CallFunc(keyID Key32, params []byte) []byte { - return CallFunc(o.objID, keyID, params) -} - -func (o ScMutableMap) Clear() { - Clear(o.objID) -} - -func (o ScMutableMap) GetAddress(key MapKey) ScMutableAddress { - return ScMutableAddress{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetAddressArray(key MapKey) ScMutableAddressArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_ADDRESS|TYPE_ARRAY) - return ScMutableAddressArray{objID: arrID} -} - -func (o ScMutableMap) GetAgentID(key MapKey) ScMutableAgentID { - return ScMutableAgentID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetAgentIDArray(key MapKey) ScMutableAgentIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_AGENT_ID|TYPE_ARRAY) - return ScMutableAgentIDArray{objID: arrID} -} - -func (o ScMutableMap) GetBool(key MapKey) ScMutableBool { - return ScMutableBool{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetBoolArray(key MapKey) ScMutableBoolArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_BOOL|TYPE_ARRAY) - return ScMutableBoolArray{objID: arrID} -} - -func (o ScMutableMap) GetBytes(key MapKey) ScMutableBytes { - return ScMutableBytes{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetBytesArray(key MapKey) ScMutableBytesArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_BYTES|TYPE_ARRAY) - return ScMutableBytesArray{objID: arrID} -} - -func (o ScMutableMap) GetChainID(key MapKey) ScMutableChainID { - return ScMutableChainID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetChainIDArray(key MapKey) ScMutableChainIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_CHAIN_ID|TYPE_ARRAY) - return ScMutableChainIDArray{objID: arrID} -} - -func (o ScMutableMap) GetColor(key MapKey) ScMutableColor { - return ScMutableColor{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetColorArray(key MapKey) ScMutableColorArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_COLOR|TYPE_ARRAY) - return ScMutableColorArray{objID: arrID} -} - -func (o ScMutableMap) GetHash(key MapKey) ScMutableHash { - return ScMutableHash{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetHashArray(key MapKey) ScMutableHashArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_HASH|TYPE_ARRAY) - return ScMutableHashArray{objID: arrID} -} - -func (o ScMutableMap) GetHname(key MapKey) ScMutableHname { - return ScMutableHname{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetHnameArray(key MapKey) ScMutableHnameArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_HNAME|TYPE_ARRAY) - return ScMutableHnameArray{objID: arrID} -} - -func (o ScMutableMap) GetInt8(key MapKey) ScMutableInt8 { - return ScMutableInt8{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetInt8Array(key MapKey) ScMutableInt8Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT8|TYPE_ARRAY) - return ScMutableInt8Array{objID: arrID} -} - -func (o ScMutableMap) GetInt16(key MapKey) ScMutableInt16 { - return ScMutableInt16{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetInt16Array(key MapKey) ScMutableInt16Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT16|TYPE_ARRAY) - return ScMutableInt16Array{objID: arrID} -} - -func (o ScMutableMap) GetInt32(key MapKey) ScMutableInt32 { - return ScMutableInt32{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetInt32Array(key MapKey) ScMutableInt32Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT32|TYPE_ARRAY) - return ScMutableInt32Array{objID: arrID} -} - -func (o ScMutableMap) GetInt64(key MapKey) ScMutableInt64 { - return ScMutableInt64{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetInt64Array(key MapKey) ScMutableInt64Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT64|TYPE_ARRAY) - return ScMutableInt64Array{objID: arrID} -} - -func (o ScMutableMap) GetMap(key MapKey) ScMutableMap { - mapID := GetObjectID(o.objID, key.KeyID(), TYPE_MAP) - return ScMutableMap{objID: mapID} -} - -func (o ScMutableMap) GetMapArray(key MapKey) ScMutableMapArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_MAP|TYPE_ARRAY) - return ScMutableMapArray{objID: arrID} -} - -func (o ScMutableMap) GetRequestID(key MapKey) ScMutableRequestID { - return ScMutableRequestID{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetRequestIDArray(key MapKey) ScMutableRequestIDArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_REQUEST_ID|TYPE_ARRAY) - return ScMutableRequestIDArray{objID: arrID} -} - -func (o ScMutableMap) GetString(key MapKey) ScMutableString { - return ScMutableString{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetStringArray(key MapKey) ScMutableStringArray { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_STRING|TYPE_ARRAY) - return ScMutableStringArray{objID: arrID} -} - -func (o ScMutableMap) GetUint8(key MapKey) ScMutableUint8 { - return ScMutableUint8{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetUint8Array(key MapKey) ScMutableUint8Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT8|TYPE_ARRAY) - return ScMutableUint8Array{objID: arrID} -} - -func (o ScMutableMap) GetUint16(key MapKey) ScMutableUint16 { - return ScMutableUint16{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetUint16Array(key MapKey) ScMutableUint16Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT16|TYPE_ARRAY) - return ScMutableUint16Array{objID: arrID} -} - -func (o ScMutableMap) GetUint32(key MapKey) ScMutableUint32 { - return ScMutableUint32{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetUint32Array(key MapKey) ScMutableUint32Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT32|TYPE_ARRAY) - return ScMutableUint32Array{objID: arrID} -} - -func (o ScMutableMap) GetUint64(key MapKey) ScMutableUint64 { - return ScMutableUint64{objID: o.objID, keyID: key.KeyID()} -} - -func (o ScMutableMap) GetUint64Array(key MapKey) ScMutableUint64Array { - arrID := GetObjectID(o.objID, key.KeyID(), TYPE_INT64|TYPE_ARRAY) - return ScMutableUint64Array{objID: arrID} -} - -func (o ScMutableMap) Immutable() ScImmutableMap { - return ScImmutableMap(o) -} - -func (o ScMutableMap) MapID() int32 { - return o.objID -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableMapArray struct { - objID int32 -} - -func (o ScMutableMapArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableMapArray) GetMap(index int32) ScMutableMap { - mapID := GetObjectID(o.objID, Key32(index), TYPE_MAP) - return ScMutableMap{objID: mapID} -} - -func (o ScMutableMapArray) Immutable() ScImmutableMapArray { - return ScImmutableMapArray(o) -} - -func (o ScMutableMapArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableRequestID struct { - objID int32 - keyID Key32 -} - -func NewScMutableRequestID(objID int32, keyID Key32) ScMutableRequestID { - return ScMutableRequestID{objID: objID, keyID: keyID} -} - -func (o ScMutableRequestID) Delete() { - DelKey(o.objID, o.keyID, TYPE_REQUEST_ID) -} - -func (o ScMutableRequestID) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_REQUEST_ID) -} - -func (o ScMutableRequestID) SetValue(value ScRequestID) { - SetBytes(o.objID, o.keyID, TYPE_REQUEST_ID, value.Bytes()) -} - -func (o ScMutableRequestID) String() string { - return o.Value().String() -} - -func (o ScMutableRequestID) Value() ScRequestID { - return NewScRequestIDFromBytes(GetBytes(o.objID, o.keyID, TYPE_REQUEST_ID)) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableRequestIDArray struct { - objID int32 -} - -func (o ScMutableRequestIDArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableRequestIDArray) GetRequestID(index int32) ScMutableRequestID { - return ScMutableRequestID{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableRequestIDArray) Immutable() ScImmutableRequestIDArray { - return ScImmutableRequestIDArray(o) -} - -func (o ScMutableRequestIDArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableString struct { - objID int32 - keyID Key32 -} - -func NewScMutableString(objID int32, keyID Key32) ScMutableString { - return ScMutableString{objID: objID, keyID: keyID} -} - -func (o ScMutableString) Delete() { - DelKey(o.objID, o.keyID, TYPE_STRING) -} - -func (o ScMutableString) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_STRING) -} - -func (o ScMutableString) SetValue(value string) { - SetBytes(o.objID, o.keyID, TYPE_STRING, []byte(value)) -} - -func (o ScMutableString) String() string { - return o.Value() -} - -func (o ScMutableString) Value() string { - bytes := GetBytes(o.objID, o.keyID, TYPE_STRING) - if bytes == nil { - return "" - } - return string(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableStringArray struct { - objID int32 -} - -func (o ScMutableStringArray) Clear() { - Clear(o.objID) -} - -func (o ScMutableStringArray) GetString(index int32) ScMutableString { - return ScMutableString{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableStringArray) Immutable() ScImmutableStringArray { - return ScImmutableStringArray(o) -} - -func (o ScMutableStringArray) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint8 struct { - objID int32 - keyID Key32 -} - -func NewScMutableUint8(objID int32, keyID Key32) ScMutableUint8 { - return ScMutableUint8{objID: objID, keyID: keyID} -} - -func (o ScMutableUint8) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScMutableUint8) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT8) -} - -func (o ScMutableUint8) SetValue(value uint8) { - bytes := make([]byte, 1) - bytes[0] = value - SetBytes(o.objID, o.keyID, TYPE_INT8, bytes) -} - -func (o ScMutableUint8) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScMutableUint8) Value() uint8 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT8) - return bytes[0] -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint8Array struct { - objID int32 -} - -func (o ScMutableUint8Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableUint8Array) GetUint8(index int32) ScMutableUint8 { - return ScMutableUint8{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableUint8Array) Immutable() ScImmutableUint8Array { - return ScImmutableUint8Array(o) -} - -func (o ScMutableUint8Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint16 struct { - objID int32 - keyID Key32 -} - -func NewScMutableUint16(objID int32, keyID Key32) ScMutableUint16 { - return ScMutableUint16{objID: objID, keyID: keyID} -} - -func (o ScMutableUint16) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScMutableUint16) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT16) -} - -func (o ScMutableUint16) SetValue(value uint16) { - bytes := make([]byte, 2) - binary.LittleEndian.PutUint16(bytes, value) - SetBytes(o.objID, o.keyID, TYPE_INT16, bytes) -} - -func (o ScMutableUint16) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScMutableUint16) Value() uint16 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT16) - return binary.LittleEndian.Uint16(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint16Array struct { - objID int32 -} - -func (o ScMutableUint16Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableUint16Array) GetUint16(index int32) ScMutableUint16 { - return ScMutableUint16{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableUint16Array) Immutable() ScImmutableUint16Array { - return ScImmutableUint16Array(o) -} - -func (o ScMutableUint16Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint32 struct { - objID int32 - keyID Key32 -} - -func NewScMutableUint32(objID int32, keyID Key32) ScMutableUint32 { - return ScMutableUint32{objID: objID, keyID: keyID} -} - -func (o ScMutableUint32) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScMutableUint32) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT32) -} - -func (o ScMutableUint32) SetValue(value uint32) { - bytes := make([]byte, 4) - binary.LittleEndian.PutUint32(bytes, value) - SetBytes(o.objID, o.keyID, TYPE_INT32, bytes) -} - -func (o ScMutableUint32) String() string { - return strconv.FormatUint(uint64(o.Value()), 10) -} - -func (o ScMutableUint32) Value() uint32 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT32) - return binary.LittleEndian.Uint32(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint32Array struct { - objID int32 -} - -func (o ScMutableUint32Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableUint32Array) GetUint32(index int32) ScMutableUint32 { - return ScMutableUint32{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableUint32Array) Immutable() ScImmutableUint32Array { - return ScImmutableUint32Array(o) -} - -func (o ScMutableUint32Array) Length() int32 { - return GetLength(o.objID) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint64 struct { - objID int32 - keyID Key32 -} - -func NewScMutableUint64(objID int32, keyID Key32) ScMutableUint64 { - return ScMutableUint64{objID: objID, keyID: keyID} -} - -func (o ScMutableUint64) Delete() { - DelKey(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScMutableUint64) Exists() bool { - return Exists(o.objID, o.keyID, TYPE_INT64) -} - -func (o ScMutableUint64) SetValue(value uint64) { - bytes := make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, value) - SetBytes(o.objID, o.keyID, TYPE_INT64, bytes) -} - -func (o ScMutableUint64) String() string { - return strconv.FormatUint(o.Value(), 10) -} - -func (o ScMutableUint64) Value() uint64 { - bytes := GetBytes(o.objID, o.keyID, TYPE_INT64) - return binary.LittleEndian.Uint64(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMutableUint64Array struct { - objID int32 -} - -func (o ScMutableUint64Array) Clear() { - Clear(o.objID) -} - -func (o ScMutableUint64Array) GetUint64(index int32) ScMutableUint64 { - return ScMutableUint64{objID: o.objID, keyID: Key32(index)} -} - -func (o ScMutableUint64Array) Immutable() ScImmutableUint64Array { - return ScImmutableUint64Array(o) -} - -func (o ScMutableUint64Array) Length() int32 { - return GetLength(o.objID) -} diff --git a/packages/vm/wasmlib/src/bytes.rs b/packages/vm/wasmlib/src/bytes.rs deleted file mode 100644 index e93f11ee54..0000000000 --- a/packages/vm/wasmlib/src/bytes.rs +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -use crate::hashtypes::*; -use crate::host::*; - -// decodes separate entities from a byte buffer -pub struct BytesDecoder<'a> { - buf: &'a [u8], -} - -impl BytesDecoder<'_> { - // constructs a decoder - pub fn new(data: &[u8]) -> BytesDecoder { - if data.len() == 0 { - panic("cannot decode empty byte array, use exist()"); - } - BytesDecoder { buf: data } - } - - // decodes an ScAddress from the byte buffer - pub fn address(&mut self) -> ScAddress { - ScAddress::from_bytes(self.bytes()) - } - - // decodes an ScAgentID from the byte buffer - pub fn agent_id(&mut self) -> ScAgentID { - ScAgentID::from_bytes(self.bytes()) - } - - // decodes a bool from the byte buffer - pub fn bool(&mut self) -> bool { - self.uint8() != 0 - } - - // decodes the next substring of bytes from the byte buffer - pub fn bytes(&mut self) -> &[u8] { - let size = self.uint32() as usize; - if self.buf.len() < size { - panic("insufficient bytes"); - } - let value = &self.buf[..size]; - self.buf = &self.buf[size..]; - value - } - - // decodes an ScChainID from the byte buffer - pub fn chain_id(&mut self) -> ScChainID { - ScChainID::from_bytes(self.bytes()) - } - - // decodes an ScColor from the byte buffer - pub fn color(&mut self) -> ScColor { - ScColor::from_bytes(self.bytes()) - } - - // decodes an ScHash from the byte buffer - pub fn hash(&mut self) -> ScHash { - ScHash::from_bytes(self.bytes()) - } - - // decodes an ScHname from the byte buffer - pub fn hname(&mut self) -> ScHname { - ScHname::from_bytes(self.bytes()) - } - - // decodes an int8 from the byte buffer - pub fn int8(&mut self) -> i8 { - self.uint8() as i8 - } - - // decodes an int16 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int16(&mut self) -> i16 { - self.leb128_decode(16) as i16 - } - - // decodes an int32 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int32(&mut self) -> i32 { - self.leb128_decode(32) as i32 - } - - // decodes an int64 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int64(&mut self) -> i64 { - self.leb128_decode(64) - } - - // leb128 decoder - fn leb128_decode(&mut self, bits: i32) -> i64 { - let mut val = 0_i64; - let mut s = 0; - loop { - if self.buf.len() == 0 { - panic("insufficient bytes"); - } - let mut b = self.buf[0] as i8; - self.buf = &self.buf[1..]; - val |= ((b & 0x7f) as i64) << s; - - // termination bit set? - if (b & -0x80) == 0 { - if ((val >> s) as i8) & 0x7f != b & 0x7f { - panic("integer too large"); - } - - // extend int7 sign to int8 - b |= (b & 0x40) << 1; - - // extend int8 sign to int64 - return val | ((b as i64) << s); - } - s += 7; - if s >= bits { - panic("integer representation too long"); - } - } - } - - // decodes an ScRequestID from the byte buffer - pub fn request_id(&mut self) -> ScRequestID { - ScRequestID::from_bytes(self.bytes()) - } - - // decodes an UTF-8 text string from the byte buffer - pub fn string(&mut self) -> String { - String::from_utf8_lossy(self.bytes()).to_string() - } - - // decodes an uint8 from the byte buffer - pub fn uint8(&mut self) -> u8 { - if self.buf.len() == 0 { - panic("insufficient bytes"); - } - let val = self.buf[0]; - self.buf = &self.buf[1..]; - val - } - - // decodes an uint16 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint16(&mut self) -> u16 { - self.int16() as u16 - } - - // decodes an uint32 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint32(&mut self) -> u32 { - self.int32() as u32 - } - - // decodes an uint64 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint64(&mut self) -> u64 { - self.int64() as u64 - } -} - -impl Drop for BytesDecoder<'_> { - fn drop(&mut self) { - if self.buf.len() != 0 { - panic("extra bytes"); - } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// encodes separate entities into a byte buffer -pub struct BytesEncoder { - buf: Vec, -} - -impl BytesEncoder { - // constructs an encoder - pub fn new() -> BytesEncoder { - BytesEncoder { buf: Vec::new() } - } - - // encodes an ScAddress into the byte buffer - pub fn address(&mut self, value: &ScAddress) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // encodes an ScAgentID into the byte buffer - pub fn agent_id(&mut self, value: &ScAgentID) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // encodes a bool into the byte buffer - pub fn bool(&mut self, val: bool) -> &BytesEncoder { - self.uint8(val as u8) - } - - // encodes a substring of bytes into the byte buffer - pub fn bytes(&mut self, value: &[u8]) -> &BytesEncoder { - self.uint32(value.len() as u32); - self.buf.extend_from_slice(value); - self - } - - // encodes an ScChainID into the byte buffer - pub fn chain_id(&mut self, value: &ScChainID) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // encodes an ScColor into the byte buffer - pub fn color(&mut self, value: &ScColor) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // retrieve the encoded byte buffer - pub fn data(&self) -> Vec { - self.buf.clone() - } - - // encodes an ScHash into the byte buffer - pub fn hash(&mut self, value: &ScHash) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // encodes an ScHname into the byte buffer - pub fn hname(&mut self, value: ScHname) -> &BytesEncoder { - self.bytes(&value.to_bytes()) - } - - // encodes an int8 into the byte buffer - pub fn int8(&mut self, val: i8) -> &BytesEncoder { - self.uint8(val as u8) - } - - // encodes an int16 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int16(&mut self, val: i16) -> &BytesEncoder { - self.leb128_encode(val as i64) - } - - // encodes an int32 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int32(&mut self, val: i32) -> &BytesEncoder { - self.leb128_encode(val as i64) - } - - // encodes an int64 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn int64(&mut self, val: i64) -> &BytesEncoder { - self.leb128_encode(val) - } - - // leb128 encoder - fn leb128_encode(&mut self, mut val: i64) -> &BytesEncoder { - loop { - let b = val as u8; - let s = b & 0x40; - val >>= 7; - if (val == 0 && s == 0) || (val == -1 && s != 0) { - self.buf.push(b & 0x7f); - return self; - } - self.buf.push(b | 0x80); - } - } - - // encodes an ScRequestID into the byte buffer - pub fn request_id(&mut self, value: &ScRequestID) -> &BytesEncoder { - self.bytes(value.to_bytes()) - } - - // encodes an UTF-8 text string into the byte buffer - pub fn string(&mut self, value: &str) -> &BytesEncoder { - self.bytes(value.as_bytes()) - } - - // encodes an uint8 into the byte buffer - pub fn uint8(&mut self, val: u8) -> &BytesEncoder { - self.buf.push(val); - self - } - - // encodes an uint16 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint16(&mut self, val: u16) -> &BytesEncoder { - self.int16(val as i16) - } - - // encodes an uint32 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint32(&mut self, val: u32) -> &BytesEncoder { - self.int32(val as i32) - } - - // encodes an uint64 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - pub fn uint64(&mut self, val: u64) -> &BytesEncoder { - self.int64(val as i64) - } -} diff --git a/packages/vm/wasmlib/src/context.rs b/packages/vm/wasmlib/src/context.rs deleted file mode 100644 index eadcb87483..0000000000 --- a/packages/vm/wasmlib/src/context.rs +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// encapsulates standard host entities into a simple interface - -use std::convert::TryInto; - -use crate::bytes::*; -use crate::contract::*; -use crate::hashtypes::*; -use crate::host::*; -use crate::immutable::*; -use crate::keys::*; -use crate::mutable::*; - -// all access to the objects in host's object tree starts here -pub(crate) static ROOT: ScMutableMap = ScMutableMap { obj_id: OBJ_ID_ROOT }; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// retrieves any information that is related to colored token balances -pub struct ScBalances { - balances: ScImmutableMap, -} - -impl ScBalances { - // retrieve the balance for the specified token color - pub fn balance(&self, color: &ScColor) -> i64 { - self.balances.get_int64(color).value() - } - - // retrieve an array of all token colors that have a non-zero balance - pub fn colors(&self) -> ScImmutableColorArray { - self.balances.get_color_array(&KEY_COLOR) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// passes token transfer information to a function call -#[derive(Clone, Copy)] -pub struct ScTransfers { - pub(crate) transfers: ScMutableMap, -} - -impl ScTransfers { - // create a new transfers object ready to add token transfers - pub fn new() -> ScTransfers { - ScTransfers { transfers: ScMutableMap::new() } - } - - // create a new transfers object from a balances object - pub fn from_balances(balances: ScBalances) -> ScTransfers { - let transfers = ScTransfers::new(); - let colors = balances.colors(); - for i in 0..colors.length() { - let color = colors.get_color(i).value(); - transfers.set(&color, balances.balance(&color)); - } - transfers - } - - // create a new transfers object and initialize it with the specified amount of iotas - pub fn iotas(amount: i64) -> ScTransfers { - ScTransfers::transfer(&ScColor::IOTA, amount) - } - - // create a new transfers object and initialize it with the specified token transfer - pub fn transfer(color: &ScColor, amount: i64) -> ScTransfers { - let transfer = ScTransfers::new(); - transfer.set(color, amount); - transfer - } - - // set the specified colored token transfer in the transfers object - // note that this will overwrite any previous amount for the specified color - pub fn set(&self, color: &ScColor, amount: i64) { - self.transfers.get_int64(color).set_value(amount); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// provides access to utility functions that are handled by the host -pub struct ScUtility { - utility: ScMutableMap, -} - -impl ScUtility { - // decodes the specified base58-encoded string value to its original bytes - pub fn base58_decode(&self, value: &str) -> Vec { - self.utility.call_func(KEY_BASE58_DECODE, value.as_bytes()) - } - - // encodes the specified bytes to a base-58-encoded string - pub fn base58_encode(&self, value: &[u8]) -> String { - let result = self.utility.call_func(KEY_BASE58_ENCODE, value); - unsafe { String::from_utf8_unchecked(result) } - } - - // retrieves the address for the specified BLS public key - pub fn bls_address_from_pubkey(&self, pub_key: &[u8]) -> ScAddress { - let result = self.utility.call_func(KEY_BLS_ADDRESS, pub_key); - ScAddress::from_bytes(&result) - } - - // aggregates the specified multiple BLS signatures and public keys into a single one - pub fn bls_aggregate_signatures(&self, pub_keys_bin: &[&[u8]], sigs_bin: &[&[u8]]) -> (Vec, Vec) { - let mut encode = BytesEncoder::new(); - encode.int32(pub_keys_bin.len() as i32); - for pub_key in pub_keys_bin { - encode.bytes(pub_key); - } - encode.int32(sigs_bin.len() as i32); - for sig in sigs_bin { - encode.bytes(sig); - } - let result = self.utility.call_func(KEY_BLS_AGGREGATE, &encode.data()); - let mut decode = BytesDecoder::new(&result); - return (decode.bytes().to_vec(), decode.bytes().to_vec()); - } - - // checks if the specified BLS signature is valid - pub fn bls_valid_signature(&self, data: &[u8], pub_key: &[u8], signature: &[u8]) -> bool { - let mut encode = BytesEncoder::new(); - encode.bytes(data); - encode.bytes(pub_key); - encode.bytes(signature); - let result = self.utility.call_func(KEY_BLS_VALID, &encode.data()); - (result[0] & 0x01) != 0 - } - - // retrieves the address for the specified ED25519 public key - pub fn ed25519_address_from_pubkey(&self, pub_key: &[u8]) -> ScAddress { - let result = self.utility.call_func(KEY_ED25519_ADDRESS, pub_key); - ScAddress::from_bytes(&result) - } - - // checks if the specified ED25519 signature is valid - pub fn ed25519_valid_signature(&self, data: &[u8], pub_key: &[u8], signature: &[u8]) -> bool { - let mut encode = BytesEncoder::new(); - encode.bytes(data); - encode.bytes(pub_key); - encode.bytes(signature); - let result = self.utility.call_func(KEY_ED25519_VALID, &encode.data()); - (result[0] & 0x01) != 0 - } - - // hashes the specified value bytes using BLAKE2b hashing and returns the resulting 32-byte hash - pub fn hash_blake2b(&self, value: &[u8]) -> ScHash { - let hash = self.utility.call_func(KEY_HASH_BLAKE2B, value); - ScHash::from_bytes(&hash) - } - - // hashes the specified value bytes using SHA3 hashing and returns the resulting 32-byte hash - pub fn hash_sha3(&self, value: &[u8]) -> ScHash { - let hash = self.utility.call_func(KEY_HASH_SHA3, value); - ScHash::from_bytes(&hash) - } - - // calculates 32-bit hash for the specified name string - pub fn hname(&self, value: &str) -> ScHname { - let result = self.utility.call_func(KEY_HNAME, value.as_bytes()); - ScHname::from_bytes(&result) - } -} - -// wrapper function for simplified internal access to base58 encoding -pub(crate) fn base58_encode(bytes: &[u8]) -> String { - ScFuncContext {}.utility().base58_encode(bytes) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// shared interface part of ScFuncContext and ScViewContext -pub trait ScBaseContext { - // retrieve the agent id of this contract account - fn account_id(&self) -> ScAgentID { - ROOT.get_agent_id(&KEY_ACCOUNT_ID).value() - } - - // access the current balances for all token colors - fn balances(&self) -> ScBalances { - ScBalances { balances: ROOT.get_map(&KEY_BALANCES).immutable() } - } - - // retrieve the chain id of the chain this contract lives on - fn chain_id(&self) -> ScChainID { - ROOT.get_chain_id(&KEY_CHAIN_ID).value() - } - - // retrieve the agent id of the owner of the chain this contract lives on - fn chain_owner_id(&self) -> ScAgentID { - ROOT.get_agent_id(&KEY_CHAIN_OWNER_ID).value() - } - - // retrieve the hname of this contract - fn contract(&self) -> ScHname { - ROOT.get_hname(&KEY_CONTRACT).value() - } - - // retrieve the agent id of the creator of this contract - fn contract_creator(&self) -> ScAgentID { - ROOT.get_agent_id(&KEY_CONTRACT_CREATOR).value() - } - - // logs informational text message in the log on the host - fn log(&self, text: &str) { - log(text); - } - - // logs error text message in the log on the host and then panics - fn panic(&self, text: &str) { - panic(text); - } - - // retrieve parameters that were passed to the smart contract function - fn params(&self) -> ScImmutableMap { - ROOT.get_map(&KEY_PARAMS).immutable() - } - - // panics with specified message if specified condition is not satisfied - fn require(&self, cond: bool, msg: &str) { - if !cond { - panic(msg); - } - } - - // map that holds any results returned by the smart contract function - fn results(&self) -> ScMutableMap { - ROOT.get_map(&KEY_RESULTS) - } - - // deterministic time stamp fixed at the moment of calling the smart contract - fn timestamp(&self) -> i64 { - ROOT.get_int64(&KEY_TIMESTAMP).value() - } - - // logs debugging trace text message in the log on the host - // similar to log() except this will only show in the log in a special debug mode - fn trace(&self, text: &str) { - trace(text); - } - - // access diverse utility functions provided by the host - fn utility(&self) -> ScUtility { - ScUtility { utility: ROOT.get_map(&KEY_UTILITY) } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract interface with mutable access to state -#[derive(Clone, Copy)] -pub struct ScFuncContext {} - -// reuse shared part of interface -impl ScBaseContext for ScFuncContext {} - -impl ScFuncCallContext for ScFuncContext { - fn can_call_func(&self) { - panic!("can_call_func"); - } -} - -impl ScViewCallContext for ScFuncContext { - fn can_call_view(&self) { - panic!("can_call_view"); - } -} - -impl ScFuncContext { - // synchronously calls the specified smart contract function, - // passing the provided parameters and token transfers to it - pub fn call(&self, hcontract: ScHname, hfunction: ScHname, params: Option, transfer: Option) -> ScImmutableMap { - let mut encode = BytesEncoder::new(); - encode.hname(hcontract); - encode.hname(hfunction); - if let Some(params) = params { - encode.int32(params.map_id()); - } else { - encode.int32(0); - } - if let Some(transfer) = transfer { - encode.int32(transfer.transfers.map_id()); - } else { - encode.int32(0); - } - ROOT.get_bytes(&KEY_CALL).set_value(&encode.data()); - ROOT.get_map(&KEY_RETURN).immutable() - } - - // retrieve the agent id of the caller of the smart contract - pub fn caller(&self) -> ScAgentID { - ROOT.get_agent_id(&KEY_CALLER).value() - } - - // deploys a new instance of the specified smart contract on the current chain - // the provided parameters are passed to the smart contract "init" function - pub fn deploy(&self, program_hash: &ScHash, name: &str, description: &str, params: Option) { - let mut encode = BytesEncoder::new(); - encode.hash(program_hash); - encode.string(name); - encode.string(description); - if let Some(params) = params { - encode.int32(params.map_id()); - } else { - encode.int32(0); - } - ROOT.get_bytes(&KEY_DEPLOY).set_value(&encode.data()); - } - - // signals an event on the host that external entities can subscribe to - pub fn event(&self, text: &str) { - ROOT.get_string(&KEY_EVENT).set_value(text); - } - - // access the incoming balances for all token colors - pub fn incoming(&self) -> ScBalances { - ScBalances { balances: ROOT.get_map(&KEY_INCOMING).immutable() } - } - - // retrieve the tokens that were minted in this transaction - pub fn minted(&self) -> ScBalances { - ScBalances { balances: ROOT.get_map(&KEY_MINTED).immutable() } - } - - // asynchronously calls the specified smart contract function, - // passing the provided parameters and token transfers to it - // it is possible to schedule the call for a later execution by specifying a delay - pub fn post(&self, chain_id: &ScChainID, hcontract: ScHname, hfunction: ScHname, params: Option, transfer: ScTransfers, delay: i32) { - let mut encode = BytesEncoder::new(); - encode.chain_id(chain_id); - encode.hname(hcontract); - encode.hname(hfunction); - if let Some(params) = params { - encode.int32(params.map_id()); - } else { - encode.int32(0); - } - encode.int32(transfer.transfers.map_id()); - encode.int32(delay); - ROOT.get_bytes(&KEY_POST).set_value(&encode.data()); - } - - // generates a random value from 0 to max (exclusive max) using a deterministic RNG - pub fn random(&self, max: i64) -> i64 { - if max == 0 { - self.panic("random: max parameter should be non-zero"); - } - let state = ScMutableMap { obj_id: OBJ_ID_STATE }; - let rnd = state.get_bytes(&KEY_RANDOM); - let mut seed = rnd.value(); - if seed.is_empty() { - // get initial entropy from sandbox - seed = ROOT.get_bytes(&KEY_RANDOM).value(); - } - rnd.set_value(&self.utility().hash_sha3(&seed).to_bytes()); - let rnd = i64::from_le_bytes(seed[0..8].try_into().expect("invalid i64 length")); - (rnd as u64 % max as u64) as i64 - } - - // retrieve the request id of this transaction - pub fn request_id(&self) -> ScRequestID { - ROOT.get_request_id(&KEY_REQUEST_ID).value() - } - - // access mutable state storage on the host - pub fn state(&self) -> ScMutableMap { - ROOT.get_map(&KEY_STATE) - } - - // transfers the specified tokens to the specified Tangle ledger address - pub fn transfer_to_address(&self, address: &ScAddress, transfer: ScTransfers) { - let transfers = ROOT.get_map_array(&KEY_TRANSFERS); - let tx = transfers.get_map(transfers.length()); - tx.get_address(&KEY_ADDRESS).set_value(address); - tx.get_int32(&KEY_BALANCES).set_value(transfer.transfers.map_id()); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract view interface which has only immutable access to state -#[derive(Clone, Copy)] -pub struct ScViewContext {} - -// reuse shared part of interface -impl ScBaseContext for ScViewContext {} - -impl ScViewCallContext for ScViewContext { - fn can_call_view(&self) { - panic!("can_call_view"); - } -} - -impl ScViewContext { - // synchronously calls the specified smart contract view, - // passing the provided parameters to it - pub fn call(&self, hcontract: ScHname, hfunction: ScHname, params: Option) -> ScImmutableMap { - let mut encode = BytesEncoder::new(); - encode.hname(hcontract); - encode.hname(hfunction); - if let Some(params) = params { - encode.int32(params.map_id()); - } else { - encode.int32(0); - } - encode.int32(0); - ROOT.get_bytes(&KEY_CALL).set_value(&encode.data()); - ROOT.get_map(&KEY_RETURN).immutable() - } - - // access immutable state storage on the host - pub fn state(&self) -> ScImmutableMap { - ROOT.get_map(&KEY_STATE).immutable() - } -} diff --git a/packages/vm/wasmlib/src/contract.rs b/packages/vm/wasmlib/src/contract.rs deleted file mode 100644 index 66b349ffa4..0000000000 --- a/packages/vm/wasmlib/src/contract.rs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// base contract objects - -use std::ptr; - -use crate::bytes::*; -use crate::context::*; -use crate::hashtypes::*; -use crate::host::*; -use crate::keys::*; -use crate::mutable::*; - -pub trait ScFuncCallContext { - fn can_call_func(&self); -} - -pub trait ScViewCallContext { - fn can_call_view(&self); -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -#[derive(Clone, Copy)] -pub struct ScView { - h_contract: ScHname, - h_function: ScHname, - params_id: *mut i32, - results_id: *mut i32, -} - -impl ScView { - pub fn new(h_contract: ScHname, h_function: ScHname) -> ScView { - ScView { - h_contract: h_contract, - h_function: h_function, - params_id: ptr::null_mut(), - results_id: ptr::null_mut(), - } - } - - pub fn set_ptrs(&mut self, params_id: *mut i32, results_id: *mut i32) { - self.params_id = params_id; - self.results_id = results_id; - - unsafe { - if params_id != ptr::null_mut() { - *params_id = ScMutableMap::new().map_id(); - } - } - } - - pub fn call(&self) { - self.call_with_transfer(0); - } - - fn call_with_transfer(&self, transfer_id: i32) { - let mut encode = BytesEncoder::new(); - encode.hname(self.h_contract); - encode.hname(self.h_function); - encode.int32(self.id(self.params_id)); - encode.int32(transfer_id); - ROOT.get_bytes(&KEY_CALL).set_value(&encode.data()); - - unsafe { - if self.results_id != ptr::null_mut() { - *self.results_id = get_object_id(1, KEY_RETURN, TYPE_MAP); - } - } - } - - pub fn of_contract(&self, h_contract: ScHname) -> ScView { - let mut ret = self.clone(); - ret.h_contract = h_contract; - ret - } - - fn id(&self, params_id: *mut i32) -> i32 { - unsafe { - if params_id == ptr::null_mut() { - return 0; - } - *params_id - } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -#[derive(Clone, Copy)] -pub struct ScInitFunc { - view: ScView, -} - -impl ScInitFunc { - pub fn new(h_contract: ScHname, h_function: ScHname) -> ScInitFunc { - ScInitFunc { - view: ScView::new(h_contract, h_function), - } - } - - pub fn set_ptrs(&mut self, params_id: *mut i32, results_id: *mut i32) { - self.view.set_ptrs(params_id, results_id); - } - - pub fn call(&self) { - panic("cannot call init") - } - - pub fn of_contract(&self, h_contract: ScHname) -> ScInitFunc { - let mut ret = self.clone(); - ret.view.h_contract = h_contract; - ret - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -#[derive(Clone, Copy)] -pub struct ScFunc { - view: ScView, - delay: i32, - transfer_id: i32, -} - -impl ScFunc { - pub fn new(h_contract: ScHname, h_function: ScHname) -> ScFunc { - ScFunc { - view: ScView::new(h_contract, h_function), - delay: 0, - transfer_id: 0, - } - } - - pub fn set_ptrs(&mut self, params_id: *mut i32, results_id: *mut i32) { - self.view.set_ptrs(params_id, results_id); - } - - pub fn call(&self) { - if self.delay != 0 { - panic("cannot delay a call") - } - self.view.call_with_transfer(self.transfer_id); - } - - pub fn delay(&self, seconds: i32) -> ScFunc { - let mut ret = self.clone(); - ret.delay = seconds; - ret - } - - pub fn of_contract(&self, h_contract: ScHname) -> ScFunc { - let mut ret = self.clone(); - ret.view.h_contract = h_contract; - ret - } - - pub fn post(&self) { - self.post_to_chain(ROOT.get_chain_id(&KEY_CHAIN_ID).value()) - } - - pub fn post_to_chain(&self, chain_id: ScChainID) { - let mut encode = BytesEncoder::new(); - encode.chain_id(&chain_id); - encode.hname(self.view.h_contract); - encode.hname(self.view.h_function); - encode.int32(self.view.id(self.view.params_id)); - encode.int32(self.transfer_id); - encode.int32(self.delay); - ROOT.get_bytes(&KEY_POST).set_value(&encode.data()); - } - - pub fn transfer(&self, transfer: ScTransfers) -> ScFunc { - let mut ret = self.clone(); - ret.transfer_id = transfer.transfers.obj_id; - ret - } - - pub fn transfer_iotas(&self, amount: i64) -> ScFunc { - self.transfer(ScTransfers::iotas(amount)) - } -} diff --git a/packages/vm/wasmlib/src/coreblocklog/contract.rs b/packages/vm/wasmlib/src/coreblocklog/contract.rs deleted file mode 100644 index e8bad48177..0000000000 --- a/packages/vm/wasmlib/src/coreblocklog/contract.rs +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] - -use std::ptr; - -use crate::*; -use crate::coreblocklog::*; - -pub struct ControlAddressesCall { - pub func: ScView, - pub results: ImmutableControlAddressesResults, -} - -pub struct GetBlockInfoCall { - pub func: ScView, - pub params: MutableGetBlockInfoParams, - pub results: ImmutableGetBlockInfoResults, -} - -pub struct GetEventsForBlockCall { - pub func: ScView, - pub params: MutableGetEventsForBlockParams, - pub results: ImmutableGetEventsForBlockResults, -} - -pub struct GetEventsForContractCall { - pub func: ScView, - pub params: MutableGetEventsForContractParams, - pub results: ImmutableGetEventsForContractResults, -} - -pub struct GetEventsForRequestCall { - pub func: ScView, - pub params: MutableGetEventsForRequestParams, - pub results: ImmutableGetEventsForRequestResults, -} - -pub struct GetLatestBlockInfoCall { - pub func: ScView, - pub results: ImmutableGetLatestBlockInfoResults, -} - -pub struct GetRequestIDsForBlockCall { - pub func: ScView, - pub params: MutableGetRequestIDsForBlockParams, - pub results: ImmutableGetRequestIDsForBlockResults, -} - -pub struct GetRequestReceiptCall { - pub func: ScView, - pub params: MutableGetRequestReceiptParams, - pub results: ImmutableGetRequestReceiptResults, -} - -pub struct GetRequestReceiptsForBlockCall { - pub func: ScView, - pub params: MutableGetRequestReceiptsForBlockParams, - pub results: ImmutableGetRequestReceiptsForBlockResults, -} - -pub struct IsRequestProcessedCall { - pub func: ScView, - pub params: MutableIsRequestProcessedParams, - pub results: ImmutableIsRequestProcessedResults, -} - -pub struct ScFuncs { -} - -impl ScFuncs { - pub fn control_addresses(_ctx: & dyn ScViewCallContext) -> ControlAddressesCall { - let mut f = ControlAddressesCall { - func: ScView::new(HSC_NAME, HVIEW_CONTROL_ADDRESSES), - results: ImmutableControlAddressesResults { id: 0 }, - }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); - f - } - - pub fn get_block_info(_ctx: & dyn ScViewCallContext) -> GetBlockInfoCall { - let mut f = GetBlockInfoCall { - func: ScView::new(HSC_NAME, HVIEW_GET_BLOCK_INFO), - params: MutableGetBlockInfoParams { id: 0 }, - results: ImmutableGetBlockInfoResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_events_for_block(_ctx: & dyn ScViewCallContext) -> GetEventsForBlockCall { - let mut f = GetEventsForBlockCall { - func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_BLOCK), - params: MutableGetEventsForBlockParams { id: 0 }, - results: ImmutableGetEventsForBlockResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_events_for_contract(_ctx: & dyn ScViewCallContext) -> GetEventsForContractCall { - let mut f = GetEventsForContractCall { - func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_CONTRACT), - params: MutableGetEventsForContractParams { id: 0 }, - results: ImmutableGetEventsForContractResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_events_for_request(_ctx: & dyn ScViewCallContext) -> GetEventsForRequestCall { - let mut f = GetEventsForRequestCall { - func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_REQUEST), - params: MutableGetEventsForRequestParams { id: 0 }, - results: ImmutableGetEventsForRequestResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_latest_block_info(_ctx: & dyn ScViewCallContext) -> GetLatestBlockInfoCall { - let mut f = GetLatestBlockInfoCall { - func: ScView::new(HSC_NAME, HVIEW_GET_LATEST_BLOCK_INFO), - results: ImmutableGetLatestBlockInfoResults { id: 0 }, - }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); - f - } - - pub fn get_request_i_ds_for_block(_ctx: & dyn ScViewCallContext) -> GetRequestIDsForBlockCall { - let mut f = GetRequestIDsForBlockCall { - func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_I_DS_FOR_BLOCK), - params: MutableGetRequestIDsForBlockParams { id: 0 }, - results: ImmutableGetRequestIDsForBlockResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_request_receipt(_ctx: & dyn ScViewCallContext) -> GetRequestReceiptCall { - let mut f = GetRequestReceiptCall { - func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_RECEIPT), - params: MutableGetRequestReceiptParams { id: 0 }, - results: ImmutableGetRequestReceiptResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn get_request_receipts_for_block(_ctx: & dyn ScViewCallContext) -> GetRequestReceiptsForBlockCall { - let mut f = GetRequestReceiptsForBlockCall { - func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_RECEIPTS_FOR_BLOCK), - params: MutableGetRequestReceiptsForBlockParams { id: 0 }, - results: ImmutableGetRequestReceiptsForBlockResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } - - pub fn is_request_processed(_ctx: & dyn ScViewCallContext) -> IsRequestProcessedCall { - let mut f = IsRequestProcessedCall { - func: ScView::new(HSC_NAME, HVIEW_IS_REQUEST_PROCESSED), - params: MutableIsRequestProcessedParams { id: 0 }, - results: ImmutableIsRequestProcessedResults { id: 0 }, - }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); - f - } -} diff --git a/packages/vm/wasmlib/src/coreblocklog/params.rs b/packages/vm/wasmlib/src/coreblocklog/params.rs deleted file mode 100644 index 01b87611c2..0000000000 --- a/packages/vm/wasmlib/src/coreblocklog/params.rs +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] -#![allow(unused_imports)] - -use crate::*; -use crate::coreblocklog::*; -use crate::host::*; - -#[derive(Clone, Copy)] -pub struct ImmutableGetBlockInfoParams { - pub(crate) id: i32, -} - -impl ImmutableGetBlockInfoParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetBlockInfoParams { - pub(crate) id: i32, -} - -impl MutableGetBlockInfoParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForBlockParams { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForBlockParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForBlockParams { - pub(crate) id: i32, -} - -impl MutableGetEventsForBlockParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForContractParams { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForContractParams { - pub fn contract_hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_CONTRACT_HNAME.get_key_id()) - } - - pub fn from_block(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_FROM_BLOCK.get_key_id()) - } - - pub fn to_block(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_TO_BLOCK.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForContractParams { - pub(crate) id: i32, -} - -impl MutableGetEventsForContractParams { - pub fn contract_hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_CONTRACT_HNAME.get_key_id()) - } - - pub fn from_block(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_FROM_BLOCK.get_key_id()) - } - - pub fn to_block(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_TO_BLOCK.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForRequestParams { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForRequestParams { - pub fn request_id(&self) -> ScImmutableRequestID { - ScImmutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForRequestParams { - pub(crate) id: i32, -} - -impl MutableGetEventsForRequestParams { - pub fn request_id(&self) -> ScMutableRequestID { - ScMutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestIDsForBlockParams { - pub(crate) id: i32, -} - -impl ImmutableGetRequestIDsForBlockParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestIDsForBlockParams { - pub(crate) id: i32, -} - -impl MutableGetRequestIDsForBlockParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestReceiptParams { - pub(crate) id: i32, -} - -impl ImmutableGetRequestReceiptParams { - pub fn request_id(&self) -> ScImmutableRequestID { - ScImmutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestReceiptParams { - pub(crate) id: i32, -} - -impl MutableGetRequestReceiptParams { - pub fn request_id(&self) -> ScMutableRequestID { - ScMutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestReceiptsForBlockParams { - pub(crate) id: i32, -} - -impl ImmutableGetRequestReceiptsForBlockParams { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestReceiptsForBlockParams { - pub(crate) id: i32, -} - -impl MutableGetRequestReceiptsForBlockParams { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_BLOCK_INDEX.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableIsRequestProcessedParams { - pub(crate) id: i32, -} - -impl ImmutableIsRequestProcessedParams { - pub fn request_id(&self) -> ScImmutableRequestID { - ScImmutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableIsRequestProcessedParams { - pub(crate) id: i32, -} - -impl MutableIsRequestProcessedParams { - pub fn request_id(&self) -> ScMutableRequestID { - ScMutableRequestID::new(self.id, PARAM_REQUEST_ID.get_key_id()) - } -} diff --git a/packages/vm/wasmlib/src/coreblocklog/results.rs b/packages/vm/wasmlib/src/coreblocklog/results.rs deleted file mode 100644 index 98d0efaf24..0000000000 --- a/packages/vm/wasmlib/src/coreblocklog/results.rs +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] -#![allow(unused_imports)] - -use crate::*; -use crate::coreblocklog::*; -use crate::host::*; - -#[derive(Clone, Copy)] -pub struct ImmutableControlAddressesResults { - pub(crate) id: i32, -} - -impl ImmutableControlAddressesResults { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn governing_address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, RESULT_GOVERNING_ADDRESS.get_key_id()) - } - - pub fn state_controller_address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, RESULT_STATE_CONTROLLER_ADDRESS.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableControlAddressesResults { - pub(crate) id: i32, -} - -impl MutableControlAddressesResults { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn governing_address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, RESULT_GOVERNING_ADDRESS.get_key_id()) - } - - pub fn state_controller_address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, RESULT_STATE_CONTROLLER_ADDRESS.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetBlockInfoResults { - pub(crate) id: i32, -} - -impl ImmutableGetBlockInfoResults { - pub fn block_info(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_BLOCK_INFO.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetBlockInfoResults { - pub(crate) id: i32, -} - -impl MutableGetBlockInfoResults { - pub fn block_info(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_BLOCK_INFO.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ArrayOfImmutableBytes { - pub(crate) obj_id: i32, -} - -impl ArrayOfImmutableBytes { - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_bytes(&self, index: i32) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForBlockResults { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForBlockResults { - pub fn event(&self) -> ArrayOfImmutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfImmutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ArrayOfMutableBytes { - pub(crate) obj_id: i32, -} - -impl ArrayOfMutableBytes { - pub fn clear(&self) { - clear(self.obj_id); - } - - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_bytes(&self, index: i32) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForBlockResults { - pub(crate) id: i32, -} - -impl MutableGetEventsForBlockResults { - pub fn event(&self) -> ArrayOfMutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfMutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForContractResults { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForContractResults { - pub fn event(&self) -> ArrayOfImmutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfImmutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForContractResults { - pub(crate) id: i32, -} - -impl MutableGetEventsForContractResults { - pub fn event(&self) -> ArrayOfMutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfMutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetEventsForRequestResults { - pub(crate) id: i32, -} - -impl ImmutableGetEventsForRequestResults { - pub fn event(&self) -> ArrayOfImmutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfImmutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetEventsForRequestResults { - pub(crate) id: i32, -} - -impl MutableGetEventsForRequestResults { - pub fn event(&self) -> ArrayOfMutableBytes { - let arr_id = get_object_id(self.id, RESULT_EVENT.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfMutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetLatestBlockInfoResults { - pub(crate) id: i32, -} - -impl ImmutableGetLatestBlockInfoResults { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn block_info(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_BLOCK_INFO.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetLatestBlockInfoResults { - pub(crate) id: i32, -} - -impl MutableGetLatestBlockInfoResults { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn block_info(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_BLOCK_INFO.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ArrayOfImmutableRequestID { - pub(crate) obj_id: i32, -} - -impl ArrayOfImmutableRequestID { - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_request_id(&self, index: i32) -> ScImmutableRequestID { - ScImmutableRequestID::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestIDsForBlockResults { - pub(crate) id: i32, -} - -impl ImmutableGetRequestIDsForBlockResults { - pub fn request_id(&self) -> ArrayOfImmutableRequestID { - let arr_id = get_object_id(self.id, RESULT_REQUEST_ID.get_key_id(), TYPE_ARRAY16 | TYPE_REQUEST_ID); - ArrayOfImmutableRequestID { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ArrayOfMutableRequestID { - pub(crate) obj_id: i32, -} - -impl ArrayOfMutableRequestID { - pub fn clear(&self) { - clear(self.obj_id); - } - - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_request_id(&self, index: i32) -> ScMutableRequestID { - ScMutableRequestID::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestIDsForBlockResults { - pub(crate) id: i32, -} - -impl MutableGetRequestIDsForBlockResults { - pub fn request_id(&self) -> ArrayOfMutableRequestID { - let arr_id = get_object_id(self.id, RESULT_REQUEST_ID.get_key_id(), TYPE_ARRAY16 | TYPE_REQUEST_ID); - ArrayOfMutableRequestID { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestReceiptResults { - pub(crate) id: i32, -} - -impl ImmutableGetRequestReceiptResults { - pub fn block_index(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn request_index(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, RESULT_REQUEST_INDEX.get_key_id()) - } - - pub fn request_record(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_REQUEST_RECORD.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestReceiptResults { - pub(crate) id: i32, -} - -impl MutableGetRequestReceiptResults { - pub fn block_index(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_BLOCK_INDEX.get_key_id()) - } - - pub fn request_index(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, RESULT_REQUEST_INDEX.get_key_id()) - } - - pub fn request_record(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_REQUEST_RECORD.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetRequestReceiptsForBlockResults { - pub(crate) id: i32, -} - -impl ImmutableGetRequestReceiptsForBlockResults { - pub fn request_record(&self) -> ArrayOfImmutableBytes { - let arr_id = get_object_id(self.id, RESULT_REQUEST_RECORD.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfImmutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetRequestReceiptsForBlockResults { - pub(crate) id: i32, -} - -impl MutableGetRequestReceiptsForBlockResults { - pub fn request_record(&self) -> ArrayOfMutableBytes { - let arr_id = get_object_id(self.id, RESULT_REQUEST_RECORD.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfMutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableIsRequestProcessedResults { - pub(crate) id: i32, -} - -impl ImmutableIsRequestProcessedResults { - pub fn request_processed(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_REQUEST_PROCESSED.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableIsRequestProcessedResults { - pub(crate) id: i32, -} - -impl MutableIsRequestProcessedResults { - pub fn request_processed(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_REQUEST_PROCESSED.get_key_id()) - } -} diff --git a/packages/vm/wasmlib/src/coregovernance/results.rs b/packages/vm/wasmlib/src/coregovernance/results.rs deleted file mode 100644 index d834e234b7..0000000000 --- a/packages/vm/wasmlib/src/coregovernance/results.rs +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -#![allow(dead_code)] -#![allow(unused_imports)] - -use crate::*; -use crate::coregovernance::*; -use crate::host::*; - -#[derive(Clone, Copy)] -pub struct ArrayOfImmutableBytes { - pub(crate) obj_id: i32, -} - -impl ArrayOfImmutableBytes { - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_bytes(&self, index: i32) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetAllowedStateControllerAddressesResults { - pub(crate) id: i32, -} - -impl ImmutableGetAllowedStateControllerAddressesResults { - pub fn allowed_state_controller_addresses(&self) -> ArrayOfImmutableBytes { - let arr_id = get_object_id(self.id, RESULT_ALLOWED_STATE_CONTROLLER_ADDRESSES.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfImmutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ArrayOfMutableBytes { - pub(crate) obj_id: i32, -} - -impl ArrayOfMutableBytes { - pub fn clear(&self) { - clear(self.obj_id); - } - - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } - - pub fn get_bytes(&self, index: i32) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, Key32(index)) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetAllowedStateControllerAddressesResults { - pub(crate) id: i32, -} - -impl MutableGetAllowedStateControllerAddressesResults { - pub fn allowed_state_controller_addresses(&self) -> ArrayOfMutableBytes { - let arr_id = get_object_id(self.id, RESULT_ALLOWED_STATE_CONTROLLER_ADDRESSES.get_key_id(), TYPE_ARRAY16 | TYPE_BYTES); - ArrayOfMutableBytes { obj_id: arr_id } - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetChainInfoResults { - pub(crate) id: i32, -} - -impl ImmutableGetChainInfoResults { - pub fn chain_id(&self) -> ScImmutableChainID { - ScImmutableChainID::new(self.id, RESULT_CHAIN_ID.get_key_id()) - } - - pub fn chain_owner_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) - } - - pub fn default_owner_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_DEFAULT_OWNER_FEE.get_key_id()) - } - - pub fn default_validator_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_DEFAULT_VALIDATOR_FEE.get_key_id()) - } - - pub fn description(&self) -> ScImmutableString { - ScImmutableString::new(self.id, RESULT_DESCRIPTION.get_key_id()) - } - - pub fn fee_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, RESULT_FEE_COLOR.get_key_id()) - } - - pub fn max_blob_size(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_MAX_BLOB_SIZE.get_key_id()) - } - - pub fn max_event_size(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, RESULT_MAX_EVENT_SIZE.get_key_id()) - } - - pub fn max_events_per_req(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, RESULT_MAX_EVENTS_PER_REQ.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetChainInfoResults { - pub(crate) id: i32, -} - -impl MutableGetChainInfoResults { - pub fn chain_id(&self) -> ScMutableChainID { - ScMutableChainID::new(self.id, RESULT_CHAIN_ID.get_key_id()) - } - - pub fn chain_owner_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, RESULT_CHAIN_OWNER_ID.get_key_id()) - } - - pub fn default_owner_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_DEFAULT_OWNER_FEE.get_key_id()) - } - - pub fn default_validator_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_DEFAULT_VALIDATOR_FEE.get_key_id()) - } - - pub fn description(&self) -> ScMutableString { - ScMutableString::new(self.id, RESULT_DESCRIPTION.get_key_id()) - } - - pub fn fee_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, RESULT_FEE_COLOR.get_key_id()) - } - - pub fn max_blob_size(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_MAX_BLOB_SIZE.get_key_id()) - } - - pub fn max_event_size(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, RESULT_MAX_EVENT_SIZE.get_key_id()) - } - - pub fn max_events_per_req(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, RESULT_MAX_EVENTS_PER_REQ.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetFeeInfoResults { - pub(crate) id: i32, -} - -impl ImmutableGetFeeInfoResults { - pub fn fee_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, RESULT_FEE_COLOR.get_key_id()) - } - - pub fn owner_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_OWNER_FEE.get_key_id()) - } - - pub fn validator_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_VALIDATOR_FEE.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetFeeInfoResults { - pub(crate) id: i32, -} - -impl MutableGetFeeInfoResults { - pub fn fee_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, RESULT_FEE_COLOR.get_key_id()) - } - - pub fn owner_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_OWNER_FEE.get_key_id()) - } - - pub fn validator_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_VALIDATOR_FEE.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct ImmutableGetMaxBlobSizeResults { - pub(crate) id: i32, -} - -impl ImmutableGetMaxBlobSizeResults { - pub fn max_blob_size(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, RESULT_MAX_BLOB_SIZE.get_key_id()) - } -} - -#[derive(Clone, Copy)] -pub struct MutableGetMaxBlobSizeResults { - pub(crate) id: i32, -} - -impl MutableGetMaxBlobSizeResults { - pub fn max_blob_size(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, RESULT_MAX_BLOB_SIZE.get_key_id()) - } -} diff --git a/packages/vm/wasmlib/src/events.rs b/packages/vm/wasmlib/src/events.rs deleted file mode 100644 index 19d74cb1df..0000000000 --- a/packages/vm/wasmlib/src/events.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -use crate::context::*; -use crate::hashtypes::*; -use crate::keys::*; - -// encodes separate entities into a byte buffer -pub struct EventEncoder { - event: String, -} - -impl EventEncoder { - // constructs an encoder - pub fn new(event_name: &str) -> EventEncoder { - let mut e = EventEncoder { event: event_name.to_string() }; - let timestamp = ROOT.get_int64(&KEY_TIMESTAMP).value(); - e.int64(timestamp / 1_000_000_000); - e - } - - // encodes an ScAddress into the byte buffer - pub fn address(&mut self, value: &ScAddress) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an ScAgentID into the byte buffer - pub fn agent_id(&mut self, value: &ScAgentID) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes a Bool as 0/1 into the byte buffer - pub fn bool(&mut self, value: bool) -> &EventEncoder { - self.uint8(value as u8) - } - - // encodes a substring of bytes into the byte buffer - pub fn bytes(&mut self, value: &[u8]) -> &EventEncoder { - self.string(&base58_encode(value)) - } - - // encodes an ScChainID into the byte buffer - pub fn chain_id(&mut self, value: &ScChainID) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an ScColor into the byte buffer - pub fn color(&mut self, value: &ScColor) -> &EventEncoder { - self.string(&value.to_string()) - } - - // retrieve the encoded byte buffer - pub fn emit(&self) { - ROOT.get_string(&KEY_EVENT).set_value(&self.event); - } - - // encodes an ScHash into the byte buffer - pub fn hash(&mut self, value: &ScHash) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an ScHname into the byte buffer - pub fn hname(&mut self, value: ScHname) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Int8 into the byte buffer - pub fn int8(&mut self, value: i8) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Int16 into the byte buffer - pub fn int16(&mut self, value: i16) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Int32 into the byte buffer - pub fn int32(&mut self, value: i32) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Int64 into the byte buffer - pub fn int64(&mut self, value: i64) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an ScRequestID into the byte buffer - pub fn request_id(&mut self, value: &ScRequestID) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an UTF-8 text string into the byte buffer - pub fn string(&mut self, value: &str) -> &EventEncoder { - self.event += &("|".to_owned() + value); - self - } - - // encodes an Uint8 into the byte buffer - pub fn uint8(&mut self, value: u8) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Uint16 into the byte buffer - pub fn uint16(&mut self, value: u16) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Uint32 into the byte buffer - pub fn uint32(&mut self, value: u32) -> &EventEncoder { - self.string(&value.to_string()) - } - - // encodes an Uint64 into the byte buffer - pub fn uint64(&mut self, value: u64) -> &EventEncoder { - self.string(&value.to_string()) - } -} diff --git a/packages/vm/wasmlib/src/exports.rs b/packages/vm/wasmlib/src/exports.rs deleted file mode 100644 index 128bf7bf1c..0000000000 --- a/packages/vm/wasmlib/src/exports.rs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// Provide host with details about funcs and views in this smart contract - -use crate::context::*; -use crate::host::*; -use crate::keys::*; -use crate::mutable::*; - -// Note that we do not use the Wasm export symbol table on purpose -// because Wasm does not allow us to determine whether the symbols -// are meant as view or func, or meant as extra public callbacks -// generated by the compilation of the the Wasm code. -// There are only 2 symbols the ISCP host will actually look for -// in the export table: -// on_load (which must be defined by the SC code) and -// on_call (which is defined here as part of WasmLib) - -static mut FUNCS: Vec = vec![]; -static mut VIEWS: Vec = vec![]; - -#[no_mangle] -// general entrypoint for the host to call any SC function -// the host will pass the index of one of the entry points -// that was provided by on_load during SC initialization -fn on_call(index: i32) { - let ctx = ScFuncContext {}; - ctx.require(get_object_id(OBJ_ID_ROOT, KEY_STATE, TYPE_MAP) == OBJ_ID_STATE, "object id mismatch"); - ctx.require(get_object_id(OBJ_ID_ROOT, KEY_PARAMS, TYPE_MAP) == OBJ_ID_PARAMS, "object id mismatch"); - ctx.require(get_object_id(OBJ_ID_ROOT, KEY_RESULTS, TYPE_MAP) == OBJ_ID_RESULTS, "object id mismatch"); - - unsafe { - if (index & 0x8000) != 0 { - // immutable view function, invoke with a view context - VIEWS[(index & 0x7fff) as usize](&ScViewContext {}); - return; - } - - // mutable full function, invoke with a func context - FUNCS[index as usize](&ctx); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// context for on_load function to be able to tell host which -// funcs and views are available as entry points to the SC -pub struct ScExports { - exports: ScMutableStringArray, -} - -impl ScExports { - // constructs the symbol export context for the on_load function - pub fn new() -> ScExports { - let exports = ROOT.get_string_array(&KEY_EXPORTS); - // tell host what value our special predefined key is - // this helps detect versioning problems between host - // and client versions of WasmLib - exports.get_string(KEY_ZZZZZZZ.0).set_value("Rust:KEY_ZZZZZZZ"); - ScExports { exports: exports } - } - - // defines the external name of a smart contract func - // and the entry point function associated with it - pub fn add_func(&self, name: &str, f: fn(&ScFuncContext)) { - unsafe { - let index = FUNCS.len() as i32; - FUNCS.push(f); - self.exports.get_string(index).set_value(name); - } - } - - // defines the external name of a smart contract view - // and the entry point function associated with it - pub fn add_view(&self, name: &str, v: fn(&ScViewContext)) { - unsafe { - let index = VIEWS.len() as i32; - VIEWS.push(v); - self.exports.get_string(index | 0x8000).set_value(name); - } - } -} - diff --git a/packages/vm/wasmlib/src/hashtypes.rs b/packages/vm/wasmlib/src/hashtypes.rs deleted file mode 100644 index 56fdb4ce2c..0000000000 --- a/packages/vm/wasmlib/src/hashtypes.rs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// standard value types used by the ISCP - -use std::convert::TryInto; - -use crate::context::*; -use crate::host::*; -use crate::keys::*; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 33-byte Tangle address ids -#[derive(PartialEq, Clone)] -pub struct ScAddress { - id: [u8; 33], -} - -impl ScAddress { - pub const ZERO: ScAddress = ScAddress { id: [0; 33] }; - - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScAddress { - ScAddress { id: bytes.try_into().expect("invalid address id length") } - } - - // returns agent id representation of this Tangle address - pub fn as_agent_id(&self) -> ScAgentID { - let mut agent_id = ScAgentID { id: [0; 37] }; - agent_id.id[..33].copy_from_slice(&self.id[..33]); - agent_id - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScAddress { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 37-byte agent ids -#[derive(PartialEq, Clone)] -pub struct ScAgentID { - id: [u8; 37], -} - -impl ScAgentID { - pub const ZERO: ScAgentID = ScAgentID { id: [0; 37] }; - - // construct from address and contract name hash - pub fn new(address: &ScAddress, hname: ScHname) -> ScAgentID { - let mut agent_id = ScAgentID { id: [0; 37] }; - agent_id.id[..33].copy_from_slice(&address.to_bytes()); - agent_id.id[33..].copy_from_slice(&hname.to_bytes()); - agent_id - } - - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScAgentID { - ScAgentID { id: bytes.try_into().expect("invalid agent id length") } - } - - // gets Tangle address from agent id - pub fn address(&self) -> ScAddress { - let mut address = ScAddress { id: [0; 33] }; - address.id[..33].copy_from_slice(&self.id[..33]); - address - } - - // get contract name hash for this agent - pub fn hname(&self) -> ScHname { - ScHname::from_bytes(&self.id[33..]) - } - - // checks to see if agent id represents a Tangle address - pub fn is_address(&self) -> bool { - self.hname() == ScHname(0) - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScAgentID { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 33-byte chain ids -#[derive(PartialEq, Clone)] -pub struct ScChainID { - id: [u8; 33], -} - -impl ScChainID { - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScChainID { - ScChainID { id: bytes.try_into().expect("invalid chain id length") } - } - - // gets Tangle address from chain id - pub fn address(&self) -> ScAddress { - let mut address = ScAddress { id: [0; 33] }; - address.id[..33].copy_from_slice(&self.id[..33]); - address - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScChainID { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 32-byte token color -#[derive(PartialEq, Clone)] -pub struct ScColor { - id: [u8; 32], -} - -impl ScColor { - // predefined colors - pub const IOTA: ScColor = ScColor { id: [0x00; 32] }; - pub const MINT: ScColor = ScColor { id: [0xff; 32] }; - - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScColor { - ScColor { id: bytes.try_into().expect("invalid color id length") } - } - - // construct from request id, this will return newly minted color - pub fn from_request_id(request_id: &ScRequestID) -> ScColor { - let mut color = ScColor { id: [0x00; 32] }; - color.id[..].copy_from_slice(&request_id.id[..]); - color - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScColor { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 32-byte hash value -#[derive(PartialEq, Clone)] -pub struct ScHash { - id: [u8; 32], -} - -impl ScHash { - pub const ZERO: ScHash = ScHash { id: [0; 32] }; - - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScHash { - ScHash { id: bytes.try_into().expect("invalid hash id length") } - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScHash { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 4-byte name hash -#[derive(PartialEq, Clone, Copy)] -pub struct ScHname(pub u32); - -impl ScHname { - // construct from name string - pub fn new(name: &str) -> ScHname { - ScFuncContext {}.utility().hname(name) - } - - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScHname { - let val = u32::from_le_bytes(bytes.try_into().expect("invalid hname length")); - ScHname(val) - } - - // convert to byte array representation - pub fn to_bytes(&self) -> Vec { - self.0.to_le_bytes().to_vec() - } - - // human-readable string representation: 8 hex digits - pub fn to_string(&self) -> String { - let hex = "0123456789abcdef".as_bytes(); - let mut res = [0u8; 8]; - let mut val = self.0; - for n in 0..8 { - res[7 - n] = hex[val as usize & 0x0f]; - val >>= 4; - } - String::from_utf8(res.to_vec()).expect("WTF? invalid?") - } -} - -// can be used as key in maps -impl MapKey for ScHname { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.0.to_le_bytes()) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 34-byte transaction request ids -#[derive(PartialEq, Clone)] -pub struct ScRequestID { - id: [u8; 34], -} - -impl ScRequestID { - // construct from byte array - pub fn from_bytes(bytes: &[u8]) -> ScRequestID { - ScRequestID { id: bytes.try_into().expect("invalid request id length") } - } - - // convert to byte array representation - pub fn to_bytes(&self) -> &[u8] { - &self.id - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.id) - } -} - -// can be used as key in maps -impl MapKey for ScRequestID { - fn get_key_id(&self) -> Key32 { - get_key_id_from_bytes(&self.id) - } -} diff --git a/packages/vm/wasmlib/src/host.rs b/packages/vm/wasmlib/src/host.rs deleted file mode 100644 index 72cac67eea..0000000000 --- a/packages/vm/wasmlib/src/host.rs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// interface WasmLib to the VM host - -use std::convert::TryInto; - -use crate::keys::*; - -// all type id values should exactly match their counterpart values on the host! -pub const TYPE_ARRAY: i32 = 0x20; -pub const TYPE_ARRAY16: i32 = 0x60; -pub const TYPE_CALL: i32 = 0x80; -pub const TYPE_MASK: i32 = 0x1f; - -pub const TYPE_ADDRESS: i32 = 1; -pub const TYPE_AGENT_ID: i32 = 2; -pub const TYPE_BOOL: i32 = 3; -pub const TYPE_BYTES: i32 = 4; -pub const TYPE_CHAIN_ID: i32 = 5; -pub const TYPE_COLOR: i32 = 6; -pub const TYPE_HASH: i32 = 7; -pub const TYPE_HNAME: i32 = 8; -pub const TYPE_INT8: i32 = 9; -pub const TYPE_INT16: i32 = 10; -pub const TYPE_INT32: i32 = 11; -pub const TYPE_INT64: i32 = 12; -pub const TYPE_MAP: i32 = 13; -pub const TYPE_REQUEST_ID: i32 = 14; -pub const TYPE_STRING: i32 = 15; - -pub const OBJ_ID_NULL: i32 = 0; -pub const OBJ_ID_ROOT: i32 = 1; -pub const OBJ_ID_STATE: i32 = 2; -pub const OBJ_ID_PARAMS: i32 = 3; -pub const OBJ_ID_RESULTS: i32 = 4; - -// size in bytes of predefined types, indexed by the TYPE_* consts -const TYPE_SIZES: &[u8] = &[0, 33, 37, 1, 0, 33, 32, 32, 4, 1, 2, 4, 8, 0, 34, 0]; - -// These 4 external functions are funneling the entire WasmLib functionality -// to their counterparts on the host. -#[link(wasm_import_module = "WasmLib")] -extern { - // Copy the value data bytes of type stored in the host container object , - // under key , into the pre-allocated which can hold len bytes. - // Returns the actual length of the value data bytes on the host. - pub fn hostGetBytes(obj_id: i32, key_id: i32, type_id: i32, buffer: *const u8, size: i32) -> i32; - - // Retrieve the key id associated with the data bytes of length . - // A negative length indicates a bytes key, positive indicates a string key - // We discern between the two for better readable logging purposes - pub fn hostGetKeyID(key: *const u8, size: i32) -> i32; - - // Retrieve the id of the container sub-object of type stored in - // the host container object , under key . - pub fn hostGetObjectID(obj_id: i32, key_id: i32, type_id: i32) -> i32; - - // copy the value data bytes of type from the - // into the host container object , under key . - pub fn hostSetBytes(obj_id: i32, key_id: i32, type_id: i32, buffer: *const u8, size: i32); -} - -pub fn call_func(obj_id: i32, key_id: Key32, params: &[u8]) -> Vec { - unsafe { - let mut args = std::ptr::null(); - let mut size = params.len() as i32; - if size != 0 { - args = params.as_ptr(); - } - - // variable-sized type, first query expected length of bytes array - // (pass zero-length buffer) - size = hostGetBytes(obj_id, key_id.0, TYPE_CALL, args, size); - - // -1 means non-existent, so return default value for type - if size <= 0 { - return vec![0_u8; 0]; - } - - // allocate a sufficient length byte array in Wasm memory - // and let the host copy the actual data bytes into this Wasm byte array - let mut result = vec![0_u8; size as usize]; - hostGetBytes(obj_id, key_id.0, TYPE_CALL + 1, result.as_mut_ptr(), size); - return result; - } -} - -// Clear the entire contents of the specified container object. -// Removes all its sub-objects as well. -pub fn clear(obj_id: i32) { - // special key "length" is used with integer value zero - set_bytes(obj_id, KEY_LENGTH, TYPE_INT32, &0_i32.to_le_bytes()) -} - -// Delete the value with the specified key and type from the specified container object. -pub fn del_key(obj_id: i32, key_id: Key32, type_id: i32) { - unsafe { - // size -1 means delete - // this removes the need for a separate hostDelete function - hostSetBytes(obj_id, key_id.0, type_id, std::ptr::null_mut(), -1); - } -} - -// Check if the specified container object contains a value with the specified key and type. -pub fn exists(obj_id: i32, key_id: Key32, type_id: i32) -> bool { - unsafe { - // size -1 means only test for existence - // returned size -1 indicates keyID not found (or error) - // this removes the need for a separate hostExists function - hostGetBytes(obj_id, key_id.0, type_id, std::ptr::null_mut(), -1) >= 0 - } -} - -// Retrieve the bytes stored in the specified container object under the specified key -// and with specified type. Note that if the key does not exist this function will -// return the default value for the specified type. -pub fn get_bytes(obj_id: i32, key_id: Key32, type_id: i32) -> Vec { - unsafe { - let mut size = TYPE_SIZES[type_id as usize] as i32; - if size == 0 { - // variable-sized type, first query expected length of bytes array - // (pass zero-length buffer) - size = hostGetBytes(obj_id, key_id.0, type_id, std::ptr::null_mut(), 0); - - // -1 means non-existent, so return default value for type - if size < 0 { - return vec![0_u8; 0]; - } - } - - // allocate a sufficiently sized byte array in Wasm memory - // and let the host copy the actual data bytes into this Wasm byte array - let mut result = vec![0_u8; size as usize]; - hostGetBytes(obj_id, key_id.0, type_id, result.as_mut_ptr(), size); - return result; - } -} - -// Retrieve the key id that the host has associated with the specified bytes key -pub fn get_key_id_from_bytes(bytes: &[u8]) -> Key32 { - unsafe { - let size = bytes.len() as i32; - // negative size indicates this is a bytes key - Key32(hostGetKeyID(bytes.as_ptr(), -size - 1)) - } -} - -// Retrieve the key id that the host has associated with the specified string key -pub fn get_key_id_from_string(key: &str) -> Key32 { - let bytes = key.as_bytes(); - unsafe { - // non-negative size indicates this is a string key - Key32(hostGetKeyID(bytes.as_ptr(), bytes.len() as i32)) - } -} - -// Retrieve the key id that the host has associated with the specified integer key -pub fn get_key_id_from_uint64(key: u64, nr_of_bytes: usize) -> Key32 { - let bytes = key.to_le_bytes(); - get_key_id_from_bytes(&bytes[..nr_of_bytes]) -} - -// Retrieve the length of an array container object on the host -pub fn get_length(obj_id: i32) -> i32 { - // special integer key "length" is used - let bytes = get_bytes(obj_id, KEY_LENGTH, TYPE_INT32); - i32::from_le_bytes(bytes.try_into().unwrap()) -} - -// Retrieve the id of the specified container sub-object -pub fn get_object_id(obj_id: i32, key_id: Key32, type_id: i32) -> i32 { - unsafe { - hostGetObjectID(obj_id, key_id.0, type_id) - } -} - -// Direct logging of informational text to host log -pub fn log(text: &str) { - set_bytes(1, KEY_LOG, TYPE_STRING, text.as_bytes()) -} - -// Direct logging of error to host log, followed by panicking out of the Wasm code -pub fn panic(text: &str) { - set_bytes(1, KEY_PANIC, TYPE_STRING, text.as_bytes()) -} - -// Store the provided value bytes of specified type in the specified container object -// under the specified key. Note that if the key does not exist this function will -// create it first. -pub fn set_bytes(obj_id: i32, key_id: Key32, type_id: i32, value: &[u8]) { - unsafe { - hostSetBytes(obj_id, key_id.0, type_id, value.as_ptr(), value.len() as i32) - } -} - -// Direct logging of debug trace text to host log -pub fn trace(text: &str) { - set_bytes(1, KEY_TRACE, TYPE_STRING, text.as_bytes()) -} diff --git a/packages/vm/wasmlib/src/immutable.rs b/packages/vm/wasmlib/src/immutable.rs deleted file mode 100644 index 577c1b0a00..0000000000 --- a/packages/vm/wasmlib/src/immutable.rs +++ /dev/null @@ -1,1128 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// immutable proxies to host objects - -use std::convert::TryInto; - -use crate::context::*; -use crate::hashtypes::*; -use crate::host::*; -use crate::keys::*; - -// value proxy for immutable ScAddress in host container -pub struct ScImmutableAddress { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableAddress { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableAddress { - ScImmutableAddress { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_ADDRESS) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScAddress { - ScAddress::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_ADDRESS)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScAddress -pub struct ScImmutableAddressArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableAddressArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_address(&self, index: i32) -> ScImmutableAddress { - ScImmutableAddress { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScAgentID in host container -pub struct ScImmutableAgentID { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableAgentID { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableAgentID { - ScImmutableAgentID { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_AGENT_ID) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScAgentID { - ScAgentID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_AGENT_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScAgentID -pub struct ScImmutableAgentIDArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableAgentIDArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_agent_id(&self, index: i32) -> ScImmutableAgentID { - ScImmutableAgentID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Bool in host container -pub struct ScImmutableBool { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableBool { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableBool { - ScImmutableBool { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BOOL) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> bool { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_BOOL); - bytes[0] != 0 - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Bool -pub struct ScImmutableBoolArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableBoolArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_bool(&self, index: i32) -> ScImmutableBool { - ScImmutableBool { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable bytes array in host container -pub struct ScImmutableBytes { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableBytes { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableBytes { - ScImmutableBytes { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.value()) - } - - // get value from host container - pub fn value(&self) -> Vec { - get_bytes(self.obj_id, self.key_id, TYPE_BYTES) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of byte array -pub struct ScImmutableBytesArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableBytesArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_bytes(&self, index: i32) -> ScImmutableBytes { - ScImmutableBytes { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScChainID in host container -pub struct ScImmutableChainID { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableChainID { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableChainID { - ScImmutableChainID { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_CHAIN_ID) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScChainID { - ScChainID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_CHAIN_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScChainID -pub struct ScImmutableChainIDArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableChainIDArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_chain_id(&self, index: i32) -> ScImmutableChainID { - ScImmutableChainID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScColor in host container -pub struct ScImmutableColor { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableColor { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableColor { - ScImmutableColor { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_COLOR) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScColor { - ScColor::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_COLOR)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScColor -pub struct ScImmutableColorArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableColorArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_color(&self, index: i32) -> ScImmutableColor { - ScImmutableColor { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScHash in host container -pub struct ScImmutableHash { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableHash { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableHash { - ScImmutableHash { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_HASH) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScHash { - ScHash::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_HASH)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScHash -pub struct ScImmutableHashArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableHashArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_hash(&self, index: i32) -> ScImmutableHash { - ScImmutableHash { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScHname in host container -pub struct ScImmutableHname { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableHname { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableHname { - ScImmutableHname { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_HNAME) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScHname { - ScHname::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_HNAME)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScHname -pub struct ScImmutableHnameArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableHnameArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_hname(&self, index: i32) -> ScImmutableHname { - ScImmutableHname { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int8 in host container -pub struct ScImmutableInt8 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableInt8 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableInt8 { - ScImmutableInt8 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT8) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> i8 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT8); - bytes[0] as i8 - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int8 -pub struct ScImmutableInt8Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableInt8Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_int8(&self, index: i32) -> ScImmutableInt8 { - ScImmutableInt8 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int16 in host container -pub struct ScImmutableInt16 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableInt16 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableInt16 { - ScImmutableInt16 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT16) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> i16 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT16); - i16::from_le_bytes(bytes.try_into().expect("invalid i16 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int16 -pub struct ScImmutableInt16Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableInt16Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_int16(&self, index: i32) -> ScImmutableInt16 { - ScImmutableInt16 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int32 in host container -pub struct ScImmutableInt32 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableInt32 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableInt32 { - ScImmutableInt32 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT32) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> i32 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT32); - i32::from_le_bytes(bytes.try_into().expect("invalid i32 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int32 -pub struct ScImmutableInt32Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableInt32Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_int32(&self, index: i32) -> ScImmutableInt32 { - ScImmutableInt32 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int64 in host container -pub struct ScImmutableInt64 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableInt64 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableInt64 { - ScImmutableInt64 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT64) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> i64 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT64); - i64::from_le_bytes(bytes.try_into().expect("invalid i64 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int64 -pub struct ScImmutableInt64Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableInt64Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_int64(&self, index: i32) -> ScImmutableInt64 { - ScImmutableInt64 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// map proxy for immutable map -pub struct ScImmutableMap { - pub(crate) obj_id: i32, -} - -impl ScImmutableMap { - pub fn call_func(&self, key_id: Key32, params: &[u8]) -> Vec { - call_func(self.obj_id, key_id, params) - } - - // get value proxy for immutable ScAddress field specified by key - pub fn get_address(&self, key: &T) -> ScImmutableAddress { - ScImmutableAddress { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableAddressArray specified by key - pub fn get_address_array(&self, key: &T) -> ScImmutableAddressArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ADDRESS | TYPE_ARRAY); - ScImmutableAddressArray { obj_id: arr_id } - } - - // get value proxy for immutable ScAgentID field specified by key - pub fn get_agent_id(&self, key: &T) -> ScImmutableAgentID { - ScImmutableAgentID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableAgentIDArray specified by key - pub fn get_agent_id_array(&self, key: &T) -> ScImmutableAgentIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_AGENT_ID | TYPE_ARRAY); - ScImmutableAgentIDArray { obj_id: arr_id } - } - - // get value proxy for immutable Bool field specified by key - pub fn get_bool(&self, key: &T) -> ScImmutableBool { - ScImmutableBool { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableBoolArray specified by key - pub fn get_bool_array(&self, key: &T) -> ScImmutableBoolArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_BOOL | TYPE_ARRAY); - ScImmutableBoolArray { obj_id: arr_id } - } - - // get value proxy for immutable bytes array field specified by key - pub fn get_bytes(&self, key: &T) -> ScImmutableBytes { - ScImmutableBytes { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableBytesArray specified by key - pub fn get_bytes_array(&self, key: &T) -> ScImmutableBytesArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_BYTES | TYPE_ARRAY); - ScImmutableBytesArray { obj_id: arr_id } - } - - // get value proxy for immutable ScChainID field specified by key - pub fn get_chain_id(&self, key: &T) -> ScImmutableChainID { - ScImmutableChainID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableChainIDArray specified by key - pub fn get_chain_id_array(&self, key: &T) -> ScImmutableChainIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_CHAIN_ID | TYPE_ARRAY); - ScImmutableChainIDArray { obj_id: arr_id } - } - - // get value proxy for immutable ScColor field specified by key - pub fn get_color(&self, key: &T) -> ScImmutableColor { - ScImmutableColor { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableColorArray specified by key - pub fn get_color_array(&self, key: &T) -> ScImmutableColorArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_COLOR | TYPE_ARRAY); - ScImmutableColorArray { obj_id: arr_id } - } - - // get value proxy for immutable ScHash field specified by key - pub fn get_hash(&self, key: &T) -> ScImmutableHash { - ScImmutableHash { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableHashArray specified by key - pub fn get_hash_array(&self, key: &T) -> ScImmutableHashArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_HASH | TYPE_ARRAY); - ScImmutableHashArray { obj_id: arr_id } - } - - // get value proxy for immutable ScHname field specified by key - pub fn get_hname(&self, key: &T) -> ScImmutableHname { - ScImmutableHname { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableHnameArray specified by key - pub fn get_hname_array(&self, key: &T) -> ScImmutableHnameArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_HNAME | TYPE_ARRAY); - ScImmutableHnameArray { obj_id: arr_id } - } - - // get value proxy for immutable Int8 field specified by key - pub fn get_int8(&self, key: &T) -> ScImmutableInt8 { - ScImmutableInt8 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableInt8Array specified by key - pub fn get_int8_array(&self, key: &T) -> ScImmutableInt8Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT8 | TYPE_ARRAY); - ScImmutableInt8Array { obj_id: arr_id } - } - - // get value proxy for immutable Int16 field specified by key - pub fn get_int16(&self, key: &T) -> ScImmutableInt16 { - ScImmutableInt16 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableInt16Array specified by key - pub fn get_int16_array(&self, key: &T) -> ScImmutableInt16Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT16 | TYPE_ARRAY); - ScImmutableInt16Array { obj_id: arr_id } - } - - // get value proxy for immutable Int32 field specified by key - pub fn get_int32(&self, key: &T) -> ScImmutableInt32 { - ScImmutableInt32 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableInt32Array specified by key - pub fn get_int32_array(&self, key: &T) -> ScImmutableInt32Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT32 | TYPE_ARRAY); - ScImmutableInt32Array { obj_id: arr_id } - } - - // get value proxy for immutable Int64 field specified by key - pub fn get_int64(&self, key: &T) -> ScImmutableInt64 { - ScImmutableInt64 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableInt64Array specified by key - pub fn get_int64_array(&self, key: &T) -> ScImmutableInt64Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT64 | TYPE_ARRAY); - ScImmutableInt64Array { obj_id: arr_id } - } - - // get map proxy for ScImmutableMap specified by key - pub fn get_map(&self, key: &T) -> ScImmutableMap { - let map_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ScImmutableMap { obj_id: map_id } - } - - // get array proxy for ScImmutableMapArray specified by key - pub fn get_map_array(&self, key: &T) -> ScImmutableMapArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP | TYPE_ARRAY); - ScImmutableMapArray { obj_id: arr_id } - } - - // get value proxy for immutable ScRequestID field specified by key - pub fn get_request_id(&self, key: &T) -> ScImmutableRequestID { - ScImmutableRequestID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableRequestIDArray specified by key - pub fn get_request_id_array(&self, key: &T) -> ScImmutableRequestIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_REQUEST_ID | TYPE_ARRAY); - ScImmutableRequestIDArray { obj_id: arr_id } - } - - // get value proxy for immutable UTF-8 text string field specified by key - pub fn get_string(&self, key: &T) -> ScImmutableString { - ScImmutableString { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableStringArray specified by key - pub fn get_string_array(&self, key: &T) -> ScImmutableStringArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_STRING | TYPE_ARRAY); - ScImmutableStringArray { obj_id: arr_id } - } - - // get value proxy for immutable Uint8 field specified by key - pub fn get_uint8(&self, key: &T) -> ScImmutableUint8 { - ScImmutableUint8 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableUint8Array specified by key - pub fn get_uint8_array(&self, key: &T) -> ScImmutableUint8Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT8 | TYPE_ARRAY); - ScImmutableUint8Array { obj_id: arr_id } - } - - // get value proxy for immutable Uint16 field specified by key - pub fn get_uint16(&self, key: &T) -> ScImmutableUint16 { - ScImmutableUint16 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableUint16Array specified by key - pub fn get_uint16_array(&self, key: &T) -> ScImmutableUint16Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT16 | TYPE_ARRAY); - ScImmutableUint16Array { obj_id: arr_id } - } - - // get value proxy for immutable Uint32 field specified by key - pub fn get_uint32(&self, key: &T) -> ScImmutableUint32 { - ScImmutableUint32 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableUint32Array specified by key - pub fn get_uint32_array(&self, key: &T) -> ScImmutableUint32Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT32 | TYPE_ARRAY); - ScImmutableUint32Array { obj_id: arr_id } - } - - // get value proxy for immutable Uint64 field specified by key - pub fn get_uint64(&self, key: &T) -> ScImmutableUint64 { - ScImmutableUint64 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScImmutableUint64Array specified by key - pub fn get_uint64_array(&self, key: &T) -> ScImmutableUint64Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT64 | TYPE_ARRAY); - ScImmutableUint64Array { obj_id: arr_id } - } - - pub fn map_id(&self) -> i32 { - self.obj_id - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of maps -pub struct ScImmutableMapArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableMapArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_map(&self, index: i32) -> ScImmutableMap { - let map_id = get_object_id(self.obj_id, Key32(index), TYPE_MAP); - ScImmutableMap { obj_id: map_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// value proxy for immutable ScRequestID in host container -pub struct ScImmutableRequestID { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableRequestID { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableRequestID { - ScImmutableRequestID { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_REQUEST_ID) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> ScRequestID { - ScRequestID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_REQUEST_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScRequestID -pub struct ScImmutableRequestIDArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableRequestIDArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_request_id(&self, index: i32) -> ScImmutableRequestID { - ScImmutableRequestID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable UTF-8 text string in host container -pub struct ScImmutableString { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableString { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableString { - ScImmutableString { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_STRING) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value() - } - - // get value from host container - pub fn value(&self) -> String { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_STRING); - unsafe { String::from_utf8_unchecked(bytes) } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of UTF-8 text string -pub struct ScImmutableStringArray { - pub(crate) obj_id: i32, -} - -impl ScImmutableStringArray { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_string(&self, index: i32) -> ScImmutableString { - ScImmutableString { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint8 in host container -pub struct ScImmutableUint8 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableUint8 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableUint8 { - ScImmutableUint8 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT8) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> u8 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT8); - bytes[0] - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint8 -pub struct ScImmutableUint8Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableUint8Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_uint8(&self, index: i32) -> ScImmutableUint8 { - ScImmutableUint8 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint16 in host container -pub struct ScImmutableUint16 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableUint16 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableUint16 { - ScImmutableUint16 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT16) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> u16 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT16); - u16::from_le_bytes(bytes.try_into().expect("invalid u16 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint16 -pub struct ScImmutableUint16Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableUint16Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_uint16(&self, index: i32) -> ScImmutableUint16 { - ScImmutableUint16 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint32 in host container -pub struct ScImmutableUint32 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableUint32 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableUint32 { - ScImmutableUint32 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT32) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> u32 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT32); - u32::from_le_bytes(bytes.try_into().expect("invalid u32 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint32 -pub struct ScImmutableUint32Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableUint32Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_uint32(&self, index: i32) -> ScImmutableUint32 { - ScImmutableUint32 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint64 in host container -pub struct ScImmutableUint64 { - obj_id: i32, - key_id: Key32, -} - -impl ScImmutableUint64 { - pub fn new(obj_id: i32, key_id: Key32) -> ScImmutableUint64 { - ScImmutableUint64 { obj_id, key_id } - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT64) - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // get value from host container - pub fn value(&self) -> u64 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT64); - u64::from_le_bytes(bytes.try_into().expect("invalid u64 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint64 -pub struct ScImmutableUint64Array { - pub(crate) obj_id: i32, -} - -impl ScImmutableUint64Array { - // get value proxy for item at index, index can be 0..length()-1 - pub fn get_uint64(&self, index: i32) -> ScImmutableUint64 { - ScImmutableUint64 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} diff --git a/packages/vm/wasmlib/src/keys.rs b/packages/vm/wasmlib/src/keys.rs deleted file mode 100644 index 6e1d9b2acb..0000000000 --- a/packages/vm/wasmlib/src/keys.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -use crate::host::*; - -// conversion of data bytes to key id -pub trait MapKey { - fn get_key_id(&self) -> Key32; -} - -// implementations for both flavors of Rust string -impl MapKey for str { - fn get_key_id(&self) -> Key32 { - get_key_id_from_string(self) - } -} - -impl MapKey for String { - fn get_key_id(&self) -> Key32 { - get_key_id_from_string(self) - } -} - -// special type for predefined key ids -#[derive(Clone, Copy)] -pub struct Key32(pub i32); - -// implementation for predefined key ids -impl MapKey for Key32 { - fn get_key_id(&self) -> Key32 { - *self - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// all predefined key id values should exactly match their counterpart values on the host! -// note that predefined key ids are negative values to distinguish them from indexes - -// @formatter:off -pub const KEY_ACCOUNT_ID : Key32 = Key32(-1); -pub const KEY_ADDRESS : Key32 = Key32(-2); -pub const KEY_BALANCES : Key32 = Key32(-3); -pub const KEY_BASE58_DECODE : Key32 = Key32(-4); -pub const KEY_BASE58_ENCODE : Key32 = Key32(-5); -pub const KEY_BLS_ADDRESS : Key32 = Key32(-6); -pub const KEY_BLS_AGGREGATE : Key32 = Key32(-7); -pub const KEY_BLS_VALID : Key32 = Key32(-8); -pub const KEY_CALL : Key32 = Key32(-9); -pub const KEY_CALLER : Key32 = Key32(-10); -pub const KEY_CHAIN_ID : Key32 = Key32(-11); -pub const KEY_CHAIN_OWNER_ID : Key32 = Key32(-12); -pub const KEY_COLOR : Key32 = Key32(-13); -pub const KEY_CONTRACT : Key32 = Key32(-14); -pub const KEY_CONTRACT_CREATOR : Key32 = Key32(-15); -pub const KEY_DEPLOY : Key32 = Key32(-16); -pub const KEY_ED25519_ADDRESS : Key32 = Key32(-17); -pub const KEY_ED25519_VALID : Key32 = Key32(-18); -pub const KEY_EVENT : Key32 = Key32(-19); -pub const KEY_EXPORTS : Key32 = Key32(-20); -pub const KEY_HASH_BLAKE2B : Key32 = Key32(-21); -pub const KEY_HASH_SHA3 : Key32 = Key32(-22); -pub const KEY_HNAME : Key32 = Key32(-23); -pub const KEY_INCOMING : Key32 = Key32(-24); -pub const KEY_LENGTH : Key32 = Key32(-25); -pub const KEY_LOG : Key32 = Key32(-26); -pub const KEY_MAPS : Key32 = Key32(-27); -pub const KEY_MINTED : Key32 = Key32(-28); -pub const KEY_PANIC : Key32 = Key32(-29); -pub const KEY_PARAMS : Key32 = Key32(-30); -pub const KEY_POST : Key32 = Key32(-31); -pub const KEY_RANDOM : Key32 = Key32(-32); -pub const KEY_REQUEST_ID : Key32 = Key32(-33); -pub const KEY_RESULTS : Key32 = Key32(-34); -pub const KEY_RETURN : Key32 = Key32(-35); -pub const KEY_STATE : Key32 = Key32(-36); -pub const KEY_TIMESTAMP : Key32 = Key32(-37); -pub const KEY_TRACE : Key32 = Key32(-38); -pub const KEY_TRANSFERS : Key32 = Key32(-39); -pub const KEY_UTILITY : Key32 = Key32(-40); -pub const KEY_ZZZZZZZ : Key32 = Key32(-41); -// @formatter:on diff --git a/packages/vm/wasmlib/src/mutable.rs b/packages/vm/wasmlib/src/mutable.rs deleted file mode 100644 index 8ffaca21b0..0000000000 --- a/packages/vm/wasmlib/src/mutable.rs +++ /dev/null @@ -1,1542 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// mutable proxies to host objects - -use std::convert::TryInto; - -use crate::context::*; -use crate::hashtypes::*; -use crate::host::*; -use crate::immutable::*; -use crate::keys::*; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScAddress in host container -pub struct ScMutableAddress { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableAddress { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableAddress { - ScMutableAddress { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_ADDRESS); - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_ADDRESS) - } - - // set value in host container - pub fn set_value(&self, val: &ScAddress) { - set_bytes(self.obj_id, self.key_id, TYPE_ADDRESS, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScAddress { - ScAddress::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_ADDRESS)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScAddress -pub struct ScMutableAddressArray { - pub(crate) obj_id: i32, -} - -impl ScMutableAddressArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_address(&self, index: i32) -> ScMutableAddress { - ScMutableAddress { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableAddressArray { - ScImmutableAddressArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScAgentID in host container -pub struct ScMutableAgentID { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableAgentID { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableAgentID { - ScMutableAgentID { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_AGENT_ID) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_AGENT_ID) - } - - // set value in host container - pub fn set_value(&self, val: &ScAgentID) { - set_bytes(self.obj_id, self.key_id, TYPE_AGENT_ID, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScAgentID { - ScAgentID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_AGENT_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScAgentID -pub struct ScMutableAgentIDArray { - pub(crate) obj_id: i32, -} - -impl ScMutableAgentIDArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_agent_id(&self, index: i32) -> ScMutableAgentID { - ScMutableAgentID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableAgentIDArray { - ScImmutableAgentIDArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Bool in host container -pub struct ScMutableBool { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableBool { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableBool { - ScMutableBool { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BOOL) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BOOL) - } - - // set value in host container - pub fn set_value(&self, val: bool) { - let bytes = [val as u8]; - set_bytes(self.obj_id, self.key_id, TYPE_BOOL, &bytes); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> bool { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_BOOL); - bytes[0] != 0 - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Bool -pub struct ScMutableBoolArray { - pub(crate) obj_id: i32, -} - -impl ScMutableBoolArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_bool(&self, index: i32) -> ScMutableBool { - ScMutableBool { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableBoolArray { - ScImmutableBoolArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable bytes array in host container -pub struct ScMutableBytes { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableBytes { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableBytes { - ScMutableBytes { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) - } - - // set value in host container - pub fn set_value(&self, val: &[u8]) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, val); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - base58_encode(&self.value()) - } - - // retrieve value from host container - pub fn value(&self) -> Vec { - get_bytes(self.obj_id, self.key_id, TYPE_BYTES) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of byte array -pub struct ScMutableBytesArray { - pub(crate) obj_id: i32, -} - -impl ScMutableBytesArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_bytes(&self, index: i32) -> ScMutableBytes { - ScMutableBytes { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableBytesArray { - ScImmutableBytesArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScChainID in host container -pub struct ScMutableChainID { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableChainID { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableChainID { - ScMutableChainID { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_CHAIN_ID) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_CHAIN_ID) - } - - // set value in host container - pub fn set_value(&self, val: &ScChainID) { - set_bytes(self.obj_id, self.key_id, TYPE_CHAIN_ID, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScChainID { - ScChainID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_CHAIN_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScChainID -pub struct ScMutableChainIDArray { - pub(crate) obj_id: i32, -} - -impl ScMutableChainIDArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_chain_id(&self, index: i32) -> ScMutableChainID { - ScMutableChainID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableChainIDArray { - ScImmutableChainIDArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScColor in host container -pub struct ScMutableColor { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableColor { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableColor { - ScMutableColor { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_COLOR) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_COLOR) - } - - // set value in host container - pub fn set_value(&self, val: &ScColor) { - set_bytes(self.obj_id, self.key_id, TYPE_COLOR, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScColor { - ScColor::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_COLOR)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScColor -pub struct ScMutableColorArray { - pub(crate) obj_id: i32, -} - -impl ScMutableColorArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_color(&self, index: i32) -> ScMutableColor { - ScMutableColor { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableColorArray { - ScImmutableColorArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScHash in host container -pub struct ScMutableHash { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableHash { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableHash { - ScMutableHash { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_HASH) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_HASH) - } - - // set value in host container - pub fn set_value(&self, val: &ScHash) { - set_bytes(self.obj_id, self.key_id, TYPE_HASH, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScHash { - ScHash::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_HASH)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScHash -pub struct ScMutableHashArray { - pub(crate) obj_id: i32, -} - -impl ScMutableHashArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_hash(&self, index: i32) -> ScMutableHash { - ScMutableHash { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableHashArray { - ScImmutableHashArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScHname in host container -pub struct ScMutableHname { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableHname { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableHname { - ScMutableHname { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_HNAME) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_HNAME) - } - - // set value in host container - pub fn set_value(&self, val: ScHname) { - set_bytes(self.obj_id, self.key_id, TYPE_HNAME, &val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScHname { - ScHname::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_HNAME)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScHname -pub struct ScMutableHnameArray { - pub(crate) obj_id: i32, -} - -impl ScMutableHnameArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_hname(&self, index: i32) -> ScMutableHname { - ScMutableHname { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableHnameArray { - ScImmutableHnameArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int8 in host container -pub struct ScMutableInt8 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableInt8 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableInt8 { - ScMutableInt8 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT8) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT8) - } - - // set value in host container - pub fn set_value(&self, val: i8) { - let bytes = [val as u8]; - set_bytes(self.obj_id, self.key_id, TYPE_INT8, &bytes); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> i8 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT8); - bytes[0] as i8 - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int8 -pub struct ScMutableInt8Array { - pub(crate) obj_id: i32, -} - -impl ScMutableInt8Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_int8(&self, index: i32) -> ScMutableInt8 { - ScMutableInt8 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableInt8Array { - ScImmutableInt8Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int16 in host container -pub struct ScMutableInt16 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableInt16 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableInt16 { - ScMutableInt16 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT16) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT16) - } - - // set value in host container - pub fn set_value(&self, val: i16) { - set_bytes(self.obj_id, self.key_id, TYPE_INT16, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> i16 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT16); - i16::from_le_bytes(bytes.try_into().expect("invalid i16 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int16 -pub struct ScMutableInt16Array { - pub(crate) obj_id: i32, -} - -impl ScMutableInt16Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_int16(&self, index: i32) -> ScMutableInt16 { - ScMutableInt16 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableInt16Array { - ScImmutableInt16Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int32 in host container -pub struct ScMutableInt32 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableInt32 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableInt32 { - ScMutableInt32 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT32) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT32) - } - - // set value in host container - pub fn set_value(&self, val: i32) { - set_bytes(self.obj_id, self.key_id, TYPE_INT32, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> i32 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT32); - i32::from_le_bytes(bytes.try_into().expect("invalid i32 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int32 -pub struct ScMutableInt32Array { - pub(crate) obj_id: i32, -} - -impl ScMutableInt32Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_int32(&self, index: i32) -> ScMutableInt32 { - ScMutableInt32 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableInt32Array { - ScImmutableInt32Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int64 in host container -pub struct ScMutableInt64 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableInt64 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableInt64 { - ScMutableInt64 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT64) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT64) - } - - // set value in host container - pub fn set_value(&self, val: i64) { - set_bytes(self.obj_id, self.key_id, TYPE_INT64, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> i64 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT64); - i64::from_le_bytes(bytes.try_into().expect("invalid i64 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int64 -pub struct ScMutableInt64Array { - pub(crate) obj_id: i32, -} - -impl ScMutableInt64Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_int64(&self, index: i32) -> ScMutableInt64 { - ScMutableInt64 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableInt64Array { - ScImmutableInt64Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// map proxy for mutable map -#[derive(Clone, Copy)] -pub struct ScMutableMap { - pub(crate) obj_id: i32, -} - -impl ScMutableMap { - pub fn call_func(&self, key_id: Key32, params: &[u8]) -> Vec { - call_func(self.obj_id, key_id, params) - } - - // construct a new map on the host and return a map proxy for it - pub fn new() -> ScMutableMap { - let maps = ROOT.get_map_array(&KEY_MAPS); - maps.get_map(maps.length()) - } - - // empty the map - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for mutable ScAddress field specified by key - pub fn get_address(&self, key: &T) -> ScMutableAddress { - ScMutableAddress { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableAddressArray specified by key - pub fn get_address_array(&self, key: &T) -> ScMutableAddressArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_ADDRESS | TYPE_ARRAY); - ScMutableAddressArray { obj_id: arr_id } - } - - // get value proxy for mutable ScAgentID field specified by key - pub fn get_agent_id(&self, key: &T) -> ScMutableAgentID { - ScMutableAgentID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableAgentIDArray specified by key - pub fn get_agent_id_array(&self, key: &T) -> ScMutableAgentIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_AGENT_ID | TYPE_ARRAY); - ScMutableAgentIDArray { obj_id: arr_id } - } - - // get value proxy for mutable Bool field specified by key - pub fn get_bool(&self, key: &T) -> ScMutableBool { - ScMutableBool { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableBoolArray specified by key - pub fn get_bool_array(&self, key: &T) -> ScMutableBoolArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_BOOL | TYPE_ARRAY); - ScMutableBoolArray { obj_id: arr_id } - } - - // get value proxy for mutable bytes array field specified by key - pub fn get_bytes(&self, key: &T) -> ScMutableBytes { - ScMutableBytes { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableBytesArray specified by key - pub fn get_bytes_array(&self, key: &T) -> ScMutableBytesArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_BYTES | TYPE_ARRAY); - ScMutableBytesArray { obj_id: arr_id } - } - - // get value proxy for mutable ScChainID field specified by key - pub fn get_chain_id(&self, key: &T) -> ScMutableChainID { - ScMutableChainID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableChainIDArray specified by key - pub fn get_chain_id_array(&self, key: &T) -> ScMutableChainIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_CHAIN_ID | TYPE_ARRAY); - ScMutableChainIDArray { obj_id: arr_id } - } - - // get value proxy for mutable ScColor field specified by key - pub fn get_color(&self, key: &T) -> ScMutableColor { - ScMutableColor { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableColorArray specified by key - pub fn get_color_array(&self, key: &T) -> ScMutableColorArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_COLOR | TYPE_ARRAY); - ScMutableColorArray { obj_id: arr_id } - } - - // get value proxy for mutable ScHash field specified by key - pub fn get_hash(&self, key: &T) -> ScMutableHash { - ScMutableHash { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableHashArray specified by key - pub fn get_hash_array(&self, key: &T) -> ScMutableHashArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_HASH | TYPE_ARRAY); - ScMutableHashArray { obj_id: arr_id } - } - - // get value proxy for mutable ScHname field specified by key - pub fn get_hname(&self, key: &T) -> ScMutableHname { - ScMutableHname { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableHnameArray specified by key - pub fn get_hname_array(&self, key: &T) -> ScMutableHnameArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_HNAME | TYPE_ARRAY); - ScMutableHnameArray { obj_id: arr_id } - } - - // get value proxy for mutable Int8 field specified by key - pub fn get_int8(&self, key: &T) -> ScMutableInt8 { - ScMutableInt8 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableInt8Array specified by key - pub fn get_int8_array(&self, key: &T) -> ScMutableInt8Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT8 | TYPE_ARRAY); - ScMutableInt8Array { obj_id: arr_id } - } - - // get value proxy for mutable Int16 field specified by key - pub fn get_int16(&self, key: &T) -> ScMutableInt16 { - ScMutableInt16 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableInt16Array specified by key - pub fn get_int16_array(&self, key: &T) -> ScMutableInt16Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT16 | TYPE_ARRAY); - ScMutableInt16Array { obj_id: arr_id } - } - - // get value proxy for mutable Int32 field specified by key - pub fn get_int32(&self, key: &T) -> ScMutableInt32 { - ScMutableInt32 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableInt32Array specified by key - pub fn get_int32_array(&self, key: &T) -> ScMutableInt32Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT32 | TYPE_ARRAY); - ScMutableInt32Array { obj_id: arr_id } - } - - // get value proxy for mutable Int64 field specified by key - pub fn get_int64(&self, key: &T) -> ScMutableInt64 { - ScMutableInt64 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableInt64Array specified by key - pub fn get_int64_array(&self, key: &T) -> ScMutableInt64Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT64 | TYPE_ARRAY); - ScMutableInt64Array { obj_id: arr_id } - } - - // get map proxy for ScMutableMap specified by key - pub fn get_map(&self, key: &T) -> ScMutableMap { - let map_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP); - ScMutableMap { obj_id: map_id } - } - - // get array proxy for ScMutableMapArray specified by key - pub fn get_map_array(&self, key: &T) -> ScMutableMapArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_MAP | TYPE_ARRAY); - ScMutableMapArray { obj_id: arr_id } - } - - // get value proxy for mutable ScRequestID field specified by key - pub fn get_request_id(&self, key: &T) -> ScMutableRequestID { - ScMutableRequestID { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableRequestIDArray specified by key - pub fn get_request_id_array(&self, key: &T) -> ScMutableRequestIDArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_REQUEST_ID | TYPE_ARRAY); - ScMutableRequestIDArray { obj_id: arr_id } - } - - // get value proxy for mutable UTF-8 text string field specified by key - pub fn get_string(&self, key: &T) -> ScMutableString { - ScMutableString { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableStringArray specified by key - pub fn get_string_array(&self, key: &T) -> ScMutableStringArray { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_STRING | TYPE_ARRAY); - ScMutableStringArray { obj_id: arr_id } - } - - // get value proxy for mutable Uint8 field specified by key - pub fn get_uint8(&self, key: &T) -> ScMutableUint8 { - ScMutableUint8 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableUint8Array specified by key - pub fn get_uint8_array(&self, key: &T) -> ScMutableUint8Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT8 | TYPE_ARRAY); - ScMutableUint8Array { obj_id: arr_id } - } - - // get value proxy for mutable Uint16 field specified by key - pub fn get_uint16(&self, key: &T) -> ScMutableUint16 { - ScMutableUint16 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableUint16Array specified by key - pub fn get_uint16_array(&self, key: &T) -> ScMutableUint16Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT16 | TYPE_ARRAY); - ScMutableUint16Array { obj_id: arr_id } - } - - // get value proxy for mutable Uint32 field specified by key - pub fn get_uint32(&self, key: &T) -> ScMutableUint32 { - ScMutableUint32 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableUint32Array specified by key - pub fn get_uint32_array(&self, key: &T) -> ScMutableUint32Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT32 | TYPE_ARRAY); - ScMutableUint32Array { obj_id: arr_id } - } - - // get value proxy for mutable Uint64 field specified by key - pub fn get_uint64(&self, key: &T) -> ScMutableUint64 { - ScMutableUint64 { obj_id: self.obj_id, key_id: key.get_key_id() } - } - - // get array proxy for ScMutableUint64Array specified by key - pub fn get_uint64_array(&self, key: &T) -> ScMutableUint64Array { - let arr_id = get_object_id(self.obj_id, key.get_key_id(), TYPE_INT64 | TYPE_ARRAY); - ScMutableUint64Array { obj_id: arr_id } - } - - // get immutable version of map proxy - pub fn immutable(&self) -> ScImmutableMap { - ScImmutableMap { obj_id: self.obj_id } - } - - pub fn map_id(&self) -> i32 { - self.obj_id - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of maps -pub struct ScMutableMapArray { - pub(crate) obj_id: i32, -} - -impl ScMutableMapArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_map(&self, index: i32) -> ScMutableMap { - let map_id = get_object_id(self.obj_id, Key32(index), TYPE_MAP); - ScMutableMap { obj_id: map_id } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableMapArray { - ScImmutableMapArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScRequestID in host container -pub struct ScMutableRequestID { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableRequestID { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableRequestID { - ScMutableRequestID { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_REQUEST_ID) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_REQUEST_ID) - } - - // set value in host container - pub fn set_value(&self, val: &ScRequestID) { - set_bytes(self.obj_id, self.key_id, TYPE_REQUEST_ID, val.to_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> ScRequestID { - ScRequestID::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_REQUEST_ID)) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScRequestID -pub struct ScMutableRequestIDArray { - pub(crate) obj_id: i32, -} - -impl ScMutableRequestIDArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_request_id(&self, index: i32) -> ScMutableRequestID { - ScMutableRequestID { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableRequestIDArray { - ScImmutableRequestIDArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable UTF-8 text string in host container -pub struct ScMutableString { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableString { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableString { - ScMutableString { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_STRING) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_STRING) - } - - // set value in host container - pub fn set_value(&self, val: &str) { - set_bytes(self.obj_id, self.key_id, TYPE_STRING, val.as_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value() - } - - // retrieve value from host container - pub fn value(&self) -> String { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_STRING); - unsafe { String::from_utf8_unchecked(bytes) } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of UTF-8 text string -pub struct ScMutableStringArray { - pub(crate) obj_id: i32, -} - -impl ScMutableStringArray { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_string(&self, index: i32) -> ScMutableString { - ScMutableString { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableStringArray { - ScImmutableStringArray { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint8 in host container -pub struct ScMutableUint8 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableUint8 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableUint8 { - ScMutableUint8 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT8) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT8) - } - - // set value in host container - pub fn set_value(&self, val: u8) { - let bytes = [val]; - set_bytes(self.obj_id, self.key_id, TYPE_INT8, &bytes); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> u8 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT8); - bytes[0] - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint8 -pub struct ScMutableUint8Array { - pub(crate) obj_id: i32, -} - -impl ScMutableUint8Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_uint8(&self, index: i32) -> ScMutableUint8 { - ScMutableUint8 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableUint8Array { - ScImmutableUint8Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint16 in host container -pub struct ScMutableUint16 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableUint16 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableUint16 { - ScMutableUint16 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT16) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT16) - } - - // set value in host container - pub fn set_value(&self, val: u16) { - set_bytes(self.obj_id, self.key_id, TYPE_INT16, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> u16 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT16); - u16::from_le_bytes(bytes.try_into().expect("invalid u16 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint16 -pub struct ScMutableUint16Array { - pub(crate) obj_id: i32, -} - -impl ScMutableUint16Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_uint16(&self, index: i32) -> ScMutableUint16 { - ScMutableUint16 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableUint16Array { - ScImmutableUint16Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint32 in host container -pub struct ScMutableUint32 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableUint32 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableUint32 { - ScMutableUint32 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT32) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT32) - } - - // set value in host container - pub fn set_value(&self, val: u32) { - set_bytes(self.obj_id, self.key_id, TYPE_INT32, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> u32 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT32); - u32::from_le_bytes(bytes.try_into().expect("invalid u32 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint32 -pub struct ScMutableUint32Array { - pub(crate) obj_id: i32, -} - -impl ScMutableUint32Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_uint32(&self, index: i32) -> ScMutableUint32 { - ScMutableUint32 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableUint32Array { - ScImmutableUint32Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint64 in host container -pub struct ScMutableUint64 { - obj_id: i32, - key_id: Key32, -} - -impl ScMutableUint64 { - pub fn new(obj_id: i32, key_id: Key32) -> ScMutableUint64 { - ScMutableUint64 { obj_id, key_id } - } - - // delete value from host container - pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_INT64) - } - - // check if value exists in host container - pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_INT64) - } - - // set value in host container - pub fn set_value(&self, val: u64) { - set_bytes(self.obj_id, self.key_id, TYPE_INT64, &val.to_le_bytes()); - } - - // human-readable string representation - pub fn to_string(&self) -> String { - self.value().to_string() - } - - // retrieve value from host container - pub fn value(&self) -> u64 { - let bytes = get_bytes(self.obj_id, self.key_id, TYPE_INT64); - u64::from_le_bytes(bytes.try_into().expect("invalid ui64 length")) - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint64 -pub struct ScMutableUint64Array { - pub(crate) obj_id: i32, -} - -impl ScMutableUint64Array { - // empty the array - pub fn clear(&self) { - clear(self.obj_id); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - pub fn get_uint64(&self, index: i32) -> ScMutableUint64 { - ScMutableUint64 { obj_id: self.obj_id, key_id: Key32(index) } - } - - // get immutable version of array proxy - pub fn immutable(&self) -> ScImmutableUint64Array { - ScImmutableUint64Array { obj_id: self.obj_id } - } - - // number of items in array - pub fn length(&self) -> i32 { - get_length(self.obj_id) - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/bytes.ts b/packages/vm/wasmlib/ts/wasmlib/bytes.ts deleted file mode 100644 index 0cf37a1eb5..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/bytes.ts +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -import {Convert} from "./convert"; -import {ScAddress, ScAgentID, ScChainID, ScColor, ScHash, ScHname, ScRequestID} from "./hashtypes"; -import {panic} from "./host"; - -// decodes separate entities from a byte buffer -export class BytesDecoder { - buf: u8[]; - - // constructs a decoder - constructor(data: u8[]) { - if (data.length == 0) { - panic("cannot decode empty byte array, use exist()"); - } - this.buf = data; - } - - // decodes an ScAddress from the byte buffer - address(): ScAddress { - return ScAddress.fromBytes(this.bytes()); - } - - // decodes an ScAgentID from the byte buffer - agentID(): ScAgentID { - return ScAgentID.fromBytes(this.bytes()); - } - - // decodes a bool from the byte buffer - bool(): boolean { - return this.uint8() != 0; - } - - // decodes the next substring of bytes from the byte buffer - bytes(): u8[] { - let size = this.uint32(); - if (u32(this.buf.length) < size) { - panic("insufficient bytes"); - } - let value = this.buf.slice(0, size); - this.buf = this.buf.slice(size); - return value; - } - - // decodes an ScChainID from the byte buffer - chainID(): ScChainID { - return ScChainID.fromBytes(this.bytes()); - } - - // decodes an ScColor from the byte buffer - color(): ScColor { - return ScColor.fromBytes(this.bytes()); - } - - // decodes an ScHash from the byte buffer - hash(): ScHash { - return ScHash.fromBytes(this.bytes()); - } - - // decodes an ScHname from the byte buffer - hname(): ScHname { - return ScHname.fromBytes(this.bytes()); - } - - // decodes an int8 from the byte buffer - int8(): i8 { - return this.uint8() as i8; - } - - // decodes an int16 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int16(): i16 { - return this.leb128Decode(16) as i16; - } - - // decodes an int32 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int32(): i32 { - return this.leb128Decode(32) as i32; - } - - // decodes an int64 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int64(): i64 { - return this.leb128Decode(64); - } - - // leb128 decoder - leb128Decode(bits: i32): i64 { - let val: i64 = 0; - let s = 0; - for (; ;) { - if (this.buf.length == 0) { - panic("leb128Decode: insufficient bytes"); - } - let b = this.buf.shift() as i8; - val |= ((b & 0x7f) as i64) << s; - - // termination bit set? - if ((b & -0x80) == 0) { - if ((((val >> s) as i8) & 0x7f) != (b & 0x7f)) { - panic("integer too large"); - } - - // extend int7 sign to int8 - b |= (b & 0x40) << 1; - - // extend int8 sign to int64 - val |= ((b as i64) << s); - break; - } - s += 7; - if (s >= bits) { - panic("integer representation too long"); - } - } - return val; - } - - // decodes an ScRequestID from the byte buffer - requestID(): ScRequestID { - return ScRequestID.fromBytes(this.bytes()); - } - - // decodes an UTF-8 text string from the byte buffer - string(): string { - return Convert.toString(this.bytes()); - } - - // decodes an uint8 from the byte buffer - uint8(): u8 { - return this.buf.shift(); - } - - // decodes an uint16 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint16(): u16 { - return this.int16() as u16; - } - - // decodes an uint32 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint32(): u32 { - return this.int32() as u32; - } - - // decodes an uint64 from the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint64(): u64 { - return this.int64() as u64; - } - - close(): void { - if (this.buf.length != 0) { - panic("extra bytes"); - } - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// encodes separate entities into a byte buffer -export class BytesEncoder { - buf: u8[]; - - // constructs an encoder - constructor() { - this.buf = [] - } - - // encodes an ScAddress into the byte buffer - address(value: ScAddress): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes an ScAgentID into the byte buffer - agentID(value: ScAgentID): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes a bool into the byte buffer - bool(val: boolean): BytesEncoder { - return this.int8(val ? 1 : 0); - } - - // encodes a substring of bytes into the byte buffer - bytes(value: u8[]): BytesEncoder { - this.uint32(value.length); - for (let i = 0; i < value.length; i++) { - this.buf.push(value[i]); - } - return this; - } - - // encodes an ScChainID into the byte buffer - chainID(value: ScChainID): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes an ScColor into the byte buffer - color(value: ScColor): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // retrieve the encoded byte buffer - data(): u8[] { - return this.buf; - } - - // encodes an ScHash into the byte buffer - hash(value: ScHash): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes an ScHname into the byte buffer - hname(value: ScHname): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes an int8 into the byte buffer - int8(val: i8): BytesEncoder { - return this.uint8(val as u8); - } - - // encodes an int16 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int16(val: i16): BytesEncoder { - return this.leb128Encode(val as i64); - } - - // encodes an int32 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int32(val: i32): BytesEncoder { - return this.leb128Encode(val as i64); - } - - // encodes an int64 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - int64(val: i64): BytesEncoder { - return this.leb128Encode(val); - } - - // leb128 encoder - leb128Encode(val: i64): BytesEncoder { - for (; ;) { - let b = val as u8; - let s = b & 0x40; - val >>= 7; - if ((val == 0 && s == 0) || (val == -1 && s != 0)) { - this.buf.push(b & 0x7f); - break; - } - this.buf.push(b | 0x80); - } - return this; - } - - // encodes an ScRequestID into the byte buffer - requestID(value: ScRequestID): BytesEncoder { - return this.bytes(value.toBytes()); - } - - // encodes an UTF-8 text string into the byte buffer - string(value: string): BytesEncoder { - return this.bytes(Convert.fromString(value)); - } - - // encodes an uint8 into the byte buffer - uint8(val: u8): BytesEncoder { - this.buf.push(val); - return this; - } - - // encodes an uint16 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint16(val: u16): BytesEncoder { - return this.int16(val as i16); - } - - // encodes an uint32 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint32(val: u32): BytesEncoder { - return this.int32(val as i32); - } - - // encodes an uint64 into the byte buffer - // note that these are encoded using leb128 encoding to conserve space - uint64(val: u64): BytesEncoder { - return this.int64(val as i64); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/context.ts b/packages/vm/wasmlib/ts/wasmlib/context.ts deleted file mode 100644 index 72bcd296b6..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/context.ts +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// encapsulates standard host entities into a simple interface - -import {BytesDecoder, BytesEncoder} from "./bytes"; -import {Convert} from "./convert"; -import {ScFuncCallContext, ScViewCallContext} from "./contract"; -import {ScAddress, ScAgentID, ScChainID, ScColor, ScHash, ScHname, ScRequestID} from "./hashtypes"; -import {log, OBJ_ID_ROOT, OBJ_ID_STATE, panic} from "./host"; -import {ScImmutableColorArray, ScImmutableMap} from "./immutable"; -import * as keys from "./keys"; -import {ScMutableMap} from "./mutable"; - -// all access to the objects in host's object tree starts here -export let ROOT = new ScMutableMap(OBJ_ID_ROOT); - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// retrieves any information that is related to colored token balances -export class ScBalances { - balances: ScImmutableMap; - - constructor(id: keys.Key32) { - this.balances = ROOT.getMap(id).immutable() - } - - // retrieve the balance for the specified token color - balance(color: ScColor): i64 { - return this.balances.getInt64(color).value(); - } - - // retrieve an array of all token colors that have a non-zero balance - colors(): ScImmutableColorArray { - return this.balances.getColorArray(keys.KEY_COLOR); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// passes token transfer information to a function call -export class ScTransfers { - transfers: ScMutableMap; - - // create a new transfers object ready to add token transfers - constructor() { - this.transfers = ScMutableMap.create(); - } - - // create a new transfers object from a balances object - static fromBalances(balances: ScBalances): ScTransfers { - let transfers = new ScTransfers(); - let colors = balances.colors(); - for (let i = 0; i < colors.length(); i++) { - let color = colors.getColor(i).value(); - transfers.set(color, balances.balance(color)); - } - return transfers; - } - - // create a new transfers object and initialize it with the specified amount of iotas - static iotas(amount: i64): ScTransfers { - return ScTransfers.transfer(ScColor.IOTA, amount); - } - - // create a new transfers object and initialize it with the specified token transfer - static transfer(color: ScColor, amount: i64): ScTransfers { - let transfer = new ScTransfers(); - transfer.set(color, amount); - return transfer; - } - - // set the specified colored token transfer in the transfers object - // note that this will overwrite any previous amount for the specified color - set(color: ScColor, amount: i64): void { - this.transfers.getInt64(color).setValue(amount); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// provides access to utility functions that are handled by the host -export class ScUtility { - utility: ScMutableMap; - - constructor() { - this.utility = ROOT.getMap(keys.KEY_UTILITY) - } - - // decodes the specified base58-encoded string value to its original bytes - base58Decode(value: string): u8[] { - return this.utility.callFunc(keys.KEY_BASE58_DECODE, Convert.fromString(value)); - } - - // encodes the specified bytes to a base-58-encoded string - base58Encode(value: u8[]): string { - let result = this.utility.callFunc(keys.KEY_BASE58_ENCODE, value); - return Convert.toString(result); - } - - // retrieves the address for the specified BLS public key - blsAddressFromPubkey(pubKey: u8[]): ScAddress { - let result = this.utility.callFunc(keys.KEY_BLS_ADDRESS, pubKey); - return ScAddress.fromBytes(result); - } - - // aggregates the specified multiple BLS signatures and public keys into a single one - blsAggregateSignatures(pubKeysBin: u8[][], sigsBin: u8[][]): u8[][] { - let encode = new BytesEncoder(); - encode.int32(pubKeysBin.length); - for (let i = 0; i < pubKeysBin.length; i++) { - encode.bytes(pubKeysBin[i]); - } - encode.int32(sigsBin.length as i32); - for (let i = 0; i < sigsBin.length; i++) { - encode.bytes(sigsBin[i]); - } - let result = this.utility.callFunc(keys.KEY_BLS_AGGREGATE, encode.data()); - let decode = new BytesDecoder(result); - return [decode.bytes(), decode.bytes()]; - } - - // checks if the specified BLS signature is valid - blsValidSignature(data: u8[], pubKey: u8[], signature: u8[]): boolean { - let encode = new BytesEncoder(); - encode.bytes(data); - encode.bytes(pubKey); - encode.bytes(signature); - let result = this.utility.callFunc(keys.KEY_BLS_VALID, encode.data()); - return (result[0] & 0x01) != 0; - } - - // retrieves the address for the specified ED25519 public key - ed25519AddressFromPubkey(pubKey: u8[]): ScAddress { - let result = this.utility.callFunc(keys.KEY_ED25519_ADDRESS, pubKey); - return ScAddress.fromBytes(result); - } - - // checks if the specified ED25519 signature is valid - ed25519ValidSignature(data: u8[], pubKey: u8[], signature: u8[]): boolean { - let encode = new BytesEncoder(); - encode.bytes(data); - encode.bytes(pubKey); - encode.bytes(signature); - let result = this.utility.callFunc(keys.KEY_ED25519_VALID, encode.data()); - return (result[0] & 0x01) != 0; - } - - // hashes the specified value bytes using BLAKE2b hashing and returns the resulting 32-byte hash - hashBlake2b(value: u8[]): ScHash { - let hash = this.utility.callFunc(keys.KEY_HASH_BLAKE2B, value); - return ScHash.fromBytes(hash); - } - - // hashes the specified value bytes using SHA3 hashing and returns the resulting 32-byte hash - hashSha3(value: u8[]): ScHash { - let hash = this.utility.callFunc(keys.KEY_HASH_SHA3, value); - return ScHash.fromBytes(hash); - } - - // calculates 32-bit hash for the specified name string - hname(name: string): ScHname { - let result = this.utility.callFunc(keys.KEY_HNAME, Convert.fromString(name)); - return ScHname.fromBytes(result); - } -} - -// wrapper function for simplified internal access to base58 encoding -export function base58Encode(bytes: u8[]): string { - return new ScFuncContext().utility().base58Encode(bytes); -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// shared interface part of ScFuncContext and ScViewContext -export class ScBaseContext { - // retrieve the agent id of this contract account - accountID(): ScAgentID { - return ROOT.getAgentID(keys.KEY_ACCOUNT_ID).value(); - } - - // access the current balances for all token colors - balances(): ScBalances { - return new ScBalances(keys.KEY_BALANCES); - } - - // retrieve the chain id of the chain this contract lives on - chainID(): ScChainID { - return ROOT.getChainID(keys.KEY_CHAIN_ID).value(); - } - - // retrieve the agent id of the owner of the chain this contract lives on - chainOwnerID(): ScAgentID { - return ROOT.getAgentID(keys.KEY_CHAIN_OWNER_ID).value(); - } - - // retrieve the hname of this contract - contract(): ScHname { - return ROOT.getHname(keys.KEY_CONTRACT).value(); - } - - // retrieve the agent id of the creator of this contract - contractCreator(): ScAgentID { - return ROOT.getAgentID(keys.KEY_CONTRACT_CREATOR).value(); - } - - // logs informational text message in the log on the host - log(text: string): void { - log(text); - } - - // logs error text message in the log on the host and then panics - panic(text: string): void { - panic(text); - } - - // retrieve parameters that were passed to the smart contract function - params(): ScImmutableMap { - return ROOT.getMap(keys.KEY_PARAMS).immutable(); - } - - // panics with specified message if specified condition is not satisfied - require(cond: boolean, msg: string): void { - if (!cond) { - panic(msg); - } - } - - // map that holds any results returned by the smart contract function - results(): ScMutableMap { - return ROOT.getMap(keys.KEY_RESULTS); - } - - // deterministic time stamp fixed at the moment of calling the smart contract - timestamp(): i64 { - return ROOT.getInt64(keys.KEY_TIMESTAMP).value(); - } - - // logs debugging trace text message in the log on the host - // similar to log() except this will only show in the log in a special debug mode - trace(text: string): void { - trace(text); - } - - // access diverse utility functions provided by the host - utility(): ScUtility { - return new ScUtility(); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract interface with mutable access to state -export class ScFuncContext extends ScBaseContext implements ScViewCallContext, ScFuncCallContext { - canCallFunc(): void { - panic!("canCallFunc"); - } - - canCallView(): void { - panic!("canCallView"); - } - - // synchronously calls the specified smart contract function, - // passing the provided parameters and token transfers to it - call(hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null, transfer: ScTransfers | null): ScImmutableMap { - let encode = new BytesEncoder(); - encode.hname(hcontract); - encode.hname(hfunction); - encode.int32((params === null) ? 0 : params.mapID()); - encode.int32((transfer === null) ? 0 : transfer.transfers.mapID()); - ROOT.getBytes(keys.KEY_CALL).setValue(encode.data()); - return ROOT.getMap(keys.KEY_RETURN).immutable(); - } - - // retrieve the agent id of the caller of the smart contract - caller(): ScAgentID { - return ROOT.getAgentID(keys.KEY_CALLER).value(); - } - - // deploys a new instance of the specified smart contract on the current chain - // the provided parameters are passed to the smart contract "init" function - deploy(programHash: ScHash, name: string, description: string, params: ScMutableMap | null): void { - let encode = new BytesEncoder(); - encode.hash(programHash); - encode.string(name); - encode.string(description); - encode.int32((params === null) ? 0 : params.mapID()); - ROOT.getBytes(keys.KEY_DEPLOY).setValue(encode.data()); - } - - // signals an event on the host that external entities can subscribe to - event(text: string): void { - ROOT.getString(keys.KEY_EVENT).setValue(text); - } - - // access the incoming balances for all token colors - incoming(): ScBalances { - return new ScBalances(keys.KEY_INCOMING); - } - - // retrieve the tokens that were minted in this transaction - minted(): ScBalances { - return new ScBalances(keys.KEY_MINTED); - } - - // asynchronously calls the specified smart contract function, - // passing the provided parameters and token transfers to it - // it is possible to schedule the call for a later execution by specifying a delay - post(chainID: ScChainID, hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null, transfer: ScTransfers, delay: i32): void { - let encode = new BytesEncoder(); - encode.chainID(chainID); - encode.hname(hcontract); - encode.hname(hfunction); - encode.int32((params === null) ? 0 : params.mapID()); - encode.int32(transfer.transfers.mapID()); - encode.int32(delay); - ROOT.getBytes(keys.KEY_POST).setValue(encode.data()); - } - - // generates a random value from 0 to max (exclusive max) using a deterministic RNG - random(max: i64): i64 { - if (max == 0) { - this.panic("random: max parameter should be non-zero"); - } - let state = new ScMutableMap(OBJ_ID_STATE); - let rnd = state.getBytes(keys.KEY_RANDOM); - let seed = rnd.value(); - if (seed.length == 0) { - seed = ROOT.getBytes(keys.KEY_RANDOM).value(); - } - rnd.setValue(this.utility().hashSha3(seed).toBytes()); - return (Convert.toI64(seed.slice(0, 8)) as u64 % max as u64) as i64; - } - - // retrieve the request id of this transaction - requestID(): ScRequestID { - return ROOT.getRequestID(keys.KEY_REQUEST_ID).value(); - } - - // access mutable state storage on the host - state(): ScMutableMap { - return ROOT.getMap(keys.KEY_STATE); - } - - // transfers the specified tokens to the specified Tangle ledger address - transferToAddress(address: ScAddress, transfer: ScTransfers): void { - let transfers = ROOT.getMapArray(keys.KEY_TRANSFERS); - let tx = transfers.getMap(transfers.length()); - tx.getAddress(keys.KEY_ADDRESS).setValue(address); - tx.getInt32(keys.KEY_BALANCES).setValue(transfer.transfers.mapID()); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// smart contract view interface which has only immutable access to state -export class ScViewContext extends ScBaseContext implements ScViewCallContext { - canCallView(): void { - panic!("canCallView"); - } - - // synchronously calls the specified smart contract view, - // passing the provided parameters to it - call(hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null): ScImmutableMap { - let encode = new BytesEncoder(); - encode.hname(hcontract); - encode.hname(hfunction); - encode.int32((params === null) ? 0 : params.mapID()); - encode.int32(0); - ROOT.getBytes(keys.KEY_CALL).setValue(encode.data()); - return ROOT.getMap(keys.KEY_RETURN).immutable(); - } - - // access immutable state storage on the host - state(): ScImmutableMap { - return ROOT.getMap(keys.KEY_STATE).immutable(); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/contract.ts b/packages/vm/wasmlib/ts/wasmlib/contract.ts deleted file mode 100644 index b7cbfc1d11..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/contract.ts +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// base contract objects - -import {BytesEncoder} from "./bytes"; -import {ROOT,ScTransfers} from "./context"; -import {ScChainID,ScHname} from "./hashtypes"; -import {getObjectID, panic, TYPE_MAP} from "./host"; -import * as keys from "./keys"; -import {ScMutableMap} from "./mutable"; - -export interface ScFuncCallContext { - canCallFunc():void; -} - -export interface ScViewCallContext { - canCallView():void; -} - -export class ScMapID { - mapID: i32 = 0; -} - -type NullableScMapID = ScMapID | null; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -export class ScView { - hContract: ScHname; - hFunction: ScHname; - paramsID: NullableScMapID; - resultsID: NullableScMapID; - - constructor(hContract: ScHname, hFunction: ScHname) { - this.hContract = hContract; - this.hFunction = hFunction; - this.paramsID = null; - this.resultsID = null; - } - - setPtrs(paramsID: NullableScMapID, resultsID: NullableScMapID): void { - this.paramsID = paramsID; - this.resultsID = resultsID; - - if (paramsID === null) { - } else { - paramsID.mapID = ScMutableMap.create().mapID(); - } - } - - call(): void { - this.callWithTransfer(0); - } - - callWithTransfer(transferID: i32): void { - let encode = new BytesEncoder(); - encode.hname(this.hContract); - encode.hname(this.hFunction); - encode.int32(this.id(this.paramsID)); - encode.int32(transferID); - ROOT.getBytes(keys.KEY_CALL).setValue(encode.data()); - - let resultsID = this.resultsID; - if (resultsID === null) { - } else { - resultsID.mapID = getObjectID(1, keys.KEY_RETURN, TYPE_MAP); - } - } - - clone(): ScView { - let o = new ScView(this.hContract, this.hFunction); - o.paramsID = this.paramsID; - o.resultsID = this.resultsID; - return o; - } - - ofContract(hContract: ScHname): ScView { - let ret = this.clone(); - ret.hContract = hContract; - return ret; - } - - id(paramsID: NullableScMapID): i32 { - if (paramsID === null) { - return 0; - } - return paramsID.mapID; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -export class ScInitFunc { - view: ScView; - - constructor(hContract: ScHname, hFunction: ScHname) { - this.view = new ScView(hContract, hFunction); - } - - setPtrs(paramsID: NullableScMapID, resultsID: NullableScMapID): void { - this.view.setPtrs(paramsID, resultsID); - } - - call(): void { - return panic("cannot call init"); - } - - clone(): ScInitFunc { - let o = new ScInitFunc(this.view.hContract, this.view.hFunction); - o.view = this.view.clone(); - return o; - } - - ofContract(hContract: ScHname): ScInitFunc { - let ret = this.clone(); - ret.view.hContract = hContract; - return ret; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -export class ScFunc { - view: ScView; - delaySeconds: i32 = 0; - transferID: i32 = 0; - - constructor(hContract: ScHname, hFunction: ScHname) { - this.view = new ScView(hContract, hFunction); - } - - setPtrs(paramsID: NullableScMapID, resultsID: NullableScMapID): void { - this.view.setPtrs(paramsID, resultsID); - } - - call(): void { - if (this.delaySeconds != 0) { - return panic("cannot delay a call"); - } - this.view.callWithTransfer(this.transferID); - } - - clone(): ScFunc { - let o = new ScFunc(this.view.hContract, this.view.hFunction); - o.view = this.view.clone(); - o.delaySeconds = this.delaySeconds; - o.transferID = this.transferID; - return o; - } - - delay(seconds: i32): ScFunc { - let ret = this.clone(); - ret.delaySeconds = seconds; - return ret; - } - - ofContract(hContract: ScHname): ScFunc { - let ret = this.clone(); - ret.view.hContract = hContract; - return ret; - } - - post(): void { - return this.postToChain(ROOT.getChainID(keys.KEY_CHAIN_ID).value()); - } - - postToChain(chainID: ScChainID): void { - let encode = new BytesEncoder(); - encode.chainID(chainID); - encode.hname(this.view.hContract); - encode.hname(this.view.hFunction); - encode.int32(this.view.id(this.view.paramsID)); - encode.int32(this.transferID); - encode.int32(this.delaySeconds); - ROOT.getBytes(keys.KEY_POST).setValue(encode.data()); - } - - transfer(transfer: ScTransfers): ScFunc { - let ret = this.clone(); - ret.transferID = transfer.transfers.objID; - return ret; - } - - transferIotas(amount: i64): ScFunc { - return this.transfer(ScTransfers.iotas(amount)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/convert.ts b/packages/vm/wasmlib/ts/wasmlib/convert.ts deleted file mode 100644 index 3e23835597..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/convert.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// converts to and from little endian bytes -import {panic} from "./host"; - -export class Convert { - static equals(lhs: u8[], rhs: u8[]): boolean { - if (lhs.length != rhs.length) { - return false; - } - for (let i = lhs.length - 1; i >= 0; i--) { - if (lhs[i] != rhs[i]) { - return false; - } - } - return true; - } - - static fromI16(val: i16): u8[] { - return [ - val as u8, - (val >> 8) as u8, - ]; - } - - static fromI32(val: i32): u8[] { - return [ - val as u8, - (val >> 8) as u8, - (val >> 16) as u8, - (val >> 24) as u8, - ]; - } - - static fromI64(val: i64): u8[] { - return [ - val as u8, - (val >> 8) as u8, - (val >> 16) as u8, - (val >> 24) as u8, - (val >> 32) as u8, - (val >> 40) as u8, - (val >> 48) as u8, - (val >> 56) as u8, - ]; - } - - static fromString(val: string): u8[] { - let arrayBuffer = String.UTF8.encode(val); - let u8Array = Uint8Array.wrap(arrayBuffer) - let ret: u8[] = new Array(u8Array.length); - for (let i = 0; i < ret.length; i++) { - ret[i] = u8Array[i]; - } - return ret; - } - - static toI16(bytes: u8[]): i16 { - if (bytes.length != 2) { - panic("expected i16 (2 bytes)") - } - - let ret: i16 = bytes[1]; - return (ret << 8) | bytes[0]; - } - - static toI32(bytes: u8[]): i32 { - if (bytes.length != 4) { - panic("expected i32 (4 bytes)") - } - - let ret: i32 = bytes[3]; - ret = (ret << 8) | bytes[2]; - ret = (ret << 8) | bytes[1]; - return (ret << 8) | bytes[0]; - } - - static toI64(bytes: u8[]): i64 { - if (bytes.length != 8) { - panic("expected i64 (8 bytes)") - } - - let ret: i64 = bytes[7]; - ret = (ret << 8) | bytes[6]; - ret = (ret << 8) | bytes[5]; - ret = (ret << 8) | bytes[4]; - ret = (ret << 8) | bytes[3]; - ret = (ret << 8) | bytes[2]; - ret = (ret << 8) | bytes[1]; - return (ret << 8) | bytes[0]; - } - - static toString(bytes: u8[]): string { - return String.UTF8.decodeUnsafe(bytes.dataStart, bytes.length); - } -} \ No newline at end of file diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/contract.ts b/packages/vm/wasmlib/ts/wasmlib/coreaccounts/contract.ts deleted file mode 100644 index a8fa2cb85b..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/contract.ts +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class DepositCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDeposit); - params: sc.MutableDepositParams = new sc.MutableDepositParams(); -} - -export class HarvestCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncHarvest); - params: sc.MutableHarvestParams = new sc.MutableHarvestParams(); -} - -export class WithdrawCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWithdraw); -} - -export class AccountsCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewAccounts); - results: sc.ImmutableAccountsResults = new sc.ImmutableAccountsResults(); -} - -export class BalanceCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBalance); - params: sc.MutableBalanceParams = new sc.MutableBalanceParams(); - results: sc.ImmutableBalanceResults = new sc.ImmutableBalanceResults(); -} - -export class GetAccountNonceCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetAccountNonce); - params: sc.MutableGetAccountNonceParams = new sc.MutableGetAccountNonceParams(); - results: sc.ImmutableGetAccountNonceResults = new sc.ImmutableGetAccountNonceResults(); -} - -export class TotalAssetsCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTotalAssets); - results: sc.ImmutableTotalAssetsResults = new sc.ImmutableTotalAssetsResults(); -} - -export class ScFuncs { - static deposit(ctx: wasmlib.ScFuncCallContext): DepositCall { - let f = new DepositCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static harvest(ctx: wasmlib.ScFuncCallContext): HarvestCall { - let f = new HarvestCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static withdraw(ctx: wasmlib.ScFuncCallContext): WithdrawCall { - return new WithdrawCall(); - } - - static accounts(ctx: wasmlib.ScViewCallContext): AccountsCall { - let f = new AccountsCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static balance(ctx: wasmlib.ScViewCallContext): BalanceCall { - let f = new BalanceCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getAccountNonce(ctx: wasmlib.ScViewCallContext): GetAccountNonceCall { - let f = new GetAccountNonceCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static totalAssets(ctx: wasmlib.ScViewCallContext): TotalAssetsCall { - let f = new TotalAssetsCall(); - f.func.setPtrs(null, f.results); - return f; - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/params.ts b/packages/vm/wasmlib/ts/wasmlib/coreaccounts/params.ts deleted file mode 100644 index 973afb6f3e..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/params.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableDepositParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} - -export class MutableDepositParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} - -export class ImmutableHarvestParams extends wasmlib.ScMapID { - withdrawAmount(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamWithdrawAmount)); - } - - withdrawColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamWithdrawColor)); - } -} - -export class MutableHarvestParams extends wasmlib.ScMapID { - withdrawAmount(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamWithdrawAmount)); - } - - withdrawColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamWithdrawColor)); - } -} - -export class ImmutableBalanceParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} - -export class MutableBalanceParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} - -export class ImmutableGetAccountNonceParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} - -export class MutableGetAccountNonceParams extends wasmlib.ScMapID { - agentID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamAgentID)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/results.ts b/packages/vm/wasmlib/ts/wasmlib/coreaccounts/results.ts deleted file mode 100644 index a6c043e58f..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/results.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class MapAgentIDToImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getBytes(key: wasmlib.ScAgentID): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, key.getKeyID()); - } -} - -export class ImmutableAccountsResults extends wasmlib.ScMapID { - agents(): sc.MapAgentIDToImmutableBytes { - return new sc.MapAgentIDToImmutableBytes(this.mapID); - } -} - -export class MapAgentIDToMutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getBytes(key: wasmlib.ScAgentID): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, key.getKeyID()); - } -} - -export class MutableAccountsResults extends wasmlib.ScMapID { - agents(): sc.MapAgentIDToMutableBytes { - return new sc.MapAgentIDToMutableBytes(this.mapID); - } -} - -export class MapColorToImmutableInt64 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getInt64(key: wasmlib.ScColor): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.objID, key.getKeyID()); - } -} - -export class ImmutableBalanceResults extends wasmlib.ScMapID { - balances(): sc.MapColorToImmutableInt64 { - return new sc.MapColorToImmutableInt64(this.mapID); - } -} - -export class MapColorToMutableInt64 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getInt64(key: wasmlib.ScColor): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.objID, key.getKeyID()); - } -} - -export class MutableBalanceResults extends wasmlib.ScMapID { - balances(): sc.MapColorToMutableInt64 { - return new sc.MapColorToMutableInt64(this.mapID); - } -} - -export class ImmutableGetAccountNonceResults extends wasmlib.ScMapID { - accountNonce(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAccountNonce)); - } -} - -export class MutableGetAccountNonceResults extends wasmlib.ScMapID { - accountNonce(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultAccountNonce)); - } -} - -export class ImmutableTotalAssetsResults extends wasmlib.ScMapID { - balances(): sc.MapColorToImmutableInt64 { - return new sc.MapColorToImmutableInt64(this.mapID); - } -} - -export class MutableTotalAssetsResults extends wasmlib.ScMapID { - balances(): sc.MapColorToMutableInt64 { - return new sc.MapColorToMutableInt64(this.mapID); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/contract.ts b/packages/vm/wasmlib/ts/wasmlib/coreblob/contract.ts deleted file mode 100644 index 61e3359ae3..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblob/contract.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class StoreBlobCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncStoreBlob); - params: sc.MutableStoreBlobParams = new sc.MutableStoreBlobParams(); - results: sc.ImmutableStoreBlobResults = new sc.ImmutableStoreBlobResults(); -} - -export class GetBlobFieldCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlobField); - params: sc.MutableGetBlobFieldParams = new sc.MutableGetBlobFieldParams(); - results: sc.ImmutableGetBlobFieldResults = new sc.ImmutableGetBlobFieldResults(); -} - -export class GetBlobInfoCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlobInfo); - params: sc.MutableGetBlobInfoParams = new sc.MutableGetBlobInfoParams(); - results: sc.ImmutableGetBlobInfoResults = new sc.ImmutableGetBlobInfoResults(); -} - -export class ListBlobsCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewListBlobs); - results: sc.ImmutableListBlobsResults = new sc.ImmutableListBlobsResults(); -} - -export class ScFuncs { - static storeBlob(ctx: wasmlib.ScFuncCallContext): StoreBlobCall { - let f = new StoreBlobCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getBlobField(ctx: wasmlib.ScViewCallContext): GetBlobFieldCall { - let f = new GetBlobFieldCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getBlobInfo(ctx: wasmlib.ScViewCallContext): GetBlobInfoCall { - let f = new GetBlobInfoCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static listBlobs(ctx: wasmlib.ScViewCallContext): ListBlobsCall { - let f = new ListBlobsCall(); - f.func.setPtrs(null, f.results); - return f; - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/params.ts b/packages/vm/wasmlib/ts/wasmlib/coreblob/params.ts deleted file mode 100644 index b334596688..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblob/params.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class MapStringToImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getBytes(key: string): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, wasmlib.Key32.fromString(key)); - } -} - -export class ImmutableStoreBlobParams extends wasmlib.ScMapID { - blobs(): sc.MapStringToImmutableBytes { - return new sc.MapStringToImmutableBytes(this.mapID); - } -} - -export class MapStringToMutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getBytes(key: string): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, wasmlib.Key32.fromString(key)); - } -} - -export class MutableStoreBlobParams extends wasmlib.ScMapID { - blobs(): sc.MapStringToMutableBytes { - return new sc.MapStringToMutableBytes(this.mapID); - } -} - -export class ImmutableGetBlobFieldParams extends wasmlib.ScMapID { - field(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamField)); - } - - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); - } -} - -export class MutableGetBlobFieldParams extends wasmlib.ScMapID { - field(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamField)); - } - - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); - } -} - -export class ImmutableGetBlobInfoParams extends wasmlib.ScMapID { - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); - } -} - -export class MutableGetBlobInfoParams extends wasmlib.ScMapID { - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamHash)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/results.ts b/packages/vm/wasmlib/ts/wasmlib/coreblob/results.ts deleted file mode 100644 index f10b4bf968..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblob/results.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableStoreBlobResults extends wasmlib.ScMapID { - hash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ResultHash)); - } -} - -export class MutableStoreBlobResults extends wasmlib.ScMapID { - hash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ResultHash)); - } -} - -export class ImmutableGetBlobFieldResults extends wasmlib.ScMapID { - bytes(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBytes)); - } -} - -export class MutableGetBlobFieldResults extends wasmlib.ScMapID { - bytes(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBytes)); - } -} - -export class MapStringToImmutableInt32 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getInt32(key: string): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.objID, wasmlib.Key32.fromString(key)); - } -} - -export class ImmutableGetBlobInfoResults extends wasmlib.ScMapID { - blobSizes(): sc.MapStringToImmutableInt32 { - return new sc.MapStringToImmutableInt32(this.mapID); - } -} - -export class MapStringToMutableInt32 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getInt32(key: string): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.objID, wasmlib.Key32.fromString(key)); - } -} - -export class MutableGetBlobInfoResults extends wasmlib.ScMapID { - blobSizes(): sc.MapStringToMutableInt32 { - return new sc.MapStringToMutableInt32(this.mapID); - } -} - -export class MapHashToImmutableInt32 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getInt32(key: wasmlib.ScHash): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.objID, key.getKeyID()); - } -} - -export class ImmutableListBlobsResults extends wasmlib.ScMapID { - blobSizes(): sc.MapHashToImmutableInt32 { - return new sc.MapHashToImmutableInt32(this.mapID); - } -} - -export class MapHashToMutableInt32 { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getInt32(key: wasmlib.ScHash): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.objID, key.getKeyID()); - } -} - -export class MutableListBlobsResults extends wasmlib.ScMapID { - blobSizes(): sc.MapHashToMutableInt32 { - return new sc.MapHashToMutableInt32(this.mapID); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/contract.ts b/packages/vm/wasmlib/ts/wasmlib/coreblocklog/contract.ts deleted file mode 100644 index 4c7fe2800f..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/contract.ts +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ControlAddressesCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewControlAddresses); - results: sc.ImmutableControlAddressesResults = new sc.ImmutableControlAddressesResults(); -} - -export class GetBlockInfoCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlockInfo); - params: sc.MutableGetBlockInfoParams = new sc.MutableGetBlockInfoParams(); - results: sc.ImmutableGetBlockInfoResults = new sc.ImmutableGetBlockInfoResults(); -} - -export class GetEventsForBlockCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForBlock); - params: sc.MutableGetEventsForBlockParams = new sc.MutableGetEventsForBlockParams(); - results: sc.ImmutableGetEventsForBlockResults = new sc.ImmutableGetEventsForBlockResults(); -} - -export class GetEventsForContractCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForContract); - params: sc.MutableGetEventsForContractParams = new sc.MutableGetEventsForContractParams(); - results: sc.ImmutableGetEventsForContractResults = new sc.ImmutableGetEventsForContractResults(); -} - -export class GetEventsForRequestCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForRequest); - params: sc.MutableGetEventsForRequestParams = new sc.MutableGetEventsForRequestParams(); - results: sc.ImmutableGetEventsForRequestResults = new sc.ImmutableGetEventsForRequestResults(); -} - -export class GetLatestBlockInfoCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetLatestBlockInfo); - results: sc.ImmutableGetLatestBlockInfoResults = new sc.ImmutableGetLatestBlockInfoResults(); -} - -export class GetRequestIDsForBlockCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestIDsForBlock); - params: sc.MutableGetRequestIDsForBlockParams = new sc.MutableGetRequestIDsForBlockParams(); - results: sc.ImmutableGetRequestIDsForBlockResults = new sc.ImmutableGetRequestIDsForBlockResults(); -} - -export class GetRequestReceiptCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestReceipt); - params: sc.MutableGetRequestReceiptParams = new sc.MutableGetRequestReceiptParams(); - results: sc.ImmutableGetRequestReceiptResults = new sc.ImmutableGetRequestReceiptResults(); -} - -export class GetRequestReceiptsForBlockCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestReceiptsForBlock); - params: sc.MutableGetRequestReceiptsForBlockParams = new sc.MutableGetRequestReceiptsForBlockParams(); - results: sc.ImmutableGetRequestReceiptsForBlockResults = new sc.ImmutableGetRequestReceiptsForBlockResults(); -} - -export class IsRequestProcessedCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewIsRequestProcessed); - params: sc.MutableIsRequestProcessedParams = new sc.MutableIsRequestProcessedParams(); - results: sc.ImmutableIsRequestProcessedResults = new sc.ImmutableIsRequestProcessedResults(); -} - -export class ScFuncs { - static controlAddresses(ctx: wasmlib.ScViewCallContext): ControlAddressesCall { - let f = new ControlAddressesCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static getBlockInfo(ctx: wasmlib.ScViewCallContext): GetBlockInfoCall { - let f = new GetBlockInfoCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getEventsForBlock(ctx: wasmlib.ScViewCallContext): GetEventsForBlockCall { - let f = new GetEventsForBlockCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getEventsForContract(ctx: wasmlib.ScViewCallContext): GetEventsForContractCall { - let f = new GetEventsForContractCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getEventsForRequest(ctx: wasmlib.ScViewCallContext): GetEventsForRequestCall { - let f = new GetEventsForRequestCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getLatestBlockInfo(ctx: wasmlib.ScViewCallContext): GetLatestBlockInfoCall { - let f = new GetLatestBlockInfoCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static getRequestIDsForBlock(ctx: wasmlib.ScViewCallContext): GetRequestIDsForBlockCall { - let f = new GetRequestIDsForBlockCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getRequestReceipt(ctx: wasmlib.ScViewCallContext): GetRequestReceiptCall { - let f = new GetRequestReceiptCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getRequestReceiptsForBlock(ctx: wasmlib.ScViewCallContext): GetRequestReceiptsForBlockCall { - let f = new GetRequestReceiptsForBlockCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static isRequestProcessed(ctx: wasmlib.ScViewCallContext): IsRequestProcessedCall { - let f = new IsRequestProcessedCall(); - f.func.setPtrs(f.params, f.results); - return f; - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/params.ts b/packages/vm/wasmlib/ts/wasmlib/coreblocklog/params.ts deleted file mode 100644 index 0343cbf2e7..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/params.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableGetBlockInfoParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class MutableGetBlockInfoParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class ImmutableGetEventsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class MutableGetEventsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class ImmutableGetEventsForContractParams extends wasmlib.ScMapID { - contractHname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamContractHname)); - } - - fromBlock(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamFromBlock)); - } - - toBlock(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamToBlock)); - } -} - -export class MutableGetEventsForContractParams extends wasmlib.ScMapID { - contractHname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamContractHname)); - } - - fromBlock(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamFromBlock)); - } - - toBlock(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamToBlock)); - } -} - -export class ImmutableGetEventsForRequestParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScImmutableRequestID { - return new wasmlib.ScImmutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} - -export class MutableGetEventsForRequestParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScMutableRequestID { - return new wasmlib.ScMutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} - -export class ImmutableGetRequestIDsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class MutableGetRequestIDsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class ImmutableGetRequestReceiptParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScImmutableRequestID { - return new wasmlib.ScImmutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} - -export class MutableGetRequestReceiptParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScMutableRequestID { - return new wasmlib.ScMutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} - -export class ImmutableGetRequestReceiptsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class MutableGetRequestReceiptsForBlockParams extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamBlockIndex)); - } -} - -export class ImmutableIsRequestProcessedParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScImmutableRequestID { - return new wasmlib.ScImmutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} - -export class MutableIsRequestProcessedParams extends wasmlib.ScMapID { - requestID(): wasmlib.ScMutableRequestID { - return new wasmlib.ScMutableRequestID(this.mapID, wasmlib.Key32.fromString(sc.ParamRequestID)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/results.ts b/packages/vm/wasmlib/ts/wasmlib/coreblocklog/results.ts deleted file mode 100644 index 0cdeab00e9..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/results.ts +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableControlAddressesResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - governingAddress(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ResultGoverningAddress)); - } - - stateControllerAddress(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ResultStateControllerAddress)); - } -} - -export class MutableControlAddressesResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - governingAddress(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ResultGoverningAddress)); - } - - stateControllerAddress(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ResultStateControllerAddress)); - } -} - -export class ImmutableGetBlockInfoResults extends wasmlib.ScMapID { - blockInfo(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockInfo)); - } -} - -export class MutableGetBlockInfoResults extends wasmlib.ScMapID { - blockInfo(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockInfo)); - } -} - -export class ArrayOfImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getBytes(index: i32): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, new wasmlib.Key32(index)); - } -} - -export class ImmutableGetEventsForBlockResults extends wasmlib.ScMapID { - event(): sc.ArrayOfImmutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBytes(arrID); - } -} - -export class ArrayOfMutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getBytes(index: i32): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, new wasmlib.Key32(index)); - } -} - -export class MutableGetEventsForBlockResults extends wasmlib.ScMapID { - event(): sc.ArrayOfMutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBytes(arrID); - } -} - -export class ImmutableGetEventsForContractResults extends wasmlib.ScMapID { - event(): sc.ArrayOfImmutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBytes(arrID); - } -} - -export class MutableGetEventsForContractResults extends wasmlib.ScMapID { - event(): sc.ArrayOfMutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBytes(arrID); - } -} - -export class ImmutableGetEventsForRequestResults extends wasmlib.ScMapID { - event(): sc.ArrayOfImmutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBytes(arrID); - } -} - -export class MutableGetEventsForRequestResults extends wasmlib.ScMapID { - event(): sc.ArrayOfMutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultEvent), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBytes(arrID); - } -} - -export class ImmutableGetLatestBlockInfoResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - blockInfo(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockInfo)); - } -} - -export class MutableGetLatestBlockInfoResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - blockInfo(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockInfo)); - } -} - -export class ArrayOfImmutableRequestID { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getRequestID(index: i32): wasmlib.ScImmutableRequestID { - return new wasmlib.ScImmutableRequestID(this.objID, new wasmlib.Key32(index)); - } -} - -export class ImmutableGetRequestIDsForBlockResults extends wasmlib.ScMapID { - requestID(): sc.ArrayOfImmutableRequestID { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestID), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_REQUEST_ID); - return new sc.ArrayOfImmutableRequestID(arrID); - } -} - -export class ArrayOfMutableRequestID { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getRequestID(index: i32): wasmlib.ScMutableRequestID { - return new wasmlib.ScMutableRequestID(this.objID, new wasmlib.Key32(index)); - } -} - -export class MutableGetRequestIDsForBlockResults extends wasmlib.ScMapID { - requestID(): sc.ArrayOfMutableRequestID { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestID), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_REQUEST_ID); - return new sc.ArrayOfMutableRequestID(arrID); - } -} - -export class ImmutableGetRequestReceiptResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - requestIndex(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestIndex)); - } - - requestRecord(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestRecord)); - } -} - -export class MutableGetRequestReceiptResults extends wasmlib.ScMapID { - blockIndex(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultBlockIndex)); - } - - requestIndex(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestIndex)); - } - - requestRecord(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestRecord)); - } -} - -export class ImmutableGetRequestReceiptsForBlockResults extends wasmlib.ScMapID { - requestRecord(): sc.ArrayOfImmutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestRecord), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBytes(arrID); - } -} - -export class MutableGetRequestReceiptsForBlockResults extends wasmlib.ScMapID { - requestRecord(): sc.ArrayOfMutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestRecord), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBytes(arrID); - } -} - -export class ImmutableIsRequestProcessedResults extends wasmlib.ScMapID { - requestProcessed(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestProcessed)); - } -} - -export class MutableIsRequestProcessedResults extends wasmlib.ScMapID { - requestProcessed(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultRequestProcessed)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/contract.ts b/packages/vm/wasmlib/ts/wasmlib/coregovernance/contract.ts deleted file mode 100644 index 045e454730..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coregovernance/contract.ts +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class AddAllowedStateControllerAddressCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncAddAllowedStateControllerAddress); - params: sc.MutableAddAllowedStateControllerAddressParams = new sc.MutableAddAllowedStateControllerAddressParams(); -} - -export class ClaimChainOwnershipCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncClaimChainOwnership); -} - -export class DelegateChainOwnershipCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDelegateChainOwnership); - params: sc.MutableDelegateChainOwnershipParams = new sc.MutableDelegateChainOwnershipParams(); -} - -export class RemoveAllowedStateControllerAddressCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRemoveAllowedStateControllerAddress); - params: sc.MutableRemoveAllowedStateControllerAddressParams = new sc.MutableRemoveAllowedStateControllerAddressParams(); -} - -export class RotateStateControllerCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRotateStateController); - params: sc.MutableRotateStateControllerParams = new sc.MutableRotateStateControllerParams(); -} - -export class SetChainInfoCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetChainInfo); - params: sc.MutableSetChainInfoParams = new sc.MutableSetChainInfoParams(); -} - -export class SetContractFeeCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetContractFee); - params: sc.MutableSetContractFeeParams = new sc.MutableSetContractFeeParams(); -} - -export class SetDefaultFeeCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetDefaultFee); - params: sc.MutableSetDefaultFeeParams = new sc.MutableSetDefaultFeeParams(); -} - -export class GetAllowedStateControllerAddressesCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetAllowedStateControllerAddresses); - results: sc.ImmutableGetAllowedStateControllerAddressesResults = new sc.ImmutableGetAllowedStateControllerAddressesResults(); -} - -export class GetChainInfoCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetChainInfo); - results: sc.ImmutableGetChainInfoResults = new sc.ImmutableGetChainInfoResults(); -} - -export class GetFeeInfoCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetFeeInfo); - params: sc.MutableGetFeeInfoParams = new sc.MutableGetFeeInfoParams(); - results: sc.ImmutableGetFeeInfoResults = new sc.ImmutableGetFeeInfoResults(); -} - -export class GetMaxBlobSizeCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetMaxBlobSize); - results: sc.ImmutableGetMaxBlobSizeResults = new sc.ImmutableGetMaxBlobSizeResults(); -} - -export class ScFuncs { - static addAllowedStateControllerAddress(ctx: wasmlib.ScFuncCallContext): AddAllowedStateControllerAddressCall { - let f = new AddAllowedStateControllerAddressCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static claimChainOwnership(ctx: wasmlib.ScFuncCallContext): ClaimChainOwnershipCall { - return new ClaimChainOwnershipCall(); - } - - static delegateChainOwnership(ctx: wasmlib.ScFuncCallContext): DelegateChainOwnershipCall { - let f = new DelegateChainOwnershipCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static removeAllowedStateControllerAddress(ctx: wasmlib.ScFuncCallContext): RemoveAllowedStateControllerAddressCall { - let f = new RemoveAllowedStateControllerAddressCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static rotateStateController(ctx: wasmlib.ScFuncCallContext): RotateStateControllerCall { - let f = new RotateStateControllerCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setChainInfo(ctx: wasmlib.ScFuncCallContext): SetChainInfoCall { - let f = new SetChainInfoCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setContractFee(ctx: wasmlib.ScFuncCallContext): SetContractFeeCall { - let f = new SetContractFeeCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static setDefaultFee(ctx: wasmlib.ScFuncCallContext): SetDefaultFeeCall { - let f = new SetDefaultFeeCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static getAllowedStateControllerAddresses(ctx: wasmlib.ScViewCallContext): GetAllowedStateControllerAddressesCall { - let f = new GetAllowedStateControllerAddressesCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static getChainInfo(ctx: wasmlib.ScViewCallContext): GetChainInfoCall { - let f = new GetChainInfoCall(); - f.func.setPtrs(null, f.results); - return f; - } - - static getFeeInfo(ctx: wasmlib.ScViewCallContext): GetFeeInfoCall { - let f = new GetFeeInfoCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getMaxBlobSize(ctx: wasmlib.ScViewCallContext): GetMaxBlobSizeCall { - let f = new GetMaxBlobSizeCall(); - f.func.setPtrs(null, f.results); - return f; - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/params.ts b/packages/vm/wasmlib/ts/wasmlib/coregovernance/params.ts deleted file mode 100644 index 8e0b37cb46..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coregovernance/params.ts +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableAddAllowedStateControllerAddressParams extends wasmlib.ScMapID { - chainOwner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwner)); - } - - feeColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamFeeColor)); - } - - stateControllerAddress(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class MutableAddAllowedStateControllerAddressParams extends wasmlib.ScMapID { - chainOwner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwner)); - } - - feeColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ParamFeeColor)); - } - - stateControllerAddress(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class ImmutableDelegateChainOwnershipParams extends wasmlib.ScMapID { - chainOwner(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwner)); - } -} - -export class MutableDelegateChainOwnershipParams extends wasmlib.ScMapID { - chainOwner(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamChainOwner)); - } -} - -export class ImmutableRemoveAllowedStateControllerAddressParams extends wasmlib.ScMapID { - stateControllerAddress(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class MutableRemoveAllowedStateControllerAddressParams extends wasmlib.ScMapID { - stateControllerAddress(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class ImmutableRotateStateControllerParams extends wasmlib.ScMapID { - stateControllerAddress(): wasmlib.ScImmutableAddress { - return new wasmlib.ScImmutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class MutableRotateStateControllerParams extends wasmlib.ScMapID { - stateControllerAddress(): wasmlib.ScMutableAddress { - return new wasmlib.ScMutableAddress(this.mapID, wasmlib.Key32.fromString(sc.ParamStateControllerAddress)); - } -} - -export class ImmutableSetChainInfoParams extends wasmlib.ScMapID { - maxBlobSize(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxBlobSize)); - } - - maxEventSize(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxEventSize)); - } - - maxEventsPerReq(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxEventsPerReq)); - } - - ownerFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class MutableSetChainInfoParams extends wasmlib.ScMapID { - maxBlobSize(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxBlobSize)); - } - - maxEventSize(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxEventSize)); - } - - maxEventsPerReq(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ParamMaxEventsPerReq)); - } - - ownerFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class ImmutableSetContractFeeParams extends wasmlib.ScMapID { - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } - - ownerFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class MutableSetContractFeeParams extends wasmlib.ScMapID { - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } - - ownerFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class ImmutableSetDefaultFeeParams extends wasmlib.ScMapID { - ownerFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class MutableSetDefaultFeeParams extends wasmlib.ScMapID { - ownerFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamOwnerFee)); - } - - validatorFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ParamValidatorFee)); - } -} - -export class ImmutableGetFeeInfoParams extends wasmlib.ScMapID { - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } -} - -export class MutableGetFeeInfoParams extends wasmlib.ScMapID { - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/results.ts b/packages/vm/wasmlib/ts/wasmlib/coregovernance/results.ts deleted file mode 100644 index 96b3881322..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coregovernance/results.ts +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ArrayOfImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getBytes(index: i32): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, new wasmlib.Key32(index)); - } -} - -export class ImmutableGetAllowedStateControllerAddressesResults extends wasmlib.ScMapID { - allowedStateControllerAddresses(): sc.ArrayOfImmutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultAllowedStateControllerAddresses), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfImmutableBytes(arrID); - } -} - -export class ArrayOfMutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - length(): i32 { - return wasmlib.getLength(this.objID); - } - - getBytes(index: i32): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, new wasmlib.Key32(index)); - } -} - -export class MutableGetAllowedStateControllerAddressesResults extends wasmlib.ScMapID { - allowedStateControllerAddresses(): sc.ArrayOfMutableBytes { - let arrID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultAllowedStateControllerAddresses), wasmlib.TYPE_ARRAY16|wasmlib.TYPE_BYTES); - return new sc.ArrayOfMutableBytes(arrID); - } -} - -export class ImmutableGetChainInfoResults extends wasmlib.ScMapID { - chainID(): wasmlib.ScImmutableChainID { - return new wasmlib.ScImmutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainID)); - } - - chainOwnerID(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); - } - - defaultOwnerFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDefaultOwnerFee)); - } - - defaultValidatorFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDefaultValidatorFee)); - } - - description(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultDescription)); - } - - feeColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultFeeColor)); - } - - maxBlobSize(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxBlobSize)); - } - - maxEventSize(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxEventSize)); - } - - maxEventsPerReq(): wasmlib.ScImmutableInt16 { - return new wasmlib.ScImmutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxEventsPerReq)); - } -} - -export class MutableGetChainInfoResults extends wasmlib.ScMapID { - chainID(): wasmlib.ScMutableChainID { - return new wasmlib.ScMutableChainID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainID)); - } - - chainOwnerID(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ResultChainOwnerID)); - } - - defaultOwnerFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDefaultOwnerFee)); - } - - defaultValidatorFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultDefaultValidatorFee)); - } - - description(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ResultDescription)); - } - - feeColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultFeeColor)); - } - - maxBlobSize(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxBlobSize)); - } - - maxEventSize(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxEventSize)); - } - - maxEventsPerReq(): wasmlib.ScMutableInt16 { - return new wasmlib.ScMutableInt16(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxEventsPerReq)); - } -} - -export class ImmutableGetFeeInfoResults extends wasmlib.ScMapID { - feeColor(): wasmlib.ScImmutableColor { - return new wasmlib.ScImmutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultFeeColor)); - } - - ownerFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultOwnerFee)); - } - - validatorFee(): wasmlib.ScImmutableInt64 { - return new wasmlib.ScImmutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultValidatorFee)); - } -} - -export class MutableGetFeeInfoResults extends wasmlib.ScMapID { - feeColor(): wasmlib.ScMutableColor { - return new wasmlib.ScMutableColor(this.mapID, wasmlib.Key32.fromString(sc.ResultFeeColor)); - } - - ownerFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultOwnerFee)); - } - - validatorFee(): wasmlib.ScMutableInt64 { - return new wasmlib.ScMutableInt64(this.mapID, wasmlib.Key32.fromString(sc.ResultValidatorFee)); - } -} - -export class ImmutableGetMaxBlobSizeResults extends wasmlib.ScMapID { - maxBlobSize(): wasmlib.ScImmutableInt32 { - return new wasmlib.ScImmutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxBlobSize)); - } -} - -export class MutableGetMaxBlobSizeResults extends wasmlib.ScMapID { - maxBlobSize(): wasmlib.ScMutableInt32 { - return new wasmlib.ScMutableInt32(this.mapID, wasmlib.Key32.fromString(sc.ResultMaxBlobSize)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/contract.ts b/packages/vm/wasmlib/ts/wasmlib/coreroot/contract.ts deleted file mode 100644 index 7ab3399228..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreroot/contract.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class DeployContractCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDeployContract); - params: sc.MutableDeployContractParams = new sc.MutableDeployContractParams(); -} - -export class GrantDeployPermissionCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncGrantDeployPermission); - params: sc.MutableGrantDeployPermissionParams = new sc.MutableGrantDeployPermissionParams(); -} - -export class RevokeDeployPermissionCall { - func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRevokeDeployPermission); - params: sc.MutableRevokeDeployPermissionParams = new sc.MutableRevokeDeployPermissionParams(); -} - -export class FindContractCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewFindContract); - params: sc.MutableFindContractParams = new sc.MutableFindContractParams(); - results: sc.ImmutableFindContractResults = new sc.ImmutableFindContractResults(); -} - -export class GetContractRecordsCall { - func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetContractRecords); - results: sc.ImmutableGetContractRecordsResults = new sc.ImmutableGetContractRecordsResults(); -} - -export class ScFuncs { - static deployContract(ctx: wasmlib.ScFuncCallContext): DeployContractCall { - let f = new DeployContractCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static grantDeployPermission(ctx: wasmlib.ScFuncCallContext): GrantDeployPermissionCall { - let f = new GrantDeployPermissionCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static revokeDeployPermission(ctx: wasmlib.ScFuncCallContext): RevokeDeployPermissionCall { - let f = new RevokeDeployPermissionCall(); - f.func.setPtrs(f.params, null); - return f; - } - - static findContract(ctx: wasmlib.ScViewCallContext): FindContractCall { - let f = new FindContractCall(); - f.func.setPtrs(f.params, f.results); - return f; - } - - static getContractRecords(ctx: wasmlib.ScViewCallContext): GetContractRecordsCall { - let f = new GetContractRecordsCall(); - f.func.setPtrs(null, f.results); - return f; - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/params.ts b/packages/vm/wasmlib/ts/wasmlib/coreroot/params.ts deleted file mode 100644 index 9129658507..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreroot/params.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableDeployContractParams extends wasmlib.ScMapID { - description(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); - } - - name(): wasmlib.ScImmutableString { - return new wasmlib.ScImmutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); - } - - programHash(): wasmlib.ScImmutableHash { - return new wasmlib.ScImmutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamProgramHash)); - } -} - -export class MutableDeployContractParams extends wasmlib.ScMapID { - description(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamDescription)); - } - - name(): wasmlib.ScMutableString { - return new wasmlib.ScMutableString(this.mapID, wasmlib.Key32.fromString(sc.ParamName)); - } - - programHash(): wasmlib.ScMutableHash { - return new wasmlib.ScMutableHash(this.mapID, wasmlib.Key32.fromString(sc.ParamProgramHash)); - } -} - -export class ImmutableGrantDeployPermissionParams extends wasmlib.ScMapID { - deployer(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDeployer)); - } -} - -export class MutableGrantDeployPermissionParams extends wasmlib.ScMapID { - deployer(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDeployer)); - } -} - -export class ImmutableRevokeDeployPermissionParams extends wasmlib.ScMapID { - deployer(): wasmlib.ScImmutableAgentID { - return new wasmlib.ScImmutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDeployer)); - } -} - -export class MutableRevokeDeployPermissionParams extends wasmlib.ScMapID { - deployer(): wasmlib.ScMutableAgentID { - return new wasmlib.ScMutableAgentID(this.mapID, wasmlib.Key32.fromString(sc.ParamDeployer)); - } -} - -export class ImmutableFindContractParams extends wasmlib.ScMapID { - hname(): wasmlib.ScImmutableHname { - return new wasmlib.ScImmutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } -} - -export class MutableFindContractParams extends wasmlib.ScMapID { - hname(): wasmlib.ScMutableHname { - return new wasmlib.ScMutableHname(this.mapID, wasmlib.Key32.fromString(sc.ParamHname)); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/results.ts b/packages/vm/wasmlib/ts/wasmlib/coreroot/results.ts deleted file mode 100644 index 7a7cf43c50..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/coreroot/results.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// (Re-)generated by schema tool -// >>>> DO NOT CHANGE THIS FILE! <<<< -// Change the json schema instead - -import * as wasmlib from "wasmlib"; -import * as sc from "./index"; - -export class ImmutableFindContractResults extends wasmlib.ScMapID { - contractFound(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultContractFound)); - } - - contractRecData(): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultContractRecData)); - } -} - -export class MutableFindContractResults extends wasmlib.ScMapID { - contractFound(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultContractFound)); - } - - contractRecData(): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.mapID, wasmlib.Key32.fromString(sc.ResultContractRecData)); - } -} - -export class MapHnameToImmutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - getBytes(key: wasmlib.ScHname): wasmlib.ScImmutableBytes { - return new wasmlib.ScImmutableBytes(this.objID, key.getKeyID()); - } -} - -export class ImmutableGetContractRecordsResults extends wasmlib.ScMapID { - contractRegistry(): sc.MapHnameToImmutableBytes { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultContractRegistry), wasmlib.TYPE_MAP); - return new sc.MapHnameToImmutableBytes(mapID); - } -} - -export class MapHnameToMutableBytes { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } - - clear(): void { - wasmlib.clear(this.objID); - } - - getBytes(key: wasmlib.ScHname): wasmlib.ScMutableBytes { - return new wasmlib.ScMutableBytes(this.objID, key.getKeyID()); - } -} - -export class MutableGetContractRecordsResults extends wasmlib.ScMapID { - contractRegistry(): sc.MapHnameToMutableBytes { - let mapID = wasmlib.getObjectID(this.mapID, wasmlib.Key32.fromString(sc.ResultContractRegistry), wasmlib.TYPE_MAP); - return new sc.MapHnameToMutableBytes(mapID); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/events.ts b/packages/vm/wasmlib/ts/wasmlib/events.ts deleted file mode 100644 index 0779992c77..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/events.ts +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -import {ScAddress, ScAgentID, ScChainID, ScColor, ScHash, ScHname, ScRequestID} from "./hashtypes"; -import * as keys from "./keys"; -import {base58Encode, ROOT} from "./context"; - -// encodes separate entities into a byte buffer -export class EventEncoder { - event: string; - - // constructs an encoder - constructor(eventName: string) { - this.event = eventName; - let timestamp = ROOT.getInt64(keys.KEY_TIMESTAMP).value(); - this.int64(timestamp / 1_000_000_000); - } - - // encodes an ScAddress into the byte buffer - address(value: ScAddress): EventEncoder { - return this.string(value.toString()); - } - - // encodes an ScAgentID into the byte buffer - agentID(value: ScAgentID): EventEncoder { - return this.string(value.toString()); - } - - // encodes a Bool into the byte buffer - bool(value: bool): EventEncoder { - return this.uint8(value ? 1 : 0); - } - - // encodes a substring of bytes into the byte buffer - bytes(value: u8[]): EventEncoder { - return this.string(base58Encode(value)); - } - - // encodes an ScChainID into the byte buffer - chainID(value: ScChainID): EventEncoder { - return this.string(value.toString()); - } - - // encodes an ScColor into the byte buffer - color(value: ScColor): EventEncoder { - return this.string(value.toString()); - } - - // retrieve the encoded byte buffer - emit(): void { - ROOT.getString(keys.KEY_EVENT).setValue(this.event); - } - - // encodes an ScHash into the byte buffer - hash(value: ScHash): EventEncoder { - return this.string(value.toString()); - } - - // encodes an ScHname into the byte buffer - hname(value: ScHname): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Int8 into the byte buffer - int8(value: i8): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Int16 into the byte buffer - int16(value: i16): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Int32 into the byte buffer - int32(value: i32): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Int64 into the byte buffer - int64(value: i64): EventEncoder { - return this.string(value.toString()); - } - - // encodes an ScRequestID into the byte buffer - requestID(value: ScRequestID): EventEncoder { - return this.string(value.toString()); - } - - // encodes an UTF-8 text string into the byte buffer - string(value: string): EventEncoder { - //TODO encode potential vertical bars that are present in the value string - this.event += "|" + value; - return this; - } - - // encodes an Uint8 into the byte buffer - uint8(value: u8): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Uint16 into the byte buffer - uint16(value: u16): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Uint32 into the byte buffer - uint32(value: u32): EventEncoder { - return this.string(value.toString()); - } - - // encodes an Uint64 into the byte buffer - uint64(value: u64): EventEncoder { - return this.string(value.toString()); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/exports.ts b/packages/vm/wasmlib/ts/wasmlib/exports.ts deleted file mode 100644 index 19a08439fc..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/exports.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// Provide host with details about funcs and views in this smart contract - -import {ROOT, ScFuncContext, ScViewContext} from "./context"; -import {KEY_EXPORTS, KEY_PARAMS, KEY_RESULTS, KEY_STATE, KEY_ZZZZZZZ} from "./keys"; -import {ScMutableStringArray} from "./mutable"; -import {getObjectID, OBJ_ID_PARAMS, OBJ_ID_RESULTS, OBJ_ID_ROOT, OBJ_ID_STATE, TYPE_MAP} from "./host"; - -// Note that we do not use the Wasm export symbol table on purpose -// because Wasm does not allow us to determine whether the symbols -// are meant as view or func, or meant as extra public callbacks -// generated by the compilation of the the Wasm code. -// There are only 2 symbols the ISCP host will actually look for -// in the export table: -// on_load (which must be defined by the SC code) and -// on_call (which is defined here as part of WasmLib) - -type ScFuncContextFunc = (f: ScFuncContext) => void; -type ScViewContextFunc = (v: ScViewContext) => void; - -let funcs: Array = []; -let views: Array = []; - -// general entrypoint for the host to call any SC function -// the host will pass the index of one of the entry points -// that was provided by onLoad during SC initialization -export function onCall(index: i32): void { - let ctx = new ScFuncContext(); - ctx.require(getObjectID(OBJ_ID_ROOT, KEY_STATE, TYPE_MAP) == OBJ_ID_STATE, "object id mismatch"); - ctx.require(getObjectID(OBJ_ID_ROOT, KEY_PARAMS, TYPE_MAP) == OBJ_ID_PARAMS, "object id mismatch"); - ctx.require(getObjectID(OBJ_ID_ROOT, KEY_RESULTS, TYPE_MAP) == OBJ_ID_RESULTS, "object id mismatch"); - - if ((index & 0x8000) != 0) { - // immutable view function, invoke with a view context - let view = views[index & 0x7fff]; - view(new ScViewContext()); - return; - } - - // mutable full function, invoke with a func context - let func = funcs[index]; - func(ctx); -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// context for onLoad function to be able to tell host which -// funcs and views are available as entry points to the SC -export class ScExports { - exports: ScMutableStringArray; - - // constructs the symbol export context for the onLoad function - constructor() { - this.exports = ROOT.getStringArray(KEY_EXPORTS); - // tell host what value our special predefined key is - // this helps detect versioning problems between host - // and client versions of WasmLib - this.exports.getString(KEY_ZZZZZZZ.keyID).setValue("TypeScript:KEY_ZZZZZZZ"); - } - - // defines the external name of a smart contract func - // and the entry point function associated with it - addFunc(name: string, f: ScFuncContextFunc): void { - let index = funcs.length; - funcs.push(f); - this.exports.getString(index).setValue(name); - } - - // defines the external name of a smart contract view - // and the entry point function associated with it - addView(name: string, v: ScViewContextFunc): void { - let index = views.length as i32; - views.push(v); - this.exports.getString(index | 0x8000).setValue(name); - } -} - diff --git a/packages/vm/wasmlib/ts/wasmlib/hashtypes.ts b/packages/vm/wasmlib/ts/wasmlib/hashtypes.ts deleted file mode 100644 index 72e35f1ac5..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/hashtypes.ts +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// standard value types used by the ISCP - -import {base58Encode, ScFuncContext} from "./context"; -import {Convert} from "./convert"; -import {getKeyIDFromBytes, panic} from "./host"; -import {Key32, MapKey} from "./keys"; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -function zeroes(count: i32): u8[] { - let buf : u8[] = new Array(count); - buf.fill(0); - return buf; -} - -// value object for 33-byte Tangle address ids -export class ScAddress implements MapKey { - id: u8[] = zeroes(33); - - // construct from byte array - static fromBytes(bytes: u8[]): ScAddress { - let o = new ScAddress(); - if (bytes.length != o.id.length) { - panic("invalid address id length"); - } - o.id = bytes.slice(0); - return o; - } - - // returns agent id representation of this Tangle address - asAgentID(): ScAgentID { - return ScAgentID.fromParts(this, ScHname.zero); - } - - equals(other: ScAddress): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 37-byte agent ids -export class ScAgentID implements MapKey { - id: u8[] = zeroes(37); - - // construct from byte array - static fromBytes(bytes: u8[]): ScAgentID { - let o = new ScAgentID(); - if (bytes.length != o.id.length) { - panic("invalid agent id length"); - } - o.id = bytes.slice(0); - return o; - } - - // construct from address and contract name hash - static fromParts(address: ScAddress, hname: ScHname): ScAgentID { - let agentID = new ScAgentID(); - agentID.id = address.id.concat(hname.id); - return agentID; - } - - // gets Tangle address from agent id - address(): ScAddress { - let address = new ScAddress(); - address.id = this.id.slice(0, address.id.length); - return address; - } - - equals(other: ScAgentID): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // get contract name hash for this agent - hname(): ScHname { - let hname = new ScHname(0); - hname.id = this.id.slice(this.id.length - hname.id.length); - return hname; - } - - // checks to see if agent id represents a Tangle address - isAddress(): boolean { - return this.hname().equals(ScHname.zero); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 33-byte chain ids -export class ScChainID implements MapKey { - id: u8[] = zeroes(33); - - // construct from byte array - static fromBytes(bytes: u8[]): ScChainID { - let o = new ScChainID(); - if (bytes.length != o.id.length) { - panic("invalid chain id length"); - } - o.id = bytes.slice(0); - return o; - } - - // gets Tangle address from chain id - address(): ScAddress { - let address = new ScAddress(); - address.id = this.id.slice(0, address.id.length); - return address; - } - - equals(other: ScChainID): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 32-byte token color -export class ScColor implements MapKey { - id: u8[] = new Array(32); - - // predefined colors - static IOTA: ScColor = new ScColor(0x00); - static MINT: ScColor = new ScColor(0xff); - - constructor(fill: u8) { - this.id.fill(fill) - } - - // construct from byte array - static fromBytes(bytes: u8[]): ScColor { - let o = new ScColor(0); - if (bytes.length != o.id.length) { - panic("invalid color id length"); - } - o.id = bytes.slice(0); - return o; - } - - // construct from request id, this will return newly minted color - static fromRequestID(requestID: ScRequestID): ScColor { - let color = new ScColor(0); - color.id = requestID.id.slice(0, color.id.length) - return color; - } - - equals(other: ScColor): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 32-byte hash value -export class ScHash implements MapKey { - id: u8[] = zeroes(32); - - // construct from byte array - static fromBytes(bytes: u8[]): ScHash { - let o = new ScHash(); - if (bytes.length != o.id.length) { - panic("invalid hash id length"); - } - o.id = bytes.slice(0); - return o; - } - - equals(other: ScHash): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 4-byte name hash -export class ScHname implements MapKey { - id: u8[] = zeroes(4) - - static zero: ScHname = new ScHname(0); - - // construct from name string - constructor(id: u32) { - this.id = Convert.fromI32(id); - } - - static fromName(name: string): ScHname { - return new ScFuncContext().utility().hname(name); - } - - // construct from byte array - static fromBytes(bytes: u8[]): ScHname { - let o = new ScHname(0); - if (bytes.length != o.id.length) { - panic("invalid hname length"); - } - o.id = bytes.slice(0); - return o; - } - - equals(other: ScHname): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation: 8 hex digits - toString(): string { - const hex = "0123456789abcdef"; - let res = "" - for (let i = 3; i >= 0; i--) { - let b = this.id[i]; - res += hex.charAt((b >> 4) & 0x0f) + hex.charAt(b & 0x0f); - } - return res; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value object for 34-byte transaction request ids -export class ScRequestID implements MapKey { - id: u8[] = zeroes(34); - - // construct from byte array - static fromBytes(bytes: u8[]): ScRequestID { - let o = new ScRequestID(); - if (bytes.length != o.id.length) { - panic("invalid request id length"); - } - o.id = bytes.slice(0); - return o; - } - - equals(other: ScRequestID): boolean { - return Convert.equals(this.id, other.id); - } - - // can be used as key in maps - getKeyID(): Key32 { - return getKeyIDFromBytes(this.id); - } - - // convert to byte array representation - toBytes(): u8[] { - return this.id; - } - - // human-readable string representation - toString(): string { - return base58Encode(this.id); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/host.ts b/packages/vm/wasmlib/ts/wasmlib/host.ts deleted file mode 100644 index 4337d407fc..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/host.ts +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// interface WasmLib to the VM host - -// all type id values should exactly match their counterpart values on the host! - -import {Key32} from "./keys"; -import * as keys from "./keys"; -import {Convert} from "./convert"; - -export const TYPE_ARRAY: i32 = 0x20; -export const TYPE_ARRAY16: i32 = 0x60; -export const TYPE_CALL: i32 = 0x80; -export const TYPE_MASK: i32 = 0x1f; - -export const TYPE_ADDRESS: i32 = 1; -export const TYPE_AGENT_ID: i32 = 2; -export const TYPE_BOOL: i32 = 3; -export const TYPE_BYTES: i32 = 4; -export const TYPE_CHAIN_ID: i32 = 5; -export const TYPE_COLOR: i32 = 6; -export const TYPE_HASH: i32 = 7; -export const TYPE_HNAME: i32 = 8; -export const TYPE_INT8: i32 = 9; -export const TYPE_INT16: i32 = 10; -export const TYPE_INT32: i32 = 11; -export const TYPE_INT64: i32 = 12; -export const TYPE_MAP: i32 = 13; -export const TYPE_REQUEST_ID: i32 = 14; -export const TYPE_STRING: i32 = 15; - -export const OBJ_ID_NULL: i32 = 0; -export const OBJ_ID_ROOT: i32 = 1; -export const OBJ_ID_STATE: i32 = 2; -export const OBJ_ID_PARAMS: i32 = 3; -export const OBJ_ID_RESULTS: i32 = 4; - -// size in bytes of predefined types, indexed by the TYPE_* consts -export const TYPE_SIZES: u8[] = [0, 33, 37, 1, 0, 33, 32, 32, 4, 1, 2, 4, 8, 0, 34, 0]; - - -// These 4 external functions are funneling the entire WasmLib functionality -// to their counterparts on the host. - -// Copy the value data bytes of type stored in the host container object , -// under key , into the pre-allocated which can hold len bytes. -// Returns the actual length of the value data bytes on the host. -@external("WasmLib", "hostGetBytes") -export declare function hostGetBytes(objID: i32, keyID: i32, typeID: i32, buffer: usize, size: i32): i32; - -// Retrieve the key id associated with the data bytes of length . -// A negative length indicates a bytes key, positive indicates a string key -// We discern between the two for better readable logging purposes -@external("WasmLib", "hostGetKeyID") -export declare function hostGetKeyID(key: usize, size: i32): i32; - -// Retrieve the id of the container sub-object of type stored in -// the host container object , under key . -@external("WasmLib", "hostGetObjectID") -export declare function hostGetObjectID(objID: i32, keyID: i32, typeID: i32): i32; - -// copy the value data bytes of type from the -// into the host container object , under key . -@external("WasmLib", "hostSetBytes") -export declare function hostSetBytes(objID: i32, keyID: i32, typeID: i32, buffer: usize, size: i32):void; - - -export function callFunc(objID: i32, keyID: Key32, params: u8[]): u8[] { - // variable-sized type, first query expected length of bytes array - // (pass zero-length buffer) - let size = hostGetBytes(objID, keyID.keyID, TYPE_CALL, params.dataStart, params.length); - - // -1 means non-existent, so return default value for type - if (size <= 0) { - return []; - } - - // allocate a sufficient length byte array in Wasm memory - // and let the host copy the actual data bytes into this Wasm byte array - let result:u8[] = new Array(size); - hostGetBytes(objID, keyID.keyID, TYPE_CALL + 1, result.dataStart, size); - return result; -} - -// Clear the entire contents of the specified container object. -// Removes all its sub-objects as well. -export function clear(objID: i32): void { - // special key "length" is used with integer value zero - setBytes(objID, keys.KEY_LENGTH, TYPE_INT32, Convert.fromI32(0)); -} - -// Delete the value with the specified key and type from the specified container object. -export function delKey(objID: i32, keyID: Key32, typeID: i32): void { - // size -1 means delete - // this removes the need for a separate hostDelete function - hostSetBytes(objID, keyID.keyID, typeID, 0, -1); -} - -// Check if the specified container object contains a value with the specified key and type. -export function exists(objID: i32, keyID: Key32, typeID: i32): boolean { - // negative length (-1) means only test for existence - // returned size -1 indicates keyID not found (or error) - // this removes the need for a separate hostExists function - return hostGetBytes(objID, keyID.keyID, typeID, 0, -1) >= 0; -} - -// Retrieve the bytes stored in the specified container object under the specified key -// and with specified type. Note that if the key does not exist this function will -// return the default value for the specified type. -export function getBytes(objID: i32, keyID: Key32, typeID: i32): u8[] { - let size = TYPE_SIZES[typeID] as i32; - if (size == 0) { - // variable-sized type, first query expected length of bytes array - // (pass zero-length buffer) - size = hostGetBytes(objID, keyID.keyID, typeID, 0, 0); - - // -1 means non-existent, so return default value for type - if (size < 0) { - return []; - } - } - - // allocate a sufficient length byte array in Wasm memory - // and let the host copy the actual data bytes into this Wasm byte array - let result:u8[] = new Array(size); - hostGetBytes(objID, keyID.keyID, typeID, result.dataStart, size); - return result; -} - -// Retrieve the key id that the host has associated with the specified bytes key -export function getKeyID(bytes: u8[], size:i32): Key32 { - // negative size indicates this is a bytes key - return new Key32(hostGetKeyID(bytes.dataStart, size)); -} - -// Retrieve the key id that the host has associated with the specified bytes key -export function getKeyIDFromBytes(bytes: u8[]): Key32 { - // negative size indicates this is a bytes key - return getKeyID(bytes, -bytes.length - 1); -} - -// Retrieve the key id that the host has associated with the specified string key -export function getKeyIDFromString(key: string): Key32 { - let bytes = Convert.fromString(key); - - // non-negative size indicates this is a string key - return getKeyID(bytes, bytes.length); -} - -// Retrieve the key id that the host has associated with the specified integer key -export function getKeyIDFromUint64(key: u64, nrOfBytes: usize): Key32 { - // negative size indicates this is a bytes key - return getKeyID(Convert.fromI64(key as i64), -nrOfBytes - 1); -} - -// Retrieve the length of an array container object on the host -export function getLength(objID: i32): i32 { - // special integer key "length" is used - let bytes = getBytes(objID, keys.KEY_LENGTH, TYPE_INT32); - return Convert.toI32(bytes); -} - -// Retrieve the id of the specified container sub-object -export function getObjectID(objID: i32, keyID: Key32, typeID: i32): i32 { - return hostGetObjectID(objID, keyID.keyID, typeID); -} - -// Direct logging of informational text to host log -export function log(text: string): void { - setBytes(1, keys.KEY_LOG, TYPE_STRING, Convert.fromString(text)); -} - -// Direct logging of error to host log, followed by panicking out of the Wasm code -export function panic(text: string): void { - setBytes(1, keys.KEY_PANIC, TYPE_STRING, Convert.fromString(text)); -} - -// Store the provided value bytes of specified type in the specified container object -// under the specified key. Note that if the key does not exist this function will -// create it first. -export function setBytes(objID: i32, keyID: Key32, typeID: i32, value: u8[]): void { - return hostSetBytes(objID, keyID.keyID, typeID, value.dataStart, value.length); -} - -// Direct logging of debug trace text to host log -export function trace(text: string): void { - setBytes(1, keys.KEY_TRACE, TYPE_STRING, Convert.fromString(text)); -} diff --git a/packages/vm/wasmlib/ts/wasmlib/immutable.ts b/packages/vm/wasmlib/ts/wasmlib/immutable.ts deleted file mode 100644 index 78519b84cd..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/immutable.ts +++ /dev/null @@ -1,1149 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// immutable proxies to host objects - -import { base58Encode } from "./context"; -import {Convert} from "./convert"; -import {ScAddress,ScAgentID,ScChainID,ScColor,ScHash,ScHname,ScRequestID} from "./hashtypes"; -import * as host from "./host"; -import {Key32,MapKey} from "./keys"; - -// value proxy for immutable ScAddress in host container -export class ScImmutableAddress { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_ADDRESS); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScAddress { - return ScAddress.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_ADDRESS)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScAddress -export class ScImmutableAddressArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getAddress(index: i32): ScImmutableAddress { - return new ScImmutableAddress(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScAgentID in host container -export class ScImmutableAgentID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_AGENT_ID); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScAgentID { - return ScAgentID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_AGENT_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScAgentID -export class ScImmutableAgentIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getAgentID(index: i32): ScImmutableAgentID { - return new ScImmutableAgentID(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Bool in host container -export class ScImmutableBool { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_BOOL); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): boolean { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_BOOL); - return bytes[0] != 0; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Bool -export class ScImmutableBoolArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getBool(index: i32): ScImmutableBool { - return new ScImmutableBool(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable bytes array in host container -export class ScImmutableBytes { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_BYTES); - } - - // human-readable string representation - toString(): string { - return base58Encode(this.value()); - } - - // get value from host container - value(): u8[] { - return host.getBytes(this.objID, this.keyID, host.TYPE_BYTES); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of byte array -export class ScImmutableBytesArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getBytes(index: i32): ScImmutableBytes { - return new ScImmutableBytes(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScChainID in host container -export class ScImmutableChainID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_CHAIN_ID); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScChainID { - return ScChainID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_CHAIN_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScChainID -export class ScImmutableChainIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getChainID(index: i32): ScImmutableChainID { - return new ScImmutableChainID(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScColor in host container -export class ScImmutableColor { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_COLOR); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScColor { - return ScColor.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_COLOR)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScColor -export class ScImmutableColorArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getColor(index: i32): ScImmutableColor { - return new ScImmutableColor(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScHash in host container -export class ScImmutableHash { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_HASH); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScHash { - return ScHash.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HASH)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScHash -export class ScImmutableHashArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getHash(index: i32): ScImmutableHash { - return new ScImmutableHash(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable ScHname in host container -export class ScImmutableHname { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_HNAME); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScHname { - return ScHname.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HNAME)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScHname -export class ScImmutableHnameArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getHname(index: i32): ScImmutableHname { - return new ScImmutableHname(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int8 in host container -export class ScImmutableInt8 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT8); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): i8 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); - return bytes[0] as i8; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int8 -export class ScImmutableInt8Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getInt8(index: i32): ScImmutableInt8 { - return new ScImmutableInt8(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int16 in host container -export class ScImmutableInt16 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT16); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): i16 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT16); - return Convert.toI16(bytes); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int16 -export class ScImmutableInt16Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getInt16(index: i32): ScImmutableInt16 { - return new ScImmutableInt16(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int32 in host container -export class ScImmutableInt32 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT32); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): i32 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT32); - return Convert.toI32(bytes); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int32 -export class ScImmutableInt32Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getInt32(index: i32): ScImmutableInt32 { - return new ScImmutableInt32(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Int64 in host container -export class ScImmutableInt64 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT64); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): i64 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT64); - return Convert.toI64(bytes); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Int64 -export class ScImmutableInt64Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getInt64(index: i32): ScImmutableInt64 { - return new ScImmutableInt64(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// map proxy for immutable map -export class ScImmutableMap { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - callFunc(keyID: Key32, params: u8[]): u8[] { - return host.callFunc(this.objID, keyID, params); - } - - // get value proxy for immutable ScAddress field specified by key - getAddress(key: MapKey): ScImmutableAddress { - return new ScImmutableAddress(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableAddressArray specified by key - getAddressArray(key: MapKey): ScImmutableAddressArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_ADDRESS | host.TYPE_ARRAY); - return new ScImmutableAddressArray(arrID); - } - - // get value proxy for immutable ScAgentID field specified by key - getAgentID(key: MapKey): ScImmutableAgentID { - return new ScImmutableAgentID(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableAgentIDArray specified by key - getAgentIDArray(key: MapKey): ScImmutableAgentIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_AGENT_ID | host.TYPE_ARRAY); - return new ScImmutableAgentIDArray(arrID); - } - - // get value proxy for immutable Bool field specified by key - getBool(key: MapKey): ScImmutableBool { - return new ScImmutableBool(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableBoolArray specified by key - getBoolArray(key: MapKey): ScImmutableBoolArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BOOL | host.TYPE_ARRAY); - return new ScImmutableBoolArray(arrID); - } - - // get value proxy for immutable bytes array field specified by key - getBytes(key: MapKey): ScImmutableBytes { - return new ScImmutableBytes(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableBytesArray specified by key - getBytesArray(key: MapKey): ScImmutableBytesArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BYTES | host.TYPE_ARRAY); - return new ScImmutableBytesArray(arrID); - } - - // get value proxy for immutable ScChainID field specified by key - getChainID(key: MapKey): ScImmutableChainID { - return new ScImmutableChainID(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableChainIDArray specified by key - getChainIDArray(key: MapKey): ScImmutableChainIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_CHAIN_ID | host.TYPE_ARRAY); - return new ScImmutableChainIDArray(arrID); - } - - // get value proxy for immutable ScColor field specified by key - getColor(key: MapKey): ScImmutableColor { - return new ScImmutableColor(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableColorArray specified by key - getColorArray(key: MapKey): ScImmutableColorArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_COLOR | host.TYPE_ARRAY); - return new ScImmutableColorArray(arrID); - } - - // get value proxy for immutable ScHash field specified by key - getHash(key: MapKey): ScImmutableHash { - return new ScImmutableHash(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableHashArray specified by key - getHashArray(key: MapKey): ScImmutableHashArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HASH | host.TYPE_ARRAY); - return new ScImmutableHashArray(arrID); - } - - // get value proxy for immutable ScHname field specified by key - getHname(key: MapKey): ScImmutableHname { - return new ScImmutableHname(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableHnameArray specified by key - getHnameArray(key: MapKey): ScImmutableHnameArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HNAME | host.TYPE_ARRAY); - return new ScImmutableHnameArray(arrID); - } - - // get value proxy for immutable Int8 field specified by key - getInt8(key: MapKey): ScImmutableInt8 { - return new ScImmutableInt8(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableInt8Array specified by key - getInt8Array(key: MapKey): ScImmutableInt8Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); - return new ScImmutableInt8Array(arrID); - } - - // get value proxy for immutable Int16 field specified by key - getInt16(key: MapKey): ScImmutableInt16 { - return new ScImmutableInt16(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableInt16Array specified by key - getInt16Array(key: MapKey): ScImmutableInt16Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); - return new ScImmutableInt16Array(arrID); - } - - // get value proxy for immutable Int32 field specified by key - getInt32(key: MapKey): ScImmutableInt32 { - return new ScImmutableInt32(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableInt32Array specified by key - getInt32Array(key: MapKey): ScImmutableInt32Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); - return new ScImmutableInt32Array(arrID); - } - - // get value proxy for immutable Int64 field specified by key - getInt64(key: MapKey): ScImmutableInt64 { - return new ScImmutableInt64(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableInt64Array specified by key - getInt64Array(key: MapKey): ScImmutableInt64Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); - return new ScImmutableInt64Array(arrID); - } - - // get map proxy for ScImmutableMap specified by key - getMap(key: MapKey): ScImmutableMap { - let mapID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP); - return new ScImmutableMap(mapID); - } - - // get array proxy for ScImmutableMapArray specified by key - getMapArray(key: MapKey): ScImmutableMapArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP | host.TYPE_ARRAY); - return new ScImmutableMapArray(arrID); - } - - // get value proxy for immutable ScRequestID field specified by key - getRequestID(key: MapKey): ScImmutableRequestID { - return new ScImmutableRequestID(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableRequestIDArray specified by key - getRequestIDArray(key: MapKey): ScImmutableRequestIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_REQUEST_ID | host.TYPE_ARRAY); - return new ScImmutableRequestIDArray(arrID); - } - - // get value proxy for immutable UTF-8 text string field specified by key - getString(key: MapKey): ScImmutableString { - return new ScImmutableString(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableStringArray specified by key - getStringArray(key: MapKey): ScImmutableStringArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_STRING | host.TYPE_ARRAY); - return new ScImmutableStringArray(arrID); - } - - // get value proxy for immutable Uint8 field specified by key - getUint8(key: MapKey): ScImmutableUint8 { - return new ScImmutableUint8(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableUint8Array specified by key - getUint8Array(key: MapKey): ScImmutableUint8Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); - return new ScImmutableUint8Array(arrID); - } - - // get value proxy for immutable Uint16 field specified by key - getUint16(key: MapKey): ScImmutableUint16 { - return new ScImmutableUint16(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableUint16Array specified by key - getUint16Array(key: MapKey): ScImmutableUint16Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); - return new ScImmutableUint16Array(arrID); - } - - // get value proxy for immutable Uint32 field specified by key - getUint32(key: MapKey): ScImmutableUint32 { - return new ScImmutableUint32(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableUint32Array specified by key - getUint32Array(key: MapKey): ScImmutableUint32Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); - return new ScImmutableUint32Array(arrID); - } - - // get value proxy for immutable Uint64 field specified by key - getUint64(key: MapKey): ScImmutableUint64 { - return new ScImmutableUint64(this.objID, key.getKeyID()); - } - - // get array proxy for ScImmutableUint64Array specified by key - getUint64Array(key: MapKey): ScImmutableUint64Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); - return new ScImmutableUint64Array(arrID); - } - - mapID(): i32 { - return this.objID; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of maps -export class ScImmutableMapArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getMap(index: i32): ScImmutableMap { - let mapID = host.getObjectID(this.objID, new Key32(index), host.TYPE_MAP); - return new ScImmutableMap(mapID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// value proxy for immutable ScRequestID in host container -export class ScImmutableRequestID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_REQUEST_ID); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): ScRequestID { - return ScRequestID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_REQUEST_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of ScRequestID -export class ScImmutableRequestIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getRequestID(index: i32): ScImmutableRequestID { - return new ScImmutableRequestID(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable UTF-8 text string in host container -export class ScImmutableString { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_STRING); - } - - // human-readable string representation - toString(): string { - return this.value(); - } - - // get value from host container - value(): string { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_STRING); - return Convert.toString(bytes); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of UTF-8 text string -export class ScImmutableStringArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getString(index: i32): ScImmutableString { - return new ScImmutableString(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint8 in host container -export class ScImmutableUint8 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT8); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): u8 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); - return bytes[0] as u8; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint8 -export class ScImmutableUint8Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getUint8(index: i32): ScImmutableUint8 { - return new ScImmutableUint8(this.objID, new Key32(index)); - } - - // number of items in array - length(): u32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint16 in host container -export class ScImmutableUint16 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT16); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): u16 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT16); - return Convert.toI16(bytes) as u16; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint16 -export class ScImmutableUint16Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getUint16(index: i32): ScImmutableUint16 { - return new ScImmutableUint16(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint32 in host container -export class ScImmutableUint32 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT32); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): u32 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT32); - return Convert.toI32(bytes) as u32; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint32 -export class ScImmutableUint32Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getUint32(index: i32): ScImmutableUint32 { - return new ScImmutableUint32(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for immutable Uint64 in host container -export class ScImmutableUint64 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT64); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // get value from host container - value(): u64 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT64); - return Convert.toI64(bytes) as u64; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for immutable array of Uint64 -export class ScImmutableUint64Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // get value proxy for item at index, index can be 0..length()-1 - getUint64(index: i32): ScImmutableUint64 { - return new ScImmutableUint64(this.objID, new Key32(index)); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/index.ts b/packages/vm/wasmlib/ts/wasmlib/index.ts deleted file mode 100644 index bb10d93cda..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from "./bytes" -export * from "./context" -export * from "./contract" -export * from "./convert" -export * from "./events" -export * from "./exports" -export * from "./hashtypes" -export * from "./host" -export * from "./immutable" -export * from "./keys" -export * from "./mutable" diff --git a/packages/vm/wasmlib/ts/wasmlib/keys.ts b/packages/vm/wasmlib/ts/wasmlib/keys.ts deleted file mode 100644 index 7e1b25601c..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/keys.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// conversion of data bytes to key id - -import {getKeyIDFromString} from "./host"; - -export interface MapKey { - getKeyID(): Key32; -} - -export class Key32 implements MapKey { - keyID: i32; - - constructor(keyID: i32) { - this.keyID = keyID; - } - - static fromString(key: string): Key32 { - return getKeyIDFromString(key); - } - - getKeyID(): Key32 { - return this; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// all predefined key id values should exactly match their counterpart values on the host! -// note that predefined key ids are negative values to distinguish them from indexes - -// @formatter:off -export const KEY_ACCOUNT_ID = new Key32(-1); -export const KEY_ADDRESS = new Key32(-2); -export const KEY_BALANCES = new Key32(-3); -export const KEY_BASE58_DECODE = new Key32(-4); -export const KEY_BASE58_ENCODE = new Key32(-5); -export const KEY_BLS_ADDRESS = new Key32(-6); -export const KEY_BLS_AGGREGATE = new Key32(-7); -export const KEY_BLS_VALID = new Key32(-8); -export const KEY_CALL = new Key32(-9); -export const KEY_CALLER = new Key32(-10); -export const KEY_CHAIN_ID = new Key32(-11); -export const KEY_CHAIN_OWNER_ID = new Key32(-12); -export const KEY_COLOR = new Key32(-13); -export const KEY_CONTRACT = new Key32(-14); -export const KEY_CONTRACT_CREATOR = new Key32(-15); -export const KEY_DEPLOY = new Key32(-16); -export const KEY_ED25519_ADDRESS = new Key32(-17); -export const KEY_ED25519_VALID = new Key32(-18); -export const KEY_EVENT = new Key32(-19); -export const KEY_EXPORTS = new Key32(-20); -export const KEY_HASH_BLAKE2B = new Key32(-21); -export const KEY_HASH_SHA3 = new Key32(-22); -export const KEY_HNAME = new Key32(-23); -export const KEY_INCOMING = new Key32(-24); -export const KEY_LENGTH = new Key32(-25); -export const KEY_LOG = new Key32(-26); -export const KEY_MAPS = new Key32(-27); -export const KEY_MINTED = new Key32(-28); -export const KEY_PANIC = new Key32(-29); -export const KEY_PARAMS = new Key32(-30); -export const KEY_POST = new Key32(-31); -export const KEY_RANDOM = new Key32(-32); -export const KEY_REQUEST_ID = new Key32(-33); -export const KEY_RESULTS = new Key32(-34); -export const KEY_RETURN = new Key32(-35); -export const KEY_STATE = new Key32(-36); -export const KEY_TIMESTAMP = new Key32(-37); -export const KEY_TRACE = new Key32(-38); -export const KEY_TRANSFERS = new Key32(-39); -export const KEY_UTILITY = new Key32(-40); -export const KEY_ZZZZZZZ = new Key32(-41); -// @formatter:on diff --git a/packages/vm/wasmlib/ts/wasmlib/mutable.ts b/packages/vm/wasmlib/ts/wasmlib/mutable.ts deleted file mode 100644 index 6bb0923a10..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/mutable.ts +++ /dev/null @@ -1,1580 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// mutable proxies to host objects - -import {base58Encode, ROOT} from "./context"; -import {Convert} from "./convert"; -import {ScAddress, ScAgentID, ScChainID, ScColor, ScHash, ScHname, ScRequestID} from "./hashtypes"; -import * as host from "./host"; -import { - ScImmutableAddressArray, - ScImmutableAgentIDArray, - ScImmutableBoolArray, - ScImmutableBytesArray, - ScImmutableChainIDArray, - ScImmutableColorArray, - ScImmutableHashArray, - ScImmutableHnameArray, - ScImmutableInt8Array, - ScImmutableInt16Array, - ScImmutableInt32Array, - ScImmutableInt64Array, - ScImmutableMap, - ScImmutableMapArray, - ScImmutableRequestIDArray, - ScImmutableStringArray, - ScImmutableUint8Array, - ScImmutableUint16Array, - ScImmutableUint32Array, - ScImmutableUint64Array, -} from "./immutable"; -import {Key32, KEY_MAPS, MapKey} from "./keys"; - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScAddress in host container -export class ScMutableAddress { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_ADDRESS); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_ADDRESS); - } - - // set value in host container - setValue(val: ScAddress): void { - host.setBytes(this.objID, this.keyID, host.TYPE_ADDRESS, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScAddress { - return ScAddress.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_ADDRESS)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScAddress -export class ScMutableAddressArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getAddress(index: i32): ScMutableAddress { - return new ScMutableAddress(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableAddressArray { - return new ScImmutableAddressArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScAgentID in host container -export class ScMutableAgentID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_AGENT_ID); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_AGENT_ID); - } - - // set value in host container - setValue(val: ScAgentID): void { - host.setBytes(this.objID, this.keyID, host.TYPE_AGENT_ID, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScAgentID { - return ScAgentID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_AGENT_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScAgentID -export class ScMutableAgentIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getAgentID(index: i32): ScMutableAgentID { - return new ScMutableAgentID(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableAgentIDArray { - return new ScImmutableAgentIDArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Bool in host container -export class ScMutableBool { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_BOOL); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_BOOL); - } - - // set value in host container - setValue(val: boolean): void { - let bytes: u8[] = [(val ? 1 : 0) as u8] - host.setBytes(this.objID, this.keyID, host.TYPE_BOOL, bytes); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): boolean { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_BOOL); - return bytes[0] != 0; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Bool -export class ScMutableBoolArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getBool(index: i32): ScMutableBool { - return new ScMutableBool(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableBoolArray { - return new ScImmutableBoolArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable bytes array in host container -export class ScMutableBytes { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_BYTES); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_BYTES); - } - - // set value in host container - setValue(val: u8[]): void { - host.setBytes(this.objID, this.keyID, host.TYPE_BYTES, val); - } - - // human-readable string representation - toString(): string { - return base58Encode(this.value()); - } - - // retrieve value from host container - value(): u8[] { - return host.getBytes(this.objID, this.keyID, host.TYPE_BYTES); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of byte array -export class ScMutableBytesArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getBytes(index: i32): ScMutableBytes { - return new ScMutableBytes(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableBytesArray { - return new ScImmutableBytesArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScChainID in host container -export class ScMutableChainID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_CHAIN_ID); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_CHAIN_ID); - } - - // set value in host container - setValue(val: ScChainID): void { - host.setBytes(this.objID, this.keyID, host.TYPE_CHAIN_ID, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScChainID { - return ScChainID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_CHAIN_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScChainID -export class ScMutableChainIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getChainID(index: i32): ScMutableChainID { - return new ScMutableChainID(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableChainIDArray { - return new ScImmutableChainIDArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScColor in host container -export class ScMutableColor { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_COLOR); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_COLOR); - } - - // set value in host container - setValue(val: ScColor): void { - host.setBytes(this.objID, this.keyID, host.TYPE_COLOR, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScColor { - return ScColor.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_COLOR)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScColor -export class ScMutableColorArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getColor(index: i32): ScMutableColor { - return new ScMutableColor(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableColorArray { - return new ScImmutableColorArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScHash in host container -export class ScMutableHash { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_HASH); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_HASH); - } - - // set value in host container - setValue(val: ScHash): void { - host.setBytes(this.objID, this.keyID, host.TYPE_HASH, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScHash { - return ScHash.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HASH)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScHash -export class ScMutableHashArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getHash(index: i32): ScMutableHash { - return new ScMutableHash(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableHashArray { - return new ScImmutableHashArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScHname in host container -export class ScMutableHname { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_HNAME); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_HNAME); - } - - // set value in host container - setValue(val: ScHname): void { - host.setBytes(this.objID, this.keyID, host.TYPE_HNAME, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScHname { - return ScHname.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HNAME)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScHname -export class ScMutableHnameArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getHname(index: i32): ScMutableHname { - return new ScMutableHname(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableHnameArray { - return new ScImmutableHnameArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int8 in host container -export class ScMutableInt8 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT8); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT8); - } - - // set value in host container - setValue(val: i8): void { - let bytes: u8[] = [val as u8]; - host.setBytes(this.objID, this.keyID, host.TYPE_INT8, bytes); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): i8 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); - return bytes[0] as i8; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int8 -export class ScMutableInt8Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getInt8(index: i32): ScMutableInt8 { - return new ScMutableInt8(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableInt8Array { - return new ScImmutableInt8Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int16 in host container -export class ScMutableInt16 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT16); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT16); - } - - // set value in host container - setValue(val: i16): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT16, Convert.fromI16(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): i16 { - return Convert.toI16(host.getBytes(this.objID, this.keyID, host.TYPE_INT16)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int16 -export class ScMutableInt16Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getInt16(index: i32): ScMutableInt16 { - return new ScMutableInt16(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableInt16Array { - return new ScImmutableInt16Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int32 in host container -export class ScMutableInt32 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT32); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT32); - } - - // set value in host container - setValue(val: i32): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT32, Convert.fromI32(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): i32 { - return Convert.toI32(host.getBytes(this.objID, this.keyID, host.TYPE_INT32)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int32 -export class ScMutableInt32Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getInt32(index: i32): ScMutableInt32 { - return new ScMutableInt32(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableInt32Array { - return new ScImmutableInt32Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Int64 in host container -export class ScMutableInt64 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT64); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT64); - } - - // set value in host container - setValue(val: i64): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT64, Convert.fromI64(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): i64 { - return Convert.toI64(host.getBytes(this.objID, this.keyID, host.TYPE_INT64)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Int64 -export class ScMutableInt64Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getInt64(index: i32): ScMutableInt64 { - return new ScMutableInt64(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableInt64Array { - return new ScImmutableInt64Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// map proxy for mutable map -export class ScMutableMap { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // construct a new map on the host and return a map proxy for it - static create(): ScMutableMap { - let maps = ROOT.getMapArray(KEY_MAPS); - return maps.getMap(maps.length()); - } - - callFunc(keyID: Key32, params: u8[]): u8[] { - return host.callFunc(this.objID, keyID, params); - } - - // empty the map - clear(): void { - host.clear(this.objID); - } - - // get value proxy for mutable ScAddress field specified by key - getAddress(key: MapKey): ScMutableAddress { - return new ScMutableAddress(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableAddressArray specified by key - getAddressArray(key: MapKey): ScMutableAddressArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_ADDRESS | host.TYPE_ARRAY); - return new ScMutableAddressArray(arrID); - } - - // get value proxy for mutable ScAgentID field specified by key - getAgentID(key: MapKey): ScMutableAgentID { - return new ScMutableAgentID(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableAgentIDArray specified by key - getAgentIDArray(key: MapKey): ScMutableAgentIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_AGENT_ID | host.TYPE_ARRAY); - return new ScMutableAgentIDArray(arrID); - } - - // get value proxy for mutable Bool field specified by key - getBool(key: MapKey): ScMutableBool { - return new ScMutableBool(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableBoolArray specified by key - getBoolArray(key: MapKey): ScMutableBoolArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BOOL | host.TYPE_ARRAY); - return new ScMutableBoolArray(arrID); - } - - // get value proxy for mutable Bytes array field specified by key - getBytes(key: MapKey): ScMutableBytes { - return new ScMutableBytes(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableBytesArray specified by key - getBytesArray(key: MapKey): ScMutableBytesArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BYTES | host.TYPE_ARRAY); - return new ScMutableBytesArray(arrID); - } - - // get value proxy for mutable ScChainID field specified by key - getChainID(key: MapKey): ScMutableChainID { - return new ScMutableChainID(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableChainIDArray specified by key - getChainIDArray(key: MapKey): ScMutableChainIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_CHAIN_ID | host.TYPE_ARRAY); - return new ScMutableChainIDArray(arrID); - } - - // get value proxy for mutable ScColor field specified by key - getColor(key: MapKey): ScMutableColor { - return new ScMutableColor(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableColorArray specified by key - getColorArray(key: MapKey): ScMutableColorArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_COLOR | host.TYPE_ARRAY); - return new ScMutableColorArray(arrID); - } - - // get value proxy for mutable ScHash field specified by key - getHash(key: MapKey): ScMutableHash { - return new ScMutableHash(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableHashArray specified by key - getHashArray(key: MapKey): ScMutableHashArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HASH | host.TYPE_ARRAY); - return new ScMutableHashArray(arrID); - } - - // get value proxy for mutable ScHname field specified by key - getHname(key: MapKey): ScMutableHname { - return new ScMutableHname(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableHnameArray specified by key - getHnameArray(key: MapKey): ScMutableHnameArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HNAME | host.TYPE_ARRAY); - return new ScMutableHnameArray(arrID); - } - - // get value proxy for mutable Int8 field specified by key - getInt8(key: MapKey): ScMutableInt8 { - return new ScMutableInt8(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableInt8Array specified by key - getInt8Array(key: MapKey): ScMutableInt8Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); - return new ScMutableInt8Array(arrID); - } - - // get value proxy for mutable Int16 field specified by key - getInt16(key: MapKey): ScMutableInt16 { - return new ScMutableInt16(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableInt16Array specified by key - getInt16Array(key: MapKey): ScMutableInt16Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); - return new ScMutableInt16Array(arrID); - } - - // get value proxy for mutable Int32 field specified by key - getInt32(key: MapKey): ScMutableInt32 { - return new ScMutableInt32(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableInt32Array specified by key - getInt32Array(key: MapKey): ScMutableInt32Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); - return new ScMutableInt32Array(arrID); - } - - // get value proxy for mutable Int64 field specified by key - getInt64(key: MapKey): ScMutableInt64 { - return new ScMutableInt64(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableInt64Array specified by key - getInt64Array(key: MapKey): ScMutableInt64Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); - return new ScMutableInt64Array(arrID); - } - - // get map proxy for ScMutableMap specified by key - getMap(key: MapKey): ScMutableMap { - let mapID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP); - return new ScMutableMap(mapID); - } - - // get array proxy for ScMutableMapArray specified by key - getMapArray(key: MapKey): ScMutableMapArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP | host.TYPE_ARRAY); - return new ScMutableMapArray(arrID); - } - - // get value proxy for mutable ScRequestID field specified by key - getRequestID(key: MapKey): ScMutableRequestID { - return new ScMutableRequestID(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableRequestIDArray specified by key - getRequestIDArray(key: MapKey): ScMutableRequestIDArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_REQUEST_ID | host.TYPE_ARRAY); - return new ScMutableRequestIDArray(arrID); - } - - // get value proxy for mutable UTF-8 text string field specified by key - getString(key: MapKey): ScMutableString { - return new ScMutableString(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableStringArray specified by key - getStringArray(key: MapKey): ScMutableStringArray { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_STRING | host.TYPE_ARRAY); - return new ScMutableStringArray(arrID); - } - - // get value proxy for mutable Uint8 field specified by key - getUint8(key: MapKey): ScMutableUint8 { - return new ScMutableUint8(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableUint8Array specified by key - getUint8Array(key: MapKey): ScMutableUint8Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); - return new ScMutableUint8Array(arrID); - } - - // get value proxy for mutable Uint16 field specified by key - getUint16(key: MapKey): ScMutableUint16 { - return new ScMutableUint16(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableUint16Array specified by key - getUint16Array(key: MapKey): ScMutableUint16Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); - return new ScMutableUint16Array(arrID); - } - - // get value proxy for mutable Uint32 field specified by key - getUint32(key: MapKey): ScMutableUint32 { - return new ScMutableUint32(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableUint32Array specified by key - getUint32Array(key: MapKey): ScMutableUint32Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); - return new ScMutableUint32Array(arrID); - } - - // get value proxy for mutable Uint64 field specified by key - getUint64(key: MapKey): ScMutableUint64 { - return new ScMutableUint64(this.objID, key.getKeyID()); - } - - // get array proxy for ScMutableUint64Array specified by key - getUint64Array(key: MapKey): ScMutableUint64Array { - let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); - return new ScMutableUint64Array(arrID); - } - - // get immutable version of map proxy - immutable(): ScImmutableMap { - return new ScImmutableMap(this.objID); - } - - mapID(): i32 { - return this.objID; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of maps -export class ScMutableMapArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getMap(index: i32): ScMutableMap { - let mapID = host.getObjectID(this.objID, new Key32(index), host.TYPE_MAP); - return new ScMutableMap(mapID); - } - - // get immutable version of array proxy - immutable(): ScImmutableMapArray { - return new ScImmutableMapArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable ScRequestID in host container -export class ScMutableRequestID { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_REQUEST_ID); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_REQUEST_ID); - } - - // set value in host container - setValue(val: ScRequestID): void { - host.setBytes(this.objID, this.keyID, host.TYPE_REQUEST_ID, val.toBytes()); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): ScRequestID { - return ScRequestID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_REQUEST_ID)); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of ScRequestID -export class ScMutableRequestIDArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getRequestID(index: i32): ScMutableRequestID { - return new ScMutableRequestID(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableRequestIDArray { - return new ScImmutableRequestIDArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable UTF-8 text string in host container -export class ScMutableString { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_STRING); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_STRING); - } - - // set value in host container - setValue(val: string): void { - host.setBytes(this.objID, this.keyID, host.TYPE_STRING, Convert.fromString(val)); - } - - // human-readable string representation - toString(): string { - return this.value(); - } - - // retrieve value from host container - value(): string { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_STRING); - return Convert.toString(bytes); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of UTF-8 text string -export class ScMutableStringArray { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getString(index: i32): ScMutableString { - return new ScMutableString(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableStringArray { - return new ScImmutableStringArray(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint8 in host container -export class ScMutableUint8 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT8); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT8); - } - - // set value in host container - setValue(val: u8): void { - let bytes: u8[] = [val as u8]; - host.setBytes(this.objID, this.keyID, host.TYPE_INT8, bytes); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): u8 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); - return bytes[0] as u8; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint8 -export class ScMutableUint8Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getUint8(index: i32): ScMutableUint8 { - return new ScMutableUint8(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableUint8Array { - return new ScImmutableUint8Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint16 in host container -export class ScMutableUint16 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT16); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT16); - } - - // set value in host container - setValue(val: u16): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT16, Convert.fromI16(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): u16 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT16); - return Convert.toI16(bytes) as u16; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint16 -export class ScMutableUint16Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getUint16(index: i32): ScMutableUint16 { - return new ScMutableUint16(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableUint16Array { - return new ScImmutableUint16Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint32 in host container -export class ScMutableUint32 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT32); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT32); - } - - // set value in host container - setValue(val: u32): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT32, Convert.fromI32(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): u32 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT32); - return Convert.toI32(bytes) as u32; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint32 -export class ScMutableUint32Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getUint32(index: i32): ScMutableUint32 { - return new ScMutableUint32(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableUint32Array { - return new ScImmutableUint32Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// value proxy for mutable Uint64 in host container -export class ScMutableUint64 { - objID: i32; - keyID: Key32; - - constructor(objID: i32, keyID: Key32) { - this.objID = objID; - this.keyID = keyID; - } - - // delete value from host container - delete(): void { - host.delKey(this.objID, this.keyID, host.TYPE_INT64); - } - - // check if value exists in host container - exists(): boolean { - return host.exists(this.objID, this.keyID, host.TYPE_INT64); - } - - // set value in host container - setValue(val: u64): void { - host.setBytes(this.objID, this.keyID, host.TYPE_INT64, Convert.fromI64(val)); - } - - // human-readable string representation - toString(): string { - return this.value().toString(); - } - - // retrieve value from host container - value(): u64 { - let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT64); - return Convert.toI64(bytes) as u64; - } -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -// array proxy for mutable array of Uint64 -export class ScMutableUint64Array { - objID: i32; - - constructor(id: i32) { - this.objID = id; - } - - // empty the array - clear(): void { - host.clear(this.objID); - } - - // get value proxy for item at index, index can be 0..length() - // when index equals length() a new item is appended - getUint64(index: i32): ScMutableUint64 { - return new ScMutableUint64(this.objID, new Key32(index)); - } - - // get immutable version of array proxy - immutable(): ScImmutableUint64Array { - return new ScImmutableUint64Array(this.objID); - } - - // number of items in array - length(): i32 { - return host.getLength(this.objID); - } -} diff --git a/packages/vm/wasmlib/ts/wasmlib/package-lock.json b/packages/vm/wasmlib/ts/wasmlib/package-lock.json deleted file mode 100644 index b0e4152706..0000000000 --- a/packages/vm/wasmlib/ts/wasmlib/package-lock.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "wasmlib", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@assemblyscript/loader": { - "version": "0.19.22", - "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.19.22.tgz", - "integrity": "sha512-ksrMVpPOatD7ZzXCw+c/g3zId5rm8MMnQe7P32dH/qtDrgT9SbQjJYEngRP0YhRF0qrBCga2PtpID7arqphGyg==" - }, - "assemblyscript": { - "version": "0.19.22", - "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.22.tgz", - "integrity": "sha512-+Rclbx0+BI3qAe9fjc8XGbSUDaayTtjINnD19I4MmfpT2R43c9YTQERP36676shkPxb1fisDFZeSTL65Da8Q2g==", - "dev": true, - "requires": { - "binaryen": "102.0.0-nightly.20211028", - "long": "^5.2.0", - "source-map-support": "^0.5.20" - } - }, - "binaryen": { - "version": "102.0.0-nightly.20211028", - "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz", - "integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==", - "dev": true - }, - "buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true - }, - "long": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/long/-/long-5.2.0.tgz", - "integrity": "sha512-9RTUNjK60eJbx3uz+TEGF7fUr29ZDxR5QzXcyDpeSfeH28S9ycINflOgOlppit5U+4kNTe83KQnMEerw7GmE8w==", - "dev": true - }, - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - }, - "source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - } - } -} diff --git a/packages/vm/wasmproc/bytes.go b/packages/vm/wasmproc/bytes.go deleted file mode 100644 index e05b2a6488..0000000000 --- a/packages/vm/wasmproc/bytes.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -type BytesDecoder struct { - data []byte -} - -func NewBytesDecoder(data []byte) *BytesDecoder { - return &BytesDecoder{data: data} -} - -func (d *BytesDecoder) Bool() bool { - return d.Int8() != 0 -} - -func (d *BytesDecoder) Bytes() []byte { - size := int(d.Int32()) - if len(d.data) < size { - panic("insufficient bytes") - } - value := d.data[:size] - d.data = d.data[size:] - return value -} - -func (d *BytesDecoder) Int8() int8 { - if len(d.data) == 0 { - panic("insufficient bytes") - } - value := d.data[0] - d.data = d.data[1:] - return int8(value) -} - -func (d *BytesDecoder) Int16() int16 { - return int16(d.leb128Decode(16)) -} - -func (d *BytesDecoder) Int32() int32 { - return int32(d.leb128Decode(32)) -} - -func (d *BytesDecoder) Int64() int64 { - return d.leb128Decode(64) -} - -// leb128 decoder -func (d *BytesDecoder) leb128Decode(bits int) int64 { - val := int64(0) - s := 0 - for { - if len(d.data) == 0 { - panic("insufficient bytes") - } - b := int8(d.data[0]) - d.data = d.data[1:] - val |= int64(b&0x7f) << s - if (b & -0x80) == 0 { - if int8(val>>s)&0x7f != b&0x7f { - panic("integer too large") - } - - // extend int7 sign to int8 - b |= (b & 0x40) << 1 - - // extend int8 sign to int64 - return val | (int64(b) << s) - } - s += 7 - if s >= bits { - panic("integer representation too long") - } - } -} - -func (d *BytesDecoder) Uint8() uint8 { - return uint8(d.Int8()) -} - -func (d *BytesDecoder) Uint16() uint16 { - return uint16(d.Int16()) -} - -func (d *BytesDecoder) Uint32() uint32 { - return uint32(d.Int32()) -} - -func (d *BytesDecoder) Uint64() uint64 { - return uint64(d.Int64()) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type BytesEncoder struct { - data []byte -} - -func NewBytesEncoder() *BytesEncoder { - return &BytesEncoder{data: make([]byte, 0, 128)} -} - -func (e *BytesEncoder) Bool(value bool) *BytesEncoder { - if value { - return e.Int8(1) - } - return e.Int8(0) -} - -func (e *BytesEncoder) Bytes(value []byte) *BytesEncoder { - e.Int32(int32(len(value))) - e.data = append(e.data, value...) - return e -} - -func (e *BytesEncoder) Data() []byte { - return e.data -} - -func (e *BytesEncoder) Int8(value int8) *BytesEncoder { - e.data = append(e.data, byte(value)) - return e -} - -func (e *BytesEncoder) Int16(value int16) *BytesEncoder { - return e.leb128Encode(int64(value)) -} - -func (e *BytesEncoder) Int32(value int32) *BytesEncoder { - return e.leb128Encode(int64(value)) -} - -func (e *BytesEncoder) Int64(value int64) *BytesEncoder { - return e.leb128Encode(value) -} - -// leb128 encoder -func (e *BytesEncoder) leb128Encode(value int64) *BytesEncoder { - for { - b := byte(value) - s := b & 0x40 - value >>= 7 - if (value == 0 && s == 0) || (value == -1 && s != 0) { - e.data = append(e.data, b&0x7f) - return e - } - e.data = append(e.data, b|0x80) - } -} - -func (e *BytesEncoder) Uint8(value uint8) *BytesEncoder { - return e.Int8(int8(value)) -} - -func (e *BytesEncoder) Uint16(value uint16) *BytesEncoder { - return e.Int16(int16(value)) -} - -func (e *BytesEncoder) Uint32(value uint32) *BytesEncoder { - return e.Int32(int32(value)) -} - -func (e *BytesEncoder) Uint64(value uint64) *BytesEncoder { - return e.Int64(int64(value)) -} diff --git a/packages/vm/wasmproc/scbalances.go b/packages/vm/wasmproc/scbalances.go deleted file mode 100644 index ee02afb615..0000000000 --- a/packages/vm/wasmproc/scbalances.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "strconv" - - "github.com/iotaledger/wasp/packages/iscp/colored" - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/kv/dict" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -func NewScBalances(wc *WasmContext, keyID int32) *ScDict { - o := NewScDict(&wc.KvStoreHost, dict.New()) - switch keyID { - case wasmhost.KeyIncoming: - if wc.ctx == nil { - o.Panicf("no incoming() on views") - } - return loadBalances(o, wc.ctx.IncomingTransfer()) - case wasmhost.KeyMinted: - if wc.ctx == nil { - o.Panicf("no minted() on views") - } - return loadBalances(o, wc.ctx.Minted()) - - case wasmhost.KeyBalances: - if wc.ctx != nil { - return loadBalances(o, wc.ctx.Balances()) - } - return loadBalances(o, wc.ctxView.Balances()) - } - o.Panicf("unknown balances: %s", wc.GetKeyStringFromID(keyID)) - return nil -} - -func loadBalances(o *ScDict, balances colored.Balances) *ScDict { - index := 0 - key := o.host.GetKeyStringFromID(wasmhost.KeyColor) - balances.ForEachRandomly(func(color colored.Color, balance uint64) bool { - o.kvStore.Set(kv.Key(color[:]), codec.EncodeUint64(balance)) - o.kvStore.Set(kv.Key(key+"."+strconv.Itoa(index)), color[:]) - index++ - return true - }) - // save KeyLength - o.kvStore.Set(kv.Key(key), codec.EncodeInt32(int32(index))) - return o -} diff --git a/packages/vm/wasmproc/sccontext.go b/packages/vm/wasmproc/sccontext.go deleted file mode 100644 index c0556303aa..0000000000 --- a/packages/vm/wasmproc/sccontext.go +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "time" - - "github.com/iotaledger/wasp/packages/iscp/colored" - - "github.com/iotaledger/wasp/packages/hashing" - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/kv/dict" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -var typeIds = map[int32]int32{ - wasmhost.KeyAccountID: wasmhost.OBJTYPE_AGENT_ID, - wasmhost.KeyBalances: wasmhost.OBJTYPE_MAP, - wasmhost.KeyCall: wasmhost.OBJTYPE_BYTES, - wasmhost.KeyCaller: wasmhost.OBJTYPE_AGENT_ID, - wasmhost.KeyChainID: wasmhost.OBJTYPE_CHAIN_ID, - wasmhost.KeyChainOwnerID: wasmhost.OBJTYPE_AGENT_ID, - wasmhost.KeyContract: wasmhost.OBJTYPE_HNAME, - wasmhost.KeyContractCreator: wasmhost.OBJTYPE_AGENT_ID, - wasmhost.KeyDeploy: wasmhost.OBJTYPE_BYTES, - wasmhost.KeyEvent: wasmhost.OBJTYPE_STRING, - wasmhost.KeyExports: wasmhost.OBJTYPE_STRING | wasmhost.OBJTYPE_ARRAY, - wasmhost.KeyIncoming: wasmhost.OBJTYPE_MAP, - wasmhost.KeyLog: wasmhost.OBJTYPE_STRING, - wasmhost.KeyMaps: wasmhost.OBJTYPE_MAP | wasmhost.OBJTYPE_ARRAY, - wasmhost.KeyMinted: wasmhost.OBJTYPE_MAP, - wasmhost.KeyPanic: wasmhost.OBJTYPE_STRING, - wasmhost.KeyParams: wasmhost.OBJTYPE_MAP, - wasmhost.KeyPost: wasmhost.OBJTYPE_BYTES, - wasmhost.KeyRandom: wasmhost.OBJTYPE_BYTES, - wasmhost.KeyRequestID: wasmhost.OBJTYPE_REQUEST_ID, - wasmhost.KeyResults: wasmhost.OBJTYPE_MAP, - wasmhost.KeyReturn: wasmhost.OBJTYPE_MAP, - wasmhost.KeyState: wasmhost.OBJTYPE_MAP, - wasmhost.KeyTimestamp: wasmhost.OBJTYPE_INT64, - wasmhost.KeyTrace: wasmhost.OBJTYPE_STRING, - wasmhost.KeyTransfers: wasmhost.OBJTYPE_MAP | wasmhost.OBJTYPE_ARRAY, - wasmhost.KeyUtility: wasmhost.OBJTYPE_MAP, -} - -type ScContext struct { - ScSandboxObject - wc *WasmContext -} - -func NewScContext(wc *WasmContext, host *wasmhost.KvStoreHost) *ScContext { - o := &ScContext{} - o.wc = wc - o.host = host - o.name = "root" - o.id = 1 - o.isRoot = true - o.objects = make(map[int32]int32) - return o -} - -func (o *ScContext) Exists(keyID, typeID int32) bool { - if keyID == wasmhost.KeyExports { - return o.wc.ctx == nil && o.wc.ctxView == nil - } - return o.GetTypeID(keyID) > 0 -} - -func (o *ScContext) GetBytes(keyID, typeID int32) []byte { - if o.wc == nil { - o.Panicf("missing context") - } - ctx := o.wc.ctx - if ctx == nil { - return o.getBytesForView(keyID, typeID) - } - switch keyID { - case wasmhost.KeyAccountID: - return ctx.AccountID().Bytes() - case wasmhost.KeyCaller: - return ctx.Caller().Bytes() - case wasmhost.KeyChainID: - return ctx.ChainID().Bytes() - case wasmhost.KeyChainOwnerID: - return ctx.ChainOwnerID().Bytes() - case wasmhost.KeyContract: - return ctx.Contract().Bytes() - case wasmhost.KeyContractCreator: - return ctx.ContractCreator().Bytes() - case wasmhost.KeyRandom: - return ctx.GetEntropy().Bytes() - case wasmhost.KeyRequestID: - return ctx.Request().ID().Bytes() - case wasmhost.KeyTimestamp: - return codec.EncodeInt64(ctx.GetTimestamp()) - } - o.InvalidKey(keyID) - return nil -} - -//nolint:unparam -func (o *ScContext) getBytesForView(keyID, typeID int32) []byte { - ctx := o.wc.ctxView - if ctx == nil { - o.Panicf("missing context") - } - switch keyID { - case wasmhost.KeyAccountID: - return ctx.AccountID().Bytes() - case wasmhost.KeyChainID: - return ctx.ChainID().Bytes() - case wasmhost.KeyChainOwnerID: - return ctx.ChainOwnerID().Bytes() - case wasmhost.KeyContract: - return ctx.Contract().Bytes() - case wasmhost.KeyContractCreator: - return ctx.ContractCreator().Bytes() - case wasmhost.KeyTimestamp: - return codec.EncodeInt64(ctx.GetTimestamp()) - } - o.InvalidKey(keyID) - return nil -} - -func (o *ScContext) GetObjectID(keyID, typeID int32) int32 { - if keyID == wasmhost.KeyExports && (o.wc.ctx != nil || o.wc.ctxView != nil) { - // once map has entries (after on_load) this cannot be called any longer - o.InvalidKey(keyID) - return 0 - } - - return GetMapObjectID(o, keyID, typeID, ObjFactories{ - wasmhost.KeyBalances: func() WaspObject { return NewScBalances(o.wc, keyID) }, - wasmhost.KeyExports: func() WaspObject { return NewScExports(o.wc) }, - wasmhost.KeyIncoming: func() WaspObject { return NewScBalances(o.wc, keyID) }, - wasmhost.KeyMaps: func() WaspObject { return NewScMaps(o.host) }, - wasmhost.KeyMinted: func() WaspObject { return NewScBalances(o.wc, keyID) }, - wasmhost.KeyParams: func() WaspObject { return NewScDict(o.host, o.wc.params()) }, - wasmhost.KeyResults: func() WaspObject { return NewScDict(o.host, dict.New()) }, - wasmhost.KeyReturn: func() WaspObject { return NewScDict(o.host, dict.New()) }, - wasmhost.KeyState: func() WaspObject { return NewScDict(o.host, o.wc.state()) }, - wasmhost.KeyTransfers: func() WaspObject { return NewScTransfers(o.wc) }, - wasmhost.KeyUtility: func() WaspObject { return NewScUtility(o.wc, nil) }, - }) -} - -func (o *ScContext) GetTypeID(keyID int32) int32 { - return typeIds[keyID] -} - -func (o *ScContext) SetBytes(keyID, typeID int32, bytes []byte) { - switch keyID { - case wasmhost.KeyCall: - o.processCall(bytes) - case wasmhost.KeyDeploy: - o.processDeploy(bytes) - case wasmhost.KeyEvent: - o.wc.ctx.Event(string(bytes)) - case wasmhost.KeyLog: - o.wc.log().Infof(string(bytes)) - case wasmhost.KeyTrace: - o.wc.log().Debugf(string(bytes)) - case wasmhost.KeyPanic: - o.wc.log().Panicf(string(bytes)) - case wasmhost.KeyPost: - o.processPost(bytes) - default: - o.InvalidKey(keyID) - } -} - -func (o *ScContext) processCall(bytes []byte) { - decode := NewBytesDecoder(bytes) - contract, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - function, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - params := o.getParams(decode.Int32()) - transfer := o.getTransfer(decode.Int32()) - - o.Tracef("CALL c'%s' f'%s'", contract.String(), function.String()) - results, err := o.processCallUnlocked(contract, function, params, transfer) - if err != nil { - o.Panicf("failed to invoke call: %v", err) - } - resultsID := o.GetObjectID(wasmhost.KeyReturn, wasmhost.OBJTYPE_MAP) - o.host.FindObject(resultsID).(*ScDict).kvStore = results -} - -func (o *ScContext) processCallUnlocked(contract, function iscp.Hname, params dict.Dict, transfer colored.Balances) (dict.Dict, error) { - o.wc.proc.instanceLock.Unlock() - defer o.wc.proc.instanceLock.Lock() - - if o.wc.ctx != nil { - return o.wc.ctx.Call(contract, function, params, transfer) - } - return o.wc.ctxView.Call(contract, function, params) -} - -func (o *ScContext) processDeploy(bytes []byte) { - decode := NewBytesDecoder(bytes) - programHash, err := hashing.HashValueFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - name := string(decode.Bytes()) - description := string(decode.Bytes()) - params := o.getParams(decode.Int32()) - o.Tracef("DEPLOY c'%s' f'%s'", name, description) - err = o.processDeployUnlocked(programHash, name, description, params) - if err != nil { - o.Panicf("failed to deploy: %v", err) - } -} - -func (o *ScContext) processDeployUnlocked(programHash hashing.HashValue, name, description string, params dict.Dict) error { - o.wc.proc.instanceLock.Unlock() - defer o.wc.proc.instanceLock.Lock() - - return o.wc.ctx.DeployContract(programHash, name, description, params) -} - -func (o *ScContext) processPost(bytes []byte) { - decode := NewBytesDecoder(bytes) - chainID, err := iscp.ChainIDFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - contract, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - function, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - o.Tracef("POST c'%s' f'%s'", contract.String(), function.String()) - params := o.getParams(decode.Int32()) - transferID := decode.Int32() - if transferID == 0 { - o.Panicf("transfer is required for post") - } - transfer := o.getTransfer(transferID) - metadata := &iscp.SendMetadata{ - TargetContract: contract, - EntryPoint: function, - Args: params, - } - delay := decode.Int32() - if delay == 0 { - if !o.wc.ctx.Send(chainID.AsAddress(), transfer, metadata) { - o.Panicf("failed to send to %s", chainID.AsAddress().String()) - } - return - } - - if delay < 0 { - o.Panicf("invalid delay: %d", delay) - } - - timeLock := time.Unix(0, o.wc.ctx.GetTimestamp()) - timeLock = timeLock.Add(time.Duration(delay) * time.Second) - options := iscp.SendOptions{ - TimeLock: uint32(timeLock.Unix()), - } - if !o.wc.ctx.Send(chainID.AsAddress(), transfer, metadata, options) { - o.Panicf("failed to send to %s", chainID.AsAddress().String()) - } -} - -func (o *ScContext) getParams(paramsID int32) dict.Dict { - if paramsID == 0 { - return dict.New() - } - params := o.host.FindObject(paramsID).(*ScDict).kvStore.(dict.Dict) - params.MustIterate("", func(key kv.Key, value []byte) bool { - o.Tracef(" PARAM '%s'", key) - return true - }) - return params -} - -func (o *ScContext) getTransfer(transferID int32) colored.Balances { - if transferID == 0 { - return colored.NewBalances() - } - transfer := colored.NewBalances() - transferDict := o.host.FindObject(transferID).(*ScDict).kvStore - transferDict.MustIterate("", func(key kv.Key, value []byte) bool { - col, err := codec.DecodeColor([]byte(key)) - if err != nil { - o.Panicf(err.Error()) - } - amount, err := codec.DecodeUint64(value) - if err != nil { - o.Panicf(err.Error()) - } - o.Tracef(" XFER %d '%s'", amount, col.String()) - transfer.Set(col, amount) - return true - }) - return transfer -} diff --git a/packages/vm/wasmproc/scdict.go b/packages/vm/wasmproc/scdict.go deleted file mode 100644 index 1ddd454dd1..0000000000 --- a/packages/vm/wasmproc/scdict.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "encoding/binary" - "fmt" - "strings" - - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -type ( - ObjFactory func() WaspObject - ObjFactories map[int32]ObjFactory -) - -type WaspObject interface { - wasmhost.HostObject - InitObj(id int32, keyID int32, owner *ScDict) - Panicf(format string, args ...interface{}) - FindOrMakeObjectID(keyID int32, factory ObjFactory) int32 - NestedKey() string - Suffix(keyID int32) string -} - -func GetArrayObjectID(arrayObj WaspObject, index, typeID int32, factory ObjFactory) int32 { - if !arrayObj.Exists(index, typeID) { - arrayObj.Panicf("GetArrayObjectID: invalid index") - } - if typeID != arrayObj.GetTypeID(index) { - arrayObj.Panicf("GetArrayObjectID: invalid type") - } - return arrayObj.FindOrMakeObjectID(index, factory) -} - -func GetMapObjectID(mapObj WaspObject, keyID, typeID int32, factories ObjFactories) int32 { - factory, ok := factories[keyID] - if !ok { - mapObj.Panicf("GetMapObjectID: invalid key") - } - if typeID != mapObj.GetTypeID(keyID) { - mapObj.Panicf("GetMapObjectID: invalid type") - } - return mapObj.FindOrMakeObjectID(keyID, factory) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScDict struct { - host *wasmhost.KvStoreHost - id int32 - isRoot bool - keyID int32 - kvStore kv.KVStore - length int32 - name string - objects map[int32]int32 - ownerID int32 - typeID int32 - types map[int32]int32 -} - -// TODO iterate over maps - -var _ WaspObject = &ScDict{} - -func NewScDict(host *wasmhost.KvStoreHost, kvStore kv.KVStore) *ScDict { - return &ScDict{host: host, kvStore: kvStore} -} - -func NewNullObject(host *wasmhost.KvStoreHost) WaspObject { - o := &ScSandboxObject{} - o.host = host - o.name = "null" - o.isRoot = true - return o -} - -func (o *ScDict) InitObj(id, keyID int32, owner *ScDict) { - o.id = id - o.keyID = keyID - o.ownerID = owner.id - o.host = owner.host - o.isRoot = o.kvStore != nil - if !o.isRoot { - o.kvStore = owner.kvStore - } - ownerObj := o.Owner() - o.typeID = ownerObj.GetTypeID(keyID) - o.name = owner.name + ownerObj.Suffix(keyID) - if o.ownerID == 1 { - // strip off "root." prefix - o.name = strings.TrimPrefix(o.name, "root.") - // strip off "." prefix - o.name = strings.TrimPrefix(o.name, ".") - } - if (o.typeID&wasmhost.OBJTYPE_ARRAY) != 0 && o.kvStore != nil { - err := o.getArrayLength() - if err != nil { - o.Panicf("InitObj: %v", err) - } - } - o.Tracef("InitObj %s", o.name) - o.objects = make(map[int32]int32) - o.types = make(map[int32]int32) -} - -func (o *ScDict) CallFunc(keyID int32, params []byte) []byte { - o.Panicf("CallFunc: invalid call") - return nil -} - -func (o *ScDict) DelKey(keyID, typeID int32) { - if (typeID & wasmhost.OBJTYPE_ARRAY) != 0 { - o.Panicf("DelKey: cannot delete array") - } - if typeID == wasmhost.OBJTYPE_MAP { - o.Panicf("DelKey: cannot delete map") - } - o.kvStore.Del(o.key(keyID, typeID)) -} - -func (o *ScDict) Exists(keyID, typeID int32) bool { - if keyID == wasmhost.KeyLength && (o.typeID&wasmhost.OBJTYPE_ARRAY) != 0 { - return true - } - if o.typeID == (wasmhost.OBJTYPE_ARRAY | wasmhost.OBJTYPE_MAP) { - return uint32(keyID) <= uint32(len(o.objects)) - } - ret, _ := o.kvStore.Has(o.key(keyID, typeID)) - return ret -} - -func (o *ScDict) FindOrMakeObjectID(keyID int32, factory ObjFactory) int32 { - objID, ok := o.objects[keyID] - if ok { - return objID - } - newObject := factory() - objID = o.host.TrackObject(newObject) - newObject.InitObj(objID, keyID, o) - o.objects[keyID] = objID - if (o.typeID & wasmhost.OBJTYPE_ARRAY) != 0 { - o.length++ - if o.kvStore != nil { - key := o.NestedKey()[1:] - o.kvStore.Set(kv.Key(key), codec.EncodeInt32(o.length)) - } - } - return objID -} - -func (o *ScDict) getArrayLength() (err error) { - key := o.NestedKey()[1:] - bytes := o.kvStore.MustGet(kv.Key(key)) - if (o.typeID & wasmhost.OBJTYPE_ARRAY16) != wasmhost.OBJTYPE_ARRAY16 { - o.length, err = codec.DecodeInt32(bytes, 0) - return err - } - - var length uint16 - length, err = codec.DecodeUint16(bytes, 0) - o.length = int32(length) - return err -} - -func (o *ScDict) GetBytes(keyID, typeID int32) []byte { - if keyID == wasmhost.KeyLength && (o.typeID&wasmhost.OBJTYPE_ARRAY) != 0 { - return codec.EncodeInt32(o.length) - } - bytes := o.kvStore.MustGet(o.key(keyID, typeID)) - o.host.TypeCheck(typeID, bytes) - return bytes -} - -func (o *ScDict) GetObjectID(keyID, typeID int32) int32 { - o.validate(keyID, typeID) - if (typeID&wasmhost.OBJTYPE_ARRAY) == 0 && typeID != wasmhost.OBJTYPE_MAP { - o.Panicf("GetObjectID: invalid type") - } - return GetMapObjectID(o, keyID, typeID, ObjFactories{ - keyID: func() WaspObject { return &ScDict{} }, - }) -} - -func (o *ScDict) GetTypeID(keyID int32) int32 { - if (o.typeID & wasmhost.OBJTYPE_ARRAY) != 0 { - return o.typeID & wasmhost.OBJTYPE_TYPEMASK - } - // TODO incomplete, currently only contains used field types - typeID, ok := o.types[keyID] - if ok { - return typeID - } - return 0 -} - -func (o *ScDict) InvalidKey(keyID int32) { - o.Panicf("invalid key: %d", keyID) -} - -func (o *ScDict) key(keyID, typeID int32) kv.Key { - o.validate(keyID, typeID) - suffix := o.Suffix(keyID) - key := o.NestedKey() + suffix - o.Tracef("fld: %s%s", o.name, suffix) - o.Tracef("key: %s", key[1:]) - return kv.Key(key[1:]) -} - -func (o *ScDict) KvStore() kv.KVStore { - return o.kvStore -} - -func (o *ScDict) NestedKey() string { - if o.isRoot { - return "" - } - ownerObj := o.Owner() - return ownerObj.NestedKey() + ownerObj.Suffix(o.keyID) -} - -func (o *ScDict) Owner() WaspObject { - return o.host.FindObject(o.ownerID).(WaspObject) -} - -func (o *ScDict) Panicf(format string, args ...interface{}) { - o.host.Panicf(o.name+"."+format, args...) -} - -func (o *ScDict) SetBytes(keyID, typeID int32, bytes []byte) { - if keyID == wasmhost.KeyLength { - if o.kvStore != nil { - // TODO this goes wrong for state, should clear map tree instead - // o.kvStore = dict.New() - if (o.typeID & wasmhost.OBJTYPE_ARRAY) != 0 { - key := o.NestedKey()[1:] - o.kvStore.Set(kv.Key(key), codec.EncodeInt32(0)) - } - } - o.objects = make(map[int32]int32) - o.length = 0 - return - } - - key := o.key(keyID, typeID) - o.host.TypeCheck(typeID, bytes) - o.kvStore.Set(key, bytes) -} - -func (o *ScDict) Suffix(keyID int32) string { - if (o.typeID & wasmhost.OBJTYPE_ARRAY16) != 0 { - if (o.typeID & wasmhost.OBJTYPE_ARRAY16) != wasmhost.OBJTYPE_ARRAY16 { - return fmt.Sprintf(".%d", keyID) - } - - buf := make([]byte, 3) - buf[0] = '#' - binary.LittleEndian.PutUint16(buf[1:], uint16(keyID)) - return string(buf) - } - - key := o.host.GetKeyFromID(keyID) - return "." + string(key) -} - -func (o *ScDict) Tracef(format string, a ...interface{}) { - o.host.Tracef(format, a...) -} - -func (o *ScDict) validate(keyID, typeID int32) { - if o.kvStore == nil { - o.Panicf("validate: Missing kvstore") - } - if typeID == -1 { - return - } - if (o.typeID & wasmhost.OBJTYPE_ARRAY) != 0 { - // actually array - arrayTypeID := o.typeID & wasmhost.OBJTYPE_TYPEMASK - if typeID == wasmhost.OBJTYPE_BYTES { - switch arrayTypeID { - case wasmhost.OBJTYPE_ADDRESS: - case wasmhost.OBJTYPE_AGENT_ID: - case wasmhost.OBJTYPE_BYTES: - case wasmhost.OBJTYPE_COLOR: - case wasmhost.OBJTYPE_HASH: - default: - o.Panicf("validate: Invalid byte type") - } - } else if arrayTypeID != typeID { - o.Panicf("validate: Invalid type") - } - if keyID == o.length { - switch o.kvStore.(type) { - case *ScViewState: - break - default: - o.length++ - key := o.NestedKey()[1:] - o.kvStore.Set(kv.Key(key), codec.EncodeInt32(o.length)) - return - } - } - if keyID < 0 || keyID >= o.length { - o.Panicf("validate: Invalid index") - } - return - } - fieldType, ok := o.types[keyID] - if !ok { - // first encounter of this key id, register type to make - // sure that future usages are all using that same type - o.types[keyID] = typeID - return - } - if fieldType != typeID { - o.Panicf("validate: Invalid access") - } -} - -func (o *ScDict) SetKvStore(res kv.KVStore) { - o.kvStore = res - o.objects = make(map[int32]int32) - o.types = make(map[int32]int32) -} diff --git a/packages/vm/wasmproc/scexports.go b/packages/vm/wasmproc/scexports.go deleted file mode 100644 index d078a337f2..0000000000 --- a/packages/vm/wasmproc/scexports.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -type ScExports struct { - ScSandboxObject - wc *WasmContext -} - -func NewScExports(wc *WasmContext) *ScExports { - return &ScExports{wc: wc} -} - -func (o *ScExports) SetBytes(keyID, typeID int32, bytes []byte) { - o.wc.host.SetExport(keyID, string(bytes)) -} diff --git a/packages/vm/wasmproc/scmaps.go b/packages/vm/wasmproc/scmaps.go deleted file mode 100644 index 58c9406b31..0000000000 --- a/packages/vm/wasmproc/scmaps.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "github.com/iotaledger/wasp/packages/kv/dict" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScMaps struct { - ScSandboxObject -} - -func NewScMaps(host *wasmhost.KvStoreHost) *ScMaps { - a := &ScMaps{} - a.host = host - return a -} - -func (a *ScMaps) GetObjectID(keyID, typeID int32) int32 { - return GetArrayObjectID(a, keyID, typeID, func() WaspObject { - return NewScDict(a.host, dict.New()) - }) -} diff --git a/packages/vm/wasmproc/scsandbox.go b/packages/vm/wasmproc/scsandbox.go deleted file mode 100644 index d0b7311e5a..0000000000 --- a/packages/vm/wasmproc/scsandbox.go +++ /dev/null @@ -1,30 +0,0 @@ -package wasmproc - -import ( - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -type ScSandboxObject struct { - ScDict -} - -func (o *ScSandboxObject) DelKey(keyID, typeID int32) { - o.Panicf("DelKey: cannot delete predefined key") -} - -func (o *ScSandboxObject) GetBytes(keyID, typeID int32) []byte { - if keyID == wasmhost.KeyLength && (o.typeID&wasmhost.OBJTYPE_ARRAY) != 0 { - return o.ScDict.GetBytes(keyID, typeID) - } - o.InvalidKey(keyID) - return nil -} - -func (o *ScSandboxObject) GetObjectID(keyID, typeID int32) int32 { - o.InvalidKey(keyID) - return 0 -} - -func (o *ScSandboxObject) SetBytes(keyID, typeID int32, bytes []byte) { - o.InvalidKey(keyID) -} diff --git a/packages/vm/wasmproc/sctransfer.go b/packages/vm/wasmproc/sctransfer.go deleted file mode 100644 index 30ff36e3c4..0000000000 --- a/packages/vm/wasmproc/sctransfer.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "github.com/iotaledger/goshimmer/packages/ledgerstate" - "github.com/iotaledger/wasp/packages/iscp/colored" - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScTransfers struct { - ScSandboxObject - wc *WasmContext -} - -func NewScTransfers(wc *WasmContext) *ScTransfers { - return &ScTransfers{wc: wc} -} - -func (a *ScTransfers) GetObjectID(keyID, typeID int32) int32 { - return GetArrayObjectID(a, keyID, typeID, func() WaspObject { - return NewScTransferInfo(a.wc) - }) -} - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type ScTransferInfo struct { - ScSandboxObject - address ledgerstate.Address - wc *WasmContext -} - -func NewScTransferInfo(wc *WasmContext) *ScTransferInfo { - return &ScTransferInfo{wc: wc} -} - -// TODO refactor -func (o *ScTransferInfo) Invoke(balances int32) { - transfer := colored.NewBalances() - balancesObj := o.host.FindObject(balances).(*ScDict) - balancesObj.kvStore.MustIterate("", func(key kv.Key, value []byte) bool { - if len(key) != ledgerstate.ColorLength { - return true - } - col, err := codec.DecodeColor([]byte(key)) - if err != nil { - o.Panicf(err.Error()) - } - amount, err := codec.DecodeUint64(value) - if err != nil { - o.Panicf(err.Error()) - } - o.Tracef("TRANSFER #%d c'%s' a'%s'", value, col.String(), o.address.Base58()) - transfer.Set(col, amount) - return true - }) - if !o.wc.ctx.Send(o.address, transfer, nil) { - o.Panicf("failed to send to %s", o.address.Base58()) - } -} - -func (o *ScTransferInfo) SetBytes(keyID, typeID int32, bytes []byte) { - switch keyID { - case wasmhost.KeyAddress: - var err error - o.address, _, err = ledgerstate.AddressFromBytes(bytes) - if err != nil { - o.Panicf("SetBytes: invalid address: " + err.Error()) - } - case wasmhost.KeyBalances: - balanceMapID, err := codec.DecodeInt32(bytes, 0) - if err != nil { - o.Panicf("SetBytes: invalid balance map id: " + err.Error()) - } - o.Invoke(balanceMapID) - default: - o.InvalidKey(keyID) - } -} diff --git a/packages/vm/wasmproc/scutility.go b/packages/vm/wasmproc/scutility.go deleted file mode 100644 index 2cf6c16d4a..0000000000 --- a/packages/vm/wasmproc/scutility.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmproc - -import ( - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/vm/sandbox/sandbox_utils" - "github.com/iotaledger/wasp/packages/vm/wasmhost" -) - -type ScUtility struct { - ScSandboxObject - utils iscp.Utils - wc *WasmContext -} - -func NewScUtility(wc *WasmContext, gasProcessor interface{}) *ScUtility { - //if gasProcessor == nil { - // if wc.ctx != nil { - // gasProcessor = wc.ctx.Gas() - // } else { - // gasProcessor = wc.ctxView.Gas() - // } - //} - //return &ScUtility{utils: sandbox.NewUtils(gasProcessor), wc: wc} - return &ScUtility{utils: sandbox_utils.NewUtils(), wc: wc} -} - -func (o *ScUtility) CallFunc(keyID int32, bytes []byte) []byte { - utils := o.utils - switch keyID { - case wasmhost.KeyBase58Decode: - base58Decoded, err := utils.Base58().Decode(string(bytes)) - if err != nil { - o.Panicf(err.Error()) - } - return base58Decoded - case wasmhost.KeyBase58Encode: - return []byte(utils.Base58().Encode(bytes)) - case wasmhost.KeyBlsAddress: - address, err := utils.BLS().AddressFromPublicKey(bytes) - if err != nil { - o.Panicf(err.Error()) - } - return address.Bytes() - case wasmhost.KeyBlsAggregate: - return o.aggregateBLSSignatures(bytes) - case wasmhost.KeyBlsValid: - if o.validBLSSignature(bytes) { - var flag [1]byte - return flag[:] - } - return nil - case wasmhost.KeyEd25519Address: - address, err := utils.ED25519().AddressFromPublicKey(bytes) - if err != nil { - o.Panicf(err.Error()) - } - return address.Bytes() - case wasmhost.KeyEd25519Valid: - if o.validED25519Signature(bytes) { - var flag [1]byte - return flag[:] - } - return nil - case wasmhost.KeyHashBlake2b: - return utils.Hashing().Blake2b(bytes).Bytes() - case wasmhost.KeyHashSha3: - return utils.Hashing().Sha3(bytes).Bytes() - case wasmhost.KeyHname: - return codec.EncodeHname(utils.Hashing().Hname(string(bytes))) - } - o.InvalidKey(keyID) - return nil -} - -func (o *ScUtility) Exists(keyID, typeID int32) bool { - return o.GetTypeID(keyID) > 0 -} - -func (o *ScUtility) GetTypeID(keyID int32) int32 { - return wasmhost.OBJTYPE_BYTES -} - -func (o *ScUtility) aggregateBLSSignatures(bytes []byte) []byte { - decode := NewBytesDecoder(bytes) - count := int(decode.Int32()) - pubKeysBin := make([][]byte, count) - for i := 0; i < count; i++ { - pubKeysBin[i] = decode.Bytes() - } - count = int(decode.Int32()) - sigsBin := make([][]byte, count) - for i := 0; i < count; i++ { - sigsBin[i] = decode.Bytes() - } - pubKeyBin, sigBin, err := o.utils.BLS().AggregateBLSSignatures(pubKeysBin, sigsBin) - if err != nil { - o.Panicf(err.Error()) - } - return NewBytesEncoder().Bytes(pubKeyBin).Bytes(sigBin).Data() -} - -func (o *ScUtility) validBLSSignature(bytes []byte) bool { - decode := NewBytesDecoder(bytes) - data := decode.Bytes() - pubKey := decode.Bytes() - signature := decode.Bytes() - return o.utils.BLS().ValidSignature(data, pubKey, signature) -} - -func (o *ScUtility) validED25519Signature(bytes []byte) bool { - decode := NewBytesDecoder(bytes) - data := decode.Bytes() - pubKey := decode.Bytes() - signature := decode.Bytes() - return o.utils.ED25519().ValidSignature(data, pubKey, signature) -} diff --git a/packages/vm/wasmproc/scviewstate.go b/packages/vm/wasmproc/scviewstate.go deleted file mode 100644 index bd6c0f6abe..0000000000 --- a/packages/vm/wasmproc/scviewstate.go +++ /dev/null @@ -1,76 +0,0 @@ -package wasmproc - -import ( - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/kv" -) - -// ScViewState wraps immutable view state into a mutable KVStore -// with the KVWriter functions implemented as panics -// WaspLib already takes care of the immutability aspect, -// so these panics should never trigger, and we can avoid -// a much more drastic refactoring for now -type ScViewState struct { - ctxView iscp.SandboxView - viewState kv.KVStoreReader -} - -func NewScViewState(ctxView iscp.SandboxView) kv.KVStore { - return &ScViewState{ctxView: ctxView, viewState: ctxView.State()} -} - -func (s ScViewState) Set(key kv.Key, value []byte) { - s.ctxView.Log().Panicf("ScViewState.Set") -} - -func (s ScViewState) Del(key kv.Key) { - s.ctxView.Log().Panicf("ScViewState.Del") -} - -func (s ScViewState) Get(key kv.Key) ([]byte, error) { - return s.viewState.Get(key) -} - -func (s ScViewState) Has(key kv.Key) (bool, error) { - return s.viewState.Has(key) -} - -func (s ScViewState) Iterate(prefix kv.Key, f func(key kv.Key, value []byte) bool) error { - return s.viewState.Iterate(prefix, f) -} - -func (s ScViewState) IterateKeys(prefix kv.Key, f func(key kv.Key) bool) error { - return s.viewState.IterateKeys(prefix, f) -} - -func (s ScViewState) IterateSorted(prefix kv.Key, f func(key kv.Key, value []byte) bool) error { - return s.viewState.IterateSorted(prefix, f) -} - -func (s ScViewState) IterateKeysSorted(prefix kv.Key, f func(key kv.Key) bool) error { - return s.viewState.IterateKeysSorted(prefix, f) -} - -func (s ScViewState) MustGet(key kv.Key) []byte { - return s.viewState.MustGet(key) -} - -func (s ScViewState) MustHas(key kv.Key) bool { - return s.viewState.MustHas(key) -} - -func (s ScViewState) MustIterate(prefix kv.Key, f func(key kv.Key, value []byte) bool) { - s.viewState.MustIterate(prefix, f) -} - -func (s ScViewState) MustIterateKeys(prefix kv.Key, f func(key kv.Key) bool) { - s.viewState.MustIterateKeys(prefix, f) -} - -func (s ScViewState) MustIterateSorted(prefix kv.Key, f func(key kv.Key, value []byte) bool) { - s.viewState.MustIterateSorted(prefix, f) -} - -func (s ScViewState) MustIterateKeysSorted(prefix kv.Key, f func(key kv.Key) bool) { - s.viewState.MustIterateKeysSorted(prefix, f) -} diff --git a/packages/vm/wasmproc/wasmcontext.go b/packages/vm/wasmproc/wasmcontext.go deleted file mode 100644 index 20b416e657..0000000000 --- a/packages/vm/wasmproc/wasmcontext.go +++ /dev/null @@ -1,142 +0,0 @@ -package wasmproc - -import ( - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/dict" - "github.com/iotaledger/wasp/packages/vm/wasmhost" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" -) - -const ( - FuncDefault = "_default" -) - -type WasmContext struct { - wasmhost.KvStoreHost - ctx iscp.Sandbox - ctxView iscp.SandboxView - function string - id int32 - host *wasmhost.WasmHost - proc *WasmProcessor -} - -var ( - _ iscp.VMProcessorEntryPoint = &WasmContext{} - _ wasmlib.ScHost = &WasmContext{} -) - -func NewWasmContext(function string, proc *WasmProcessor) *WasmContext { - wc := &WasmContext{function: function, proc: proc} - - if proc == nil { - wc.host = &wasmhost.WasmHost{} - wc.host.Init() - return wc - } - wc.host = &proc.WasmHost - - var scKeys *wasmhost.KvStoreHost - if proc.scContext != nil { - scKeys = &proc.scContext.KvStoreHost - } - - wc.Init(scKeys) - wc.TrackObject(NewNullObject(&wc.KvStoreHost)) - wc.TrackObject(NewScContext(wc, &wc.KvStoreHost)) - return wc -} - -func (wc *WasmContext) AddFunc(f wasmlib.ScFuncContextFunction) []wasmlib.ScFuncContextFunction { - return wc.host.AddFunc(f) -} - -func (wc *WasmContext) AddView(v wasmlib.ScViewContextFunction) []wasmlib.ScViewContextFunction { - return wc.host.AddView(v) -} - -func (wc *WasmContext) Call(ctx interface{}) (dict.Dict, error) { - if wc.id == 0 { - panic("Context id is zero") - } - - wcSaved := wasmhost.Connect(wc) - defer func() { - wasmhost.Connect(wcSaved) - // clean up context after use - wc.proc.KillContext(wc.id) - }() - - switch tctx := ctx.(type) { - case iscp.Sandbox: - wc.ctx = tctx - case iscp.SandboxView: - wc.ctxView = tctx - default: - panic(iscp.ErrWrongTypeEntryPoint) - } - - if wc.function == "" { - // init function was missing, do nothing - return nil, nil - } - - if wc.function == FuncDefault { - // TODO default function, do nothing for now - return nil, nil - } - - wc.Tracef("Calling " + wc.function) - err := wc.callFunction() - if err != nil { - wc.log().Infof("VM call %s(): error %v", wc.function, err) - return nil, err - } - resultsID := wc.GetObjectID(wasmhost.OBJID_ROOT, wasmhost.KeyResults, wasmhost.OBJTYPE_MAP) - results := wc.FindObject(resultsID).(*ScDict).kvStore.(dict.Dict) - return results, nil -} - -func (wc *WasmContext) callFunction() error { - wc.proc.instanceLock.Lock() - defer wc.proc.instanceLock.Unlock() - - saveID := wc.proc.currentContextID - wc.proc.currentContextID = wc.id - err := wc.proc.RunScFunction(wc.function) - wc.proc.currentContextID = saveID - return err -} - -func (wc *WasmContext) FunctionFromCode(code uint32) string { - return wc.host.FunctionFromCode(code) -} - -func (wc *WasmContext) IsView() bool { - return wc.host.IsView(wc.function) -} - -func (wc *WasmContext) log() iscp.LogInterface { - if wc.ctx != nil { - return wc.ctx.Log() - } - if wc.ctxView != nil { - return wc.ctxView.Log() - } - return wc.proc.log -} - -func (wc *WasmContext) params() dict.Dict { - if wc.ctx != nil { - return wc.ctx.Params() - } - return wc.ctxView.Params() -} - -func (wc *WasmContext) state() kv.KVStore { - if wc.ctx != nil { - return wc.ctx.State() - } - return NewScViewState(wc.ctxView) -} diff --git a/packages/vm/wasmsolo/soloconvertor.go b/packages/vm/wasmsolo/soloconvertor.go deleted file mode 100644 index 2225226751..0000000000 --- a/packages/vm/wasmsolo/soloconvertor.go +++ /dev/null @@ -1,40 +0,0 @@ -package wasmsolo - -import ( - "github.com/iotaledger/goshimmer/packages/ledgerstate" - "github.com/iotaledger/wasp/packages/hashing" - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/iscp/colored" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" -) - -// SoloConvertor converts ISCP data types to WasmLib data types -type SoloConvertor struct{} - -func (cvt SoloConvertor) ScAddress(address ledgerstate.Address) wasmlib.ScAddress { - return wasmlib.NewScAddressFromBytes(address.Bytes()) -} - -func (cvt SoloConvertor) ScAgentID(agentID *iscp.AgentID) wasmlib.ScAgentID { - return wasmlib.NewScAgentIDFromBytes(agentID.Bytes()) -} - -func (cvt SoloConvertor) ScChainID(chainID *iscp.ChainID) wasmlib.ScChainID { - return wasmlib.NewScChainIDFromBytes(chainID.Bytes()) -} - -func (cvt SoloConvertor) ScColor(color colored.Color) wasmlib.ScColor { - return wasmlib.NewScColorFromBytes(color.Bytes()) -} - -func (cvt SoloConvertor) ScHash(hash hashing.HashValue) wasmlib.ScHash { - return wasmlib.NewScHashFromBytes(hash.Bytes()) -} - -func (cvt SoloConvertor) ScHname(hname iscp.Hname) wasmlib.ScHname { - return wasmlib.NewScHnameFromBytes(hname.Bytes()) -} - -func (cvt SoloConvertor) ScRequestID(requestID iscp.RequestID) wasmlib.ScRequestID { - return wasmlib.NewScRequestIDFromBytes(requestID.Bytes()) -} diff --git a/packages/vm/wasmsolo/solosccontext.go b/packages/vm/wasmsolo/solosccontext.go deleted file mode 100644 index b355b0232f..0000000000 --- a/packages/vm/wasmsolo/solosccontext.go +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -package wasmsolo - -import ( - "github.com/iotaledger/goshimmer/packages/ledgerstate" - "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/iscp/colored" - "github.com/iotaledger/wasp/packages/kv" - "github.com/iotaledger/wasp/packages/kv/codec" - "github.com/iotaledger/wasp/packages/kv/dict" - "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmhost" - "github.com/iotaledger/wasp/packages/vm/wasmproc" -) - -type SoloScContext struct { - wasmproc.ScContext - ctx *SoloContext -} - -func NewSoloScContext(ctx *SoloContext) *SoloScContext { - return &SoloScContext{ScContext: *wasmproc.NewScContext(nil, &ctx.wc.KvStoreHost), ctx: ctx} -} - -func (o *SoloScContext) Exists(keyID, typeID int32) bool { - return o.GetTypeID(keyID) > 0 -} - -func (o *SoloScContext) GetBytes(keyID, typeID int32) []byte { - switch keyID { - case wasmhost.KeyChainID: - return o.ctx.Chain.ChainID.Bytes() - default: - o.InvalidKey(keyID) - return nil - } -} - -func (o *SoloScContext) GetObjectID(keyID, typeID int32) int32 { - host := o.ctx.wc - return wasmproc.GetMapObjectID(o, keyID, typeID, wasmproc.ObjFactories{ - // wasmhost.KeyBalances: func() wasmproc.WaspObject { return wasmproc.NewScBalances(o.vm, keyID) }, - wasmhost.KeyExports: func() wasmproc.WaspObject { return wasmproc.NewScExports(host) }, - // wasmhost.KeyIncoming: func() wasmproc.WaspObject { return wasmproc.NewScBalances(o.vm, keyID) }, - wasmhost.KeyMaps: func() wasmproc.WaspObject { return wasmproc.NewScMaps(&host.KvStoreHost) }, - // wasmhost.KeyMinted: func() wasmproc.WaspObject { return wasmproc.NewScBalances(o.vm, keyID) }, - // wasmhost.KeyParams: func() wasmproc.WaspObject { return wasmproc.NewScDict(o.host, o.vm.params()) }, - wasmhost.KeyResults: func() wasmproc.WaspObject { return wasmproc.NewScDict(&host.KvStoreHost, dict.New()) }, - wasmhost.KeyReturn: func() wasmproc.WaspObject { return wasmproc.NewScDict(&host.KvStoreHost, dict.New()) }, - // wasmhost.KeyState: func() wasmproc.WaspObject { return wasmproc.NewScDict(o.host, o.vm.state()) }, - // wasmhost.KeyTransfers: func() wasmproc.WaspObject { return wasmproc.NewScTransfers(o.vm) }, - wasmhost.KeyUtility: func() wasmproc.WaspObject { return wasmproc.NewScUtility(nil, o.ctx) }, - }) -} - -func (o *SoloScContext) SetBytes(keyID, typeID int32, bytes []byte) { - switch keyID { - case wasmhost.KeyCall: - o.processCall(bytes) - case wasmhost.KeyPost: - o.processPost(bytes) - case wasmhost.KeyLog: - o.ctx.Chain.Log.Infof(string(bytes)) - case wasmhost.KeyTrace: - o.ctx.Chain.Log.Debugf(string(bytes)) - default: - o.ScContext.SetBytes(keyID, typeID, bytes) - } -} - -func (o *SoloScContext) processCall(bytes []byte) { - decode := wasmproc.NewBytesDecoder(bytes) - contract, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - function, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - paramsID := decode.Int32() - transferID := decode.Int32() - if transferID != 0 { - o.postSync(contract, function, paramsID, transferID, 0) - return - } - - ctx := o.ctx - funcName := ctx.wc.FunctionFromCode(uint32(function)) - if funcName == "" { - o.Panicf("unknown function") - } - o.Tracef("CALL %s.%s", ctx.scName, funcName) - params := o.getParams(paramsID) - _ = wasmhost.Connect(ctx.wasmHostOld) - res, err := ctx.Chain.CallView(ctx.scName, funcName, params) - _ = wasmhost.Connect(ctx.wc) - ctx.Err = err - if err != nil { - // o.Panicf("failed to invoke call: " + err.Error()) - return - } - returnID := o.GetObjectID(wasmhost.KeyReturn, wasmhost.OBJTYPE_MAP) - ctx.wc.FindObject(returnID).(*wasmproc.ScDict).SetKvStore(res) -} - -func (o *SoloScContext) processPost(bytes []byte) { - decode := wasmproc.NewBytesDecoder(bytes) - chainID, err := iscp.ChainIDFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - if !chainID.Equals(o.ctx.Chain.ChainID) { - o.Panicf("invalid chainID") - } - contract, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - function, err := iscp.HnameFromBytes(decode.Bytes()) - if err != nil { - o.Panicf(err.Error()) - } - paramsID := decode.Int32() - transferID := decode.Int32() - delay := decode.Int32() - o.postSync(contract, function, paramsID, transferID, delay) - //metadata := &iscp.SendMetadata{ - // TargetContract: contract, - // EntryPoint: function, - // Args: params, - //} - //delay := decode.Int32() - //if delay == 0 { - // if !o.vm.ctx.Send(chainID.AsAddress(), transfer, metadata) { - // o.Panicf("failed to send to %s", chainID.AsAddress().String()) - // } - // return - //} - // - //if delay < -1 { - // o.Panicf("invalid delay: %d", delay) - //} - // - //timeLock := time.Unix(0, o.vm.ctx.GetTimestamp()) - //timeLock = timeLock.Add(time.Duration(delay) * time.Second) - //options := iscp.SendOptions{ - // TimeLock: uint32(timeLock.Unix()), - //} - //if !o.vm.ctx.Send(chainID.AsAddress(), transfer, metadata, options) { - // o.Panicf("failed to send to %s", chainID.AsAddress().String()) - //} -} - -func (o *SoloScContext) getParams(paramsID int32) dict.Dict { - if paramsID == 0 { - return dict.New() - } - params := o.ctx.wc.FindObject(paramsID).(*wasmproc.ScDict).KvStore().(dict.Dict) - params.MustIterate("", func(key kv.Key, value []byte) bool { - o.Tracef(" PARAM '%s'", key) - return true - }) - return params -} - -func (o *SoloScContext) getTransfer(transferID int32) colored.Balances { - if transferID == 0 { - return colored.NewBalances() - } - transfer := colored.NewBalances() - transferDict := o.ctx.wc.FindObject(transferID).(*wasmproc.ScDict).KvStore() - transferDict.MustIterate("", func(key kv.Key, value []byte) bool { - color, err := codec.DecodeColor([]byte(key)) - if err != nil { - o.Panicf(err.Error()) - } - amount, err := codec.DecodeUint64(value) - if err != nil { - o.Panicf(err.Error()) - } - o.Tracef(" XFER %d '%s'", amount, color.String()) - transfer[color] = amount - return true - }) - return transfer -} - -func (o *SoloScContext) postSync(contract, function iscp.Hname, paramsID, transferID, delay int32) { - if delay != 0 { - o.Panicf("unsupported nonzero delay for SoloContext") - } - ctx := o.ctx - if contract != iscp.Hn(ctx.scName) { - o.Panicf("invalid contract") - } - funcName := ctx.wc.FunctionFromCode(uint32(function)) - if funcName == "" { - o.Panicf("unknown function") - } - o.Tracef("POST %s.%s", ctx.scName, funcName) - params := o.getParams(paramsID) - req := solo.NewCallParamsFromDic(ctx.scName, funcName, params) - if transferID != 0 { - transfer := o.getTransfer(transferID) - req.WithTransfers(transfer) - } - if ctx.mint > 0 { - mintAddress := ledgerstate.NewED25519Address(ctx.keyPair.PublicKey) - req.WithMint(mintAddress, ctx.mint) - } - _ = wasmhost.Connect(ctx.wasmHostOld) - var res dict.Dict - if ctx.offLedger { - ctx.offLedger = false - res, ctx.Err = ctx.Chain.PostRequestOffLedger(req, ctx.keyPair) - } else if !ctx.isRequest { - ctx.Tx, res, ctx.Err = ctx.Chain.PostRequestSyncTx(req, ctx.keyPair) - } else { - ctx.isRequest = false - ctx.Tx, _, ctx.Err = ctx.Chain.RequestFromParamsToLedger(req, nil) - if ctx.Err == nil { - ctx.Chain.Env.EnqueueRequests(ctx.Tx) - } - } - _ = wasmhost.Connect(ctx.wc) - if ctx.Err != nil { - return - } - returnID := o.GetObjectID(wasmhost.KeyReturn, wasmhost.OBJTYPE_MAP) - ctx.wc.FindObject(returnID).(*wasmproc.ScDict).SetKvStore(res) -} diff --git a/packages/vm/wasmvmhost/host.go b/packages/vm/wasmvmhost/host.go deleted file mode 100644 index 9b48bed8fd..0000000000 --- a/packages/vm/wasmvmhost/host.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2020 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// +build wasm - -package wasmvmhost - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - -//go:wasm-module WasmLib -//export hostGetBytes -func hostGetBytes(objID, keyID, typeID int32, value *byte, size int32) int32 - -//go:wasm-module WasmLib -//export hostGetKeyID -func hostGetKeyID(key *byte, size int32) int32 - -//go:wasm-module WasmLib -//export hostGetObjectID -func hostGetObjectID(objID, keyID, typeID int32) int32 - -//go:wasm-module WasmLib -//export hostSetBytes -func hostSetBytes(objID, keyID, typeID int32, value *byte, size int32) - -// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ - -type WasmVMHost struct{ - funcs []wasmlib.ScFuncContextFunction - views []wasmlib.ScViewContextFunction -} - -// implements wasmlib.ScHost interface -var _ wasmlib.ScHost = &WasmVMHost{} - -func (w *WasmVMHost) AddFunc(f wasmlib.ScFuncContextFunction) []wasmlib.ScFuncContextFunction { - if f != nil { - w.funcs = append(w.funcs, f) - } - return w.funcs -} - -func (w *WasmVMHost) AddView(v wasmlib.ScViewContextFunction) []wasmlib.ScViewContextFunction { - if v != nil { - w.views = append(w.views, v) - } - return w.views -} - -func (w *WasmVMHost) ConnectWasmHost() { - wasmlib.ConnectHost(w) -} - -func (w *WasmVMHost) CallFunc(objID, keyID int32, params []byte) []byte { - args := (*byte)(nil) - size := int32(len(params)) - if size != 0 { - args = ¶ms[0] - } - - // pass params and query expected length of result - size = hostGetBytes(objID, keyID, wasmlib.TYPE_CALL, args, size) - - // -1 means non-existent, so return default value for type - if size <= 0 { - return []byte(nil) - } - - // allocate a sufficient length byte array in Wasm memory - // and let the host copy the actual result into this Wasm byte array - result := make([]byte, size) - hostGetBytes(objID, keyID, wasmlib.TYPE_CALL+1, &result[0], size) - return result -} - -func (w *WasmVMHost) DelKey(objID, keyID, typeID int32) { - // size -1 means delete - // this removes the need for a separate hostDelete function - hostSetBytes(objID, keyID, typeID, nil, -1) -} - -func (w *WasmVMHost) Exists(objID, keyID, typeID int32) bool { - // size -1 means only test for existence - // returned size -1 indicates keyID not found (or error) - // this removes the need for a separate hostExists function - return hostGetBytes(objID, keyID, typeID, nil, -1) >= 0 -} - -func (w *WasmVMHost) GetBytes(objID, keyID, typeID int32) []byte { - size := int32(wasmlib.TypeSizes[typeID]) - if size == 0 { - // variable-sized type, first query expected length of bytes array - // (pass zero-length buffer) - size = hostGetBytes(objID, keyID, typeID, nil, 0) - - // -1 means non-existent, so return default value for type - if size <= 0 { - return []byte(nil) - } - } - - // allocate a sufficient length byte array in Wasm memory - // and let the host copy the actual data bytes into this Wasm byte array - result := make([]byte, size) - hostGetBytes(objID, keyID, typeID, &result[0], size) - return result -} - -func (w *WasmVMHost) GetKeyIDFromBytes(bytes []byte) int32 { - size := int32(len(bytes)) - // &bytes[0] will panic on zero length slice, so use nil instead - // negative size indicates this was from bytes - if size == 0 { - return hostGetKeyID(nil, -1) - } - return hostGetKeyID(&bytes[0], -size-1) -} - -func (w *WasmVMHost) GetKeyIDFromString(key string) int32 { - bytes := []byte(key) - size := int32(len(bytes)) - // &bytes[0] will panic on zero length slice, so use nil instead - // non-negative size indicates this was from string - if size == 0 { - return hostGetKeyID(nil, 0) - } - return hostGetKeyID(&bytes[0], size) -} - -func (w *WasmVMHost) GetObjectID(objID, keyID, typeID int32) int32 { - return hostGetObjectID(objID, keyID, typeID) -} - -func (w *WasmVMHost) SetBytes(objID, keyID, typeID int32, value []byte) { - // &bytes[0] will panic on zero length slice, so use nil instead - size := int32(len(value)) - if size == 0 { - hostSetBytes(objID, keyID, typeID, nil, size) - return - } - hostSetBytes(objID, keyID, typeID, &value[0], size) -} diff --git a/packages/wasmvm/wasmhost/wasmcontext.go b/packages/wasmvm/wasmhost/wasmcontext.go new file mode 100644 index 0000000000..3e7d1ef1a4 --- /dev/null +++ b/packages/wasmvm/wasmhost/wasmcontext.go @@ -0,0 +1,264 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmhost + +import ( + "github.com/iotaledger/wasp/packages/iscp" + "github.com/iotaledger/wasp/packages/kv" + "github.com/iotaledger/wasp/packages/kv/dict" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +const ( + FuncDefault = "_default" +) + +type ISandbox interface { + Call(funcNr int32, params []byte) []byte + Tracef(format string, args ...interface{}) +} + +type WasmContext struct { + funcName string + funcTable *WasmFuncTable + id int32 + proc *WasmProcessor + results dict.Dict + sandbox ISandbox + wcSandbox *WasmContextSandbox +} + +var ( + _ iscp.VMProcessorEntryPoint = &WasmContext{} + _ wasmlib.ScHost = &WasmContext{} +) + +func NewWasmContext(function string, proc *WasmProcessor) *WasmContext { + return &WasmContext{ + funcName: function, + proc: proc, + funcTable: proc.funcTable, + } +} + +func NewWasmContextForSoloContext(function string, sandbox ISandbox) *WasmContext { + return &WasmContext{ + funcName: function, + sandbox: sandbox, + funcTable: NewWasmFuncTable(), + } +} + +func (wc *WasmContext) Call(ctx interface{}) (dict.Dict, error) { + if wc.id == 0 { + panic("Context id is zero") + } + + wc.wcSandbox = NewWasmContextSandbox(wc, ctx) + wc.sandbox = wc.wcSandbox + + wcSaved := Connect(wc) + defer func() { + Connect(wcSaved) + // clean up context after use + wc.proc.KillContext(wc.id) + }() + + if wc.funcName == "" { + // init function was missing, do nothing + return nil, nil + } + + if wc.funcName == FuncDefault { + // TODO default function, do nothing for now + return nil, nil + } + + wc.tracef("Calling " + wc.funcName) + wc.results = nil + err := wc.callFunction() + if err != nil { + wc.log().Infof("VM call %s(): error %v", wc.funcName, err) + return nil, err + } + return wc.results, nil +} + +func (wc *WasmContext) callFunction() error { + wc.proc.instanceLock.Lock() + defer wc.proc.instanceLock.Unlock() + + saveID := wc.proc.currentContextID + wc.proc.currentContextID = wc.id + err := wc.proc.RunScFunction(wc.funcName) + wc.proc.currentContextID = saveID + return err +} + +func (wc *WasmContext) ExportName(index int32, name string) { + if index >= 0 { + if HostTracing { + wc.tracef("ExportName(%d, %s)", index, name) + } + wc.funcTable.SetExport(index, name) + return + } + + // index -1 means log WASM tag + if wc.proc != nil { + // Invocation through WasmGoVM + wc.proc.log.Infof("WASM::GO::DEBUG") + return + } + + // Invocation through SoloContext + wc.sandbox.Call(wasmlib.FnLog, wasmtypes.StringToBytes("WASM::SOLO")) +} + +func (wc *WasmContext) FunctionFromCode(code uint32) string { + return wc.funcTable.FunctionFromCode(code) +} + +func (wc *WasmContext) IsView() bool { + return wc.proc.IsView(wc.funcName) +} + +func (wc *WasmContext) log() iscp.LogInterface { + if wc.wcSandbox != nil && wc.wcSandbox.common != nil { + return wc.wcSandbox.common.Log() + } + return wc.proc.log +} + +func (wc *WasmContext) Sandbox(funcNr int32, params []byte) []byte { + if !HostTracing || funcNr == wasmlib.FnLog || funcNr == wasmlib.FnTrace { + return wc.sandbox.Call(funcNr, params) + } + + wc.tracef("Sandbox(%s)", traceSandbox(funcNr, params)) + res := wc.sandbox.Call(funcNr, params) + wc.tracef(" => %s", hex(res)) + return res +} + +// state reduces the context state to a KVStoreReader +func (wc *WasmContext) state() kv.KVStoreReader { + ctx := wc.wcSandbox.ctx + if ctx != nil { + return ctx.State() + } + ctxView := wc.wcSandbox.ctxView + if ctxView != nil { + return ctxView.State() + } + panic("cannot access state") +} + +func (wc *WasmContext) StateDelete(key []byte) { + if HostTracing { + wc.tracef("StateDelete(%s)", traceHex(key)) + } + ctx := wc.wcSandbox.ctx + if ctx == nil { + panic("StateDelete: readonly state") + } + ctx.State().Del(kv.Key(key)) +} + +func (wc *WasmContext) StateExists(key []byte) bool { + exists, err := wc.state().Has(kv.Key(key)) + if err != nil { + panic("StateExists: " + err.Error()) + } + if HostTracing { + wc.tracef("StateExists(%s) = %v", traceHex(key), exists) + } + return exists +} + +func (wc *WasmContext) StateGet(key []byte) []byte { + res, err := wc.state().Get(kv.Key(key)) + if err != nil { + panic("StateGet: " + err.Error()) + } + if HostTracing { + wc.tracef("StateGet(%s)", traceHex(key)) + wc.tracef(" => %s", hex(res)) + } + return res +} + +func (wc *WasmContext) StateSet(key, value []byte) { + if HostTracing { + wc.tracef("StateSet(%s, %s)", traceHex(key), traceVal(value)) + } + ctx := wc.wcSandbox.ctx + if ctx == nil { + panic("StateSet: readonly state") + } + ctx.State().Set(kv.Key(key), value) +} + +func (wc *WasmContext) tracef(format string, args ...interface{}) { + if wc.proc != nil { + wc.log().Debugf(format, args...) + return + } + wc.sandbox.Tracef(format, args...) +} + +func traceHex(key []byte) string { + name := "" + for i, b := range key { + if b == '.' { + return string(key[:i+1]) + hex(key[i+1:]) + } + if b == '#' { + name = string(key[:i+1]) + j := i + 1 + for ; (key[j] & 0x80) != 0; j++ { + } + dec := wasmtypes.NewWasmDecoder(key[i+1 : j+1]) + index := wasmtypes.Uint64Decode(dec) + name += wasmtypes.Uint64ToString(index) + if j+1 == len(key) { + return name + } + return name + "..." + hex(key[j+1:]) + } + } + return `"` + string(key) + `"` +} + +func traceSandbox(funcNr int32, params []byte) string { + name := sandboxFuncNames[-funcNr] + if name[0] == '$' { + return name[1:] + ", " + string(params) + } + if name[0] != '#' { + return name + } + return name[1:] + ", " + hex(params) +} + +func traceVal(val []byte) string { + for _, b := range val { + if b < ' ' || b > '~' { + return hex(val) + } + } + return string(val) +} + +// hex returns a hex string representing the byte buffer +func hex(buf []byte) string { + const hexa = "0123456789abcdef" + res := make([]byte, len(buf)*2) + for i, b := range buf { + res[i*2] = hexa[b>>4] + res[i*2+1] = hexa[b&0x0f] + } + return string(res) +} diff --git a/packages/wasmvm/wasmhost/wasmcontextsandbox.go b/packages/wasmvm/wasmhost/wasmcontextsandbox.go new file mode 100644 index 0000000000..587fe97063 --- /dev/null +++ b/packages/wasmvm/wasmhost/wasmcontextsandbox.go @@ -0,0 +1,409 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmhost + +import ( + "time" + + "github.com/iotaledger/wasp/packages/hashing" + "github.com/iotaledger/wasp/packages/iscp" + "github.com/iotaledger/wasp/packages/iscp/colored" + "github.com/iotaledger/wasp/packages/kv/codec" + "github.com/iotaledger/wasp/packages/kv/dict" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +// NOTE: These functions correspond to the Sandbox fnXxx constants in WasmLib +var sandboxFunctions = []func(*WasmContextSandbox, []byte) []byte{ + nil, + (*WasmContextSandbox).fnAccountID, + (*WasmContextSandbox).fnBalance, + (*WasmContextSandbox).fnBalances, + (*WasmContextSandbox).fnBlockContext, + (*WasmContextSandbox).fnCall, + (*WasmContextSandbox).fnCaller, + (*WasmContextSandbox).fnChainID, + (*WasmContextSandbox).fnChainOwnerID, + (*WasmContextSandbox).fnContract, + (*WasmContextSandbox).fnContractCreator, + (*WasmContextSandbox).fnDeployContract, + (*WasmContextSandbox).fnEntropy, + (*WasmContextSandbox).fnEvent, + (*WasmContextSandbox).fnIncomingTransfer, + (*WasmContextSandbox).fnLog, + (*WasmContextSandbox).fnMinted, + (*WasmContextSandbox).fnPanic, + (*WasmContextSandbox).fnParams, + (*WasmContextSandbox).fnPost, + (*WasmContextSandbox).fnRequest, + (*WasmContextSandbox).fnRequestID, + (*WasmContextSandbox).fnResults, + (*WasmContextSandbox).fnSend, + (*WasmContextSandbox).fnStateAnchor, + (*WasmContextSandbox).fnTimestamp, + (*WasmContextSandbox).fnTrace, + (*WasmContextSandbox).fnUtilsBase58Decode, + (*WasmContextSandbox).fnUtilsBase58Encode, + (*WasmContextSandbox).fnUtilsBlsAddress, + (*WasmContextSandbox).fnUtilsBlsAggregate, + (*WasmContextSandbox).fnUtilsBlsValid, + (*WasmContextSandbox).fnUtilsEd25519Address, + (*WasmContextSandbox).fnUtilsEd25519Valid, + (*WasmContextSandbox).fnUtilsHashBlake2b, + (*WasmContextSandbox).fnUtilsHashName, + (*WasmContextSandbox).fnUtilsHashSha3, +} + +// '$' prefix indicates a string param +// '$' prefix indicates a bytes param +// otherwise there is no param +// NOTE: These strings correspond to the Sandbox fnXxx constants in WasmLib +var sandboxFuncNames = []string{ + "nil", + "FnAccountID", + "#FnBalance", + "FnBalances", + "FnBlockContext", + "FnCall", + "FnCaller", + "FnChainID", + "FnChainOwnerID", + "FnContract", + "FnContractCreator", + "#FnDeployContract", + "FnEntropy", + "$FnEvent", + "FnIncomingTransfer", + "$FnLog", + "FnMinted", + "$FnPanic", + "FnParams", + "#FnPost", + "FnRequest", + "FnRequestID", + "#FnResults", + "#FnSend", + "#FnStateAnchor", + "FnTimestamp", + "$FnTrace", + "$FnUtilsBase58Decode", + "#FnUtilsBase58Encode", + "#FnUtilsBlsAddress", + "#FnUtilsBlsAggregate", + "#FnUtilsBlsValid", + "#FnUtilsEd25519Address", + "#FnUtilsEd25519Valid", + "#FnUtilsHashBlake2b", + "$FnUtilsHashName", + "#FnUtilsHashSha3", +} + +// WasmContextSandbox is the host side of the WasmLib Sandbox interface +// It acts as a change-resistant layer to wrap changes to the ISCP sandbox, +// to limit bothering users of WasmLib as little as possible with those changes. +type WasmContextSandbox struct { + common iscp.SandboxBase + ctx iscp.Sandbox + ctxView iscp.SandboxView + cvt WasmConvertor + wc *WasmContext +} + +var _ ISandbox = new(WasmContextSandbox) + +func NewWasmContextSandbox(wc *WasmContext, ctx interface{}) *WasmContextSandbox { + s := &WasmContextSandbox{wc: wc} + switch tctx := ctx.(type) { + case iscp.Sandbox: + s.common = tctx + s.ctx = tctx + case iscp.SandboxView: + s.common = tctx + s.ctxView = tctx + default: + panic(iscp.ErrWrongTypeEntryPoint) + } + return s +} + +func (s *WasmContextSandbox) Call(funcNr int32, params []byte) []byte { + return sandboxFunctions[-funcNr](s, params) +} + +func (s *WasmContextSandbox) checkErr(err error) { + if err != nil { + s.Panicf(err.Error()) + } +} + +func (s *WasmContextSandbox) Panicf(format string, args ...interface{}) { + s.common.Log().Panicf(format, args...) +} + +func (s *WasmContextSandbox) Tracef(format string, args ...interface{}) { + s.common.Log().Debugf(format, args...) +} + +//////////////////// sandbox functions \\\\\\\\\\\\\\\\\\\\ + +func (s *WasmContextSandbox) fnAccountID(args []byte) []byte { + return s.cvt.ScAgentID(s.common.AccountID()).Bytes() +} + +func (s *WasmContextSandbox) fnBalance(args []byte) []byte { + color, err := colored.ColorFromBytes(args) + s.checkErr(err) + return codec.EncodeUint64(s.ctx.Balance(color)) +} + +func (s *WasmContextSandbox) fnBalances(args []byte) []byte { + return s.common.Balances().Bytes() +} + +func (s *WasmContextSandbox) fnBlockContext(args []byte) []byte { + panic("implement me") +} + +func (s *WasmContextSandbox) fnCall(args []byte) []byte { + req := wasmrequests.NewCallRequestFromBytes(args) + contract := s.cvt.IscpHname(req.Contract) + function := s.cvt.IscpHname(req.Function) + params, err := dict.FromBytes(req.Params) + s.checkErr(err) + transfer, err := colored.BalancesFromBytes(req.Transfer) + s.checkErr(err) + s.Tracef("CALL hContract '%s, hFunction %s", contract.String(), function.String()) + results, err := s.callUnlocked(contract, function, params, transfer) + s.checkErr(err) + return results.Bytes() +} + +func (s *WasmContextSandbox) callUnlocked(contract, function iscp.Hname, params dict.Dict, transfer colored.Balances) (dict.Dict, error) { + s.wc.proc.instanceLock.Unlock() + defer s.wc.proc.instanceLock.Lock() + + if s.ctx != nil { + return s.ctx.Call(contract, function, params, transfer) + } + return s.ctxView.Call(contract, function, params) +} + +func (s *WasmContextSandbox) fnCaller(args []byte) []byte { + return s.cvt.ScAgentID(s.ctx.Caller()).Bytes() +} + +func (s *WasmContextSandbox) fnChainID(args []byte) []byte { + return s.cvt.ScChainID(s.common.ChainID()).Bytes() +} + +func (s *WasmContextSandbox) fnChainOwnerID(args []byte) []byte { + return s.cvt.ScAgentID(s.common.ChainOwnerID()).Bytes() +} + +func (s *WasmContextSandbox) fnContract(args []byte) []byte { + return s.cvt.ScHname(s.common.Contract()).Bytes() +} + +func (s *WasmContextSandbox) fnContractCreator(args []byte) []byte { + return s.cvt.ScAgentID(s.common.ContractCreator()).Bytes() +} + +func (s *WasmContextSandbox) fnDeployContract(args []byte) []byte { + req := wasmrequests.NewDeployRequestFromBytes(args) + programHash, err := hashing.HashValueFromBytes(req.ProgHash.Bytes()) + s.checkErr(err) + initParams, err := dict.FromBytes(req.Params) + s.checkErr(err) + s.Tracef("DEPLOY %s: %s", req.Name, req.Description) + err = s.deployUnlocked(programHash, req.Name, req.Description, initParams) + s.checkErr(err) + return nil +} + +func (s *WasmContextSandbox) deployUnlocked(programHash hashing.HashValue, name, description string, params dict.Dict) error { + s.wc.proc.instanceLock.Unlock() + defer s.wc.proc.instanceLock.Lock() + + return s.ctx.DeployContract(programHash, name, description, params) +} + +func (s *WasmContextSandbox) fnEntropy(args []byte) []byte { + return s.cvt.ScHash(s.ctx.GetEntropy()).Bytes() +} + +func (s *WasmContextSandbox) fnEvent(args []byte) []byte { + s.ctx.Event(string(args)) + return nil +} + +func (s *WasmContextSandbox) fnIncomingTransfer(args []byte) []byte { + return s.ctx.IncomingTransfer().Bytes() +} + +func (s *WasmContextSandbox) fnLog(args []byte) []byte { + s.common.Log().Infof(string(args)) + return nil +} + +func (s *WasmContextSandbox) fnMinted(args []byte) []byte { + return s.ctx.Minted().Bytes() +} + +func (s *WasmContextSandbox) fnPanic(args []byte) []byte { + s.common.Log().Panicf(string(args)) + return nil +} + +func (s *WasmContextSandbox) fnParams(args []byte) []byte { + return s.common.Params().Bytes() +} + +func (s *WasmContextSandbox) fnPost(args []byte) []byte { + req := wasmrequests.NewPostRequestFromBytes(args) + chainID := s.cvt.IscpChainID(&req.ChainID) + contract := s.cvt.IscpHname(req.Contract) + function := s.cvt.IscpHname(req.Function) + params, err := dict.FromBytes(req.Params) + s.checkErr(err) + transfer, err := colored.BalancesFromBytes(req.Transfer) + s.checkErr(err) + if len(transfer) == 0 { + transfer.Add(colored.Color{}, 1) + } + + s.Tracef("POST hContract '%s, hFunction %s, chain %s", contract.String(), function.String(), chainID.String()) + metadata := &iscp.SendMetadata{ + TargetContract: contract, + EntryPoint: function, + Args: params, + } + if req.Delay != 0 { + if !s.ctx.Send(chainID.AsAddress(), transfer, metadata) { + s.Panicf("failed to send to %s", chainID.AsAddress().String()) + } + return nil + } + + options := iscp.SendOptions{ + TimeLock: uint32(time.Duration(s.ctx.GetTimestamp())/time.Second) + req.Delay, + } + if !s.ctx.Send(chainID.AsAddress(), transfer, metadata, options) { + s.Panicf("failed to send to %s", chainID.AsAddress().String()) + } + return nil +} + +func (s *WasmContextSandbox) fnRequest(args []byte) []byte { + return s.ctx.Request().Bytes() +} + +func (s *WasmContextSandbox) fnRequestID(args []byte) []byte { + return s.cvt.ScRequestID(s.ctx.Request().ID()).Bytes() +} + +func (s *WasmContextSandbox) fnResults(args []byte) []byte { + results, err := dict.FromBytes(args) + if err != nil { + s.Panicf("call results: %s", err.Error()) + } + s.wc.results = results + return nil +} + +// transfer tokens to address +func (s *WasmContextSandbox) fnSend(args []byte) []byte { + req := wasmrequests.NewSendRequestFromBytes(args) + address := s.cvt.IscpAddress(&req.Address) + transfer, err := colored.BalancesFromBytes(req.Transfer) + s.checkErr(err) + if len(transfer) != 0 { + if !s.ctx.Send(address, transfer, nil) { + s.Panicf("failed to send to %s", address.String()) + } + } + return nil +} + +func (s *WasmContextSandbox) fnStateAnchor(args []byte) []byte { + panic("implement me") +} + +func (s *WasmContextSandbox) fnTimestamp(args []byte) []byte { + return codec.EncodeInt64(s.common.GetTimestamp()) +} + +func (s *WasmContextSandbox) fnTrace(args []byte) []byte { + s.common.Log().Debugf(string(args)) + return nil +} + +func (s WasmContextSandbox) fnUtilsBase58Decode(args []byte) []byte { + bytes, err := s.common.Utils().Base58().Decode(string(args)) + s.checkErr(err) + return bytes +} + +func (s WasmContextSandbox) fnUtilsBase58Encode(args []byte) []byte { + return []byte(s.common.Utils().Base58().Encode(args)) +} + +func (s WasmContextSandbox) fnUtilsBlsAddress(args []byte) []byte { + address, err := s.common.Utils().BLS().AddressFromPublicKey(args) + s.checkErr(err) + return s.cvt.ScAddress(address).Bytes() +} + +func (s WasmContextSandbox) fnUtilsBlsAggregate(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + count := wasmtypes.Uint32Decode(dec) + pubKeysBin := make([][]byte, count) + for i := uint32(0); i < count; i++ { + pubKeysBin[i] = dec.Bytes() + } + count = wasmtypes.Uint32Decode(dec) + sigsBin := make([][]byte, count) + for i := uint32(0); i < count; i++ { + sigsBin[i] = dec.Bytes() + } + pubKeyBin, sigBin, err := s.common.Utils().BLS().AggregateBLSSignatures(pubKeysBin, sigsBin) + s.checkErr(err) + return wasmtypes.NewWasmEncoder().Bytes(pubKeyBin).Bytes(sigBin).Buf() +} + +func (s WasmContextSandbox) fnUtilsBlsValid(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + data := dec.Bytes() + pubKey := dec.Bytes() + signature := dec.Bytes() + valid := s.common.Utils().BLS().ValidSignature(data, pubKey, signature) + return codec.EncodeBool(valid) +} + +func (s WasmContextSandbox) fnUtilsEd25519Address(args []byte) []byte { + address, err := s.common.Utils().ED25519().AddressFromPublicKey(args) + s.checkErr(err) + return s.cvt.ScAddress(address).Bytes() +} + +func (s WasmContextSandbox) fnUtilsEd25519Valid(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + data := dec.Bytes() + pubKey := dec.Bytes() + signature := dec.Bytes() + valid := s.common.Utils().ED25519().ValidSignature(data, pubKey, signature) + return codec.EncodeBool(valid) +} + +func (s WasmContextSandbox) fnUtilsHashBlake2b(args []byte) []byte { + return s.cvt.ScHash(s.common.Utils().Hashing().Blake2b(args)).Bytes() +} + +func (s WasmContextSandbox) fnUtilsHashName(args []byte) []byte { + return s.cvt.ScHname(s.common.Utils().Hashing().Hname(string(args))).Bytes() +} + +func (s WasmContextSandbox) fnUtilsHashSha3(args []byte) []byte { + return s.cvt.ScHash(s.common.Utils().Hashing().Sha3(args)).Bytes() +} diff --git a/packages/wasmvm/wasmhost/wasmconvertor.go b/packages/wasmvm/wasmhost/wasmconvertor.go new file mode 100644 index 0000000000..e5837d1225 --- /dev/null +++ b/packages/wasmvm/wasmhost/wasmconvertor.go @@ -0,0 +1,93 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmhost + +import ( + "github.com/iotaledger/goshimmer/packages/ledgerstate" + "github.com/iotaledger/wasp/packages/hashing" + "github.com/iotaledger/wasp/packages/iscp" + "github.com/iotaledger/wasp/packages/iscp/colored" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +// WasmConvertor converts ISCP data types to WasmLib data types +type WasmConvertor struct{} + +func (cvt WasmConvertor) IscpAddress(address *wasmtypes.ScAddress) ledgerstate.Address { + ret, _, err := ledgerstate.AddressFromBytes(address.Bytes()) + if err != nil { + panic(err) + } + return ret +} + +func (cvt WasmConvertor) IscpAgentID(agentID *wasmtypes.ScAgentID) *iscp.AgentID { + address := agentID.Address() + hname := agentID.Hname() + return iscp.NewAgentID(cvt.IscpAddress(&address), cvt.IscpHname(hname)) +} + +func (cvt WasmConvertor) IscpChainID(chainID *wasmtypes.ScChainID) *iscp.ChainID { + ret, err := iscp.ChainIDFromBytes(chainID.Bytes()) + if err != nil { + panic(err) + } + return ret +} + +func (cvt WasmConvertor) IscpColor(color *wasmtypes.ScColor) colored.Color { + ret, err := colored.ColorFromBytes(color.Bytes()) + if err != nil { + panic(err) + } + return ret +} + +func (cvt WasmConvertor) IscpHash(hash *wasmtypes.ScHash) hashing.HashValue { + ret, err := hashing.HashValueFromBytes(hash.Bytes()) + if err != nil { + panic(err) + } + return ret +} + +func (cvt WasmConvertor) IscpHname(hname wasmtypes.ScHname) iscp.Hname { + return iscp.Hname(hname) +} + +func (cvt WasmConvertor) IscpRequestID(requestID *wasmtypes.ScRequestID) iscp.RequestID { + ret, err := iscp.RequestIDFromBytes(requestID.Bytes()) + if err != nil { + panic(err) + } + return ret +} + +func (cvt WasmConvertor) ScAddress(address ledgerstate.Address) wasmtypes.ScAddress { + return wasmtypes.AddressFromBytes(address.Bytes()) +} + +func (cvt WasmConvertor) ScAgentID(agentID *iscp.AgentID) wasmtypes.ScAgentID { + return wasmtypes.AgentIDFromBytes(agentID.Bytes()) +} + +func (cvt WasmConvertor) ScChainID(chainID *iscp.ChainID) wasmtypes.ScChainID { + return wasmtypes.ChainIDFromBytes(chainID.Bytes()) +} + +func (cvt WasmConvertor) ScColor(color *colored.Color) wasmtypes.ScColor { + return wasmtypes.ColorFromBytes(color.Bytes()) +} + +func (cvt WasmConvertor) ScHash(hash hashing.HashValue) wasmtypes.ScHash { + return wasmtypes.HashFromBytes(hash.Bytes()) +} + +func (cvt WasmConvertor) ScHname(hname iscp.Hname) wasmtypes.ScHname { + return wasmtypes.ScHname(hname) +} + +func (cvt WasmConvertor) ScRequestID(requestID iscp.RequestID) wasmtypes.ScRequestID { + return wasmtypes.RequestIDFromBytes(requestID.Bytes()) +} diff --git a/packages/vm/wasmhost/wasmedgevm.go b/packages/wasmvm/wasmhost/wasmedgevm.go similarity index 71% rename from packages/vm/wasmhost/wasmedgevm.go rename to packages/wasmvm/wasmhost/wasmedgevm.go index d66ca04ba8..d23f9d55a7 100644 --- a/packages/vm/wasmhost/wasmedgevm.go +++ b/packages/wasmvm/wasmhost/wasmedgevm.go @@ -1,6 +1,7 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 +//go:build wasmedge // +build wasmedge package wasmhost @@ -13,7 +14,7 @@ import ( type WasmEdgeVM struct { WasmVMBase - edge *wasmedge.VM + edge *wasmedge.VM memory *wasmedge.Memory module *wasmedge.ImportObject store *wasmedge.Store @@ -24,7 +25,7 @@ type HostFunction func(params []interface{}) []interface{} const I32 = wasmedge.ValType_I32 -var i32 = []wasmedge.ValType{I32, I32, I32, I32, I32} +var wasmedgerI32Params = []wasmedge.ValType{I32, I32, I32, I32, I32} func NewWasmEdgeVM() WasmVM { vm := &WasmEdgeVM{} @@ -39,8 +40,16 @@ func NewWasmEdgeVM() WasmVM { return vm } -func (vm *WasmEdgeVM) NewInstance() WasmVM { - return NewWasmEdgeVM() +func (vm *WasmEdgeVM) Instantiate() error { + err := vm.edge.Instantiate() + if err != nil { + return err + } + vm.memory = vm.edge.GetStore().FindMemory("memory") + if vm.memory == nil { + return errors.New("no memory export") + } + return nil } //TODO @@ -48,28 +57,12 @@ func (vm *WasmEdgeVM) Interrupt() { panic("implement me") } -func (vm *WasmEdgeVM) importFunc(nrParams int, nrResults int, funcName string, function HostFunction) { - wrapper := func(_data interface{}, _mem *wasmedge.Memory, params []interface{}) ([]interface{}, wasmedge.Result) { - return function(params), wasmedge.Result_Success - } - funcType := wasmedge.NewFunctionType(i32[:nrParams], i32[:nrResults]) - funcWrapper := wasmedge.NewFunction(funcType, wrapper, nil, 0) - vm.module.AddFunction(funcName, funcWrapper) -} - -func (vm *WasmEdgeVM) importModule(name string) { - vm.module = wasmedge.NewImportObject(name) - vm.importers = append(vm.importers, vm.module) -} - -func (vm *WasmEdgeVM) LinkHost(impl WasmVM, host *WasmHost) error { - _ = vm.WasmVMBase.LinkHost(impl, host) +func (vm *WasmEdgeVM) LinkHost(proc *WasmProcessor) error { + _ = vm.WasmVMBase.LinkHost(proc) vm.importModule(ModuleWasmLib) - vm.importFunc(5, 1, FuncHostGetBytes, vm.exportHostGetBytes) - vm.importFunc(2, 1,FuncHostGetKeyID, vm.exportHostGetKeyID) - vm.importFunc(3, 1, FuncHostGetObjectID, vm.exportHostGetObjectID) - vm.importFunc(5, 0, FuncHostSetBytes, vm.exportHostSetBytes) + vm.importFunc(4, 1, FuncHostStateGet, vm.exportHostStateGet) + vm.importFunc(4, 0, FuncHostStateSet, vm.exportHostStateSet) err := vm.edge.RegisterImport(vm.module) if err != nil { return err @@ -107,31 +100,20 @@ func (vm *WasmEdgeVM) LoadWasm(wasmData []byte) error { return vm.Instantiate() } -func (vm *WasmEdgeVM) Instantiate() error { - err := vm.edge.Instantiate() - if err != nil { - return err - } - vm.memory = vm.edge.GetStore().FindMemory("memory") - if vm.memory == nil { - return errors.New("no memory export") - } - return nil +func (vm *WasmEdgeVM) NewInstance() WasmVM { + return NewWasmEdgeVM() } func (vm *WasmEdgeVM) RunFunction(functionName string, args ...interface{}) error { return vm.Run(func() (err error) { - _,err = vm.edge.Execute(functionName, args...) + _, err = vm.edge.Execute(functionName, args...) return err }) } func (vm *WasmEdgeVM) RunScFunction(index int32) error { - frame := vm.PreCall() - defer vm.PostCall(frame) - return vm.Run(func() (err error) { - _,err = vm.edge.Execute("on_call", index) + _, err = vm.edge.Execute("on_call", index) return err }) } @@ -168,7 +150,7 @@ func (vm *WasmEdgeVM) exportAbort(args []interface{}) []interface{} { fileName := args[1].(int32) line := args[2].(int32) col := args[3].(int32) - vm.EnvAbort(errMsg, fileName, line, col) + vm.HostAbort(errMsg, fileName, line, col) return nil } @@ -181,37 +163,34 @@ func (vm *WasmEdgeVM) exportFdWrite(args []interface{}) []interface{} { return []interface{}{ret} } -func (vm *WasmEdgeVM) exportHostGetBytes(args []interface{}) []interface{} { - objID := args[0].(int32) - keyID := args[1].(int32) - typeID := args[2].(int32) - stringRef := args[3].(int32) - size := args[4].(int32) - ret := vm.HostGetBytes(objID, keyID, typeID, stringRef, size) +func (vm *WasmEdgeVM) exportHostStateGet(args []interface{}) []interface{} { + keyRef := args[0].(int32) + keyLen := args[1].(int32) + valRef := args[2].(int32) + valLen := args[3].(int32) + ret := vm.HostStateGet(keyRef, keyLen, valRef, valLen) return []interface{}{ret} } -func (vm *WasmEdgeVM) exportHostGetKeyID(args []interface{}) []interface{} { +func (vm *WasmEdgeVM) exportHostStateSet(args []interface{}) []interface{} { keyRef := args[0].(int32) - size := args[1].(int32) - ret := vm.HostGetKeyID(keyRef, size) - return []interface{}{ret} + keyLen := args[1].(int32) + valRef := args[2].(int32) + valLen := args[3].(int32) + vm.HostStateSet(keyRef, keyLen, valRef, valLen) + return nil } -func (vm *WasmEdgeVM) exportHostGetObjectID(args []interface{}) []interface{} { - objID := args[0].(int32) - keyID := args[1].(int32) - typeID := args[2].(int32) - ret := vm.HostGetObjectID(objID, keyID, typeID) - return []interface{}{ret} +func (vm *WasmEdgeVM) importFunc(nrParams int, nrResults int, funcName string, function HostFunction) { + wrapper := func(_data interface{}, _mem *wasmedge.Memory, params []interface{}) ([]interface{}, wasmedge.Result) { + return function(params), wasmedge.Result_Success + } + funcType := wasmedge.NewFunctionType(wasmedgerI32Params[:nrParams], wasmedgerI32Params[:nrResults]) + funcWrapper := wasmedge.NewFunction(funcType, wrapper, nil, 0) + vm.module.AddFunction(funcName, funcWrapper) } -func (vm *WasmEdgeVM) exportHostSetBytes(args []interface{}) []interface{} { - objID := args[0].(int32) - keyID := args[1].(int32) - typeID := args[2].(int32) - stringRef := args[3].(int32) - size := args[4].(int32) - vm.HostSetBytes(objID, keyID, typeID, stringRef, size) - return nil +func (vm *WasmEdgeVM) importModule(name string) { + vm.module = wasmedge.NewImportObject(name) + vm.importers = append(vm.importers, vm.module) } diff --git a/packages/vm/wasmhost/wasmervm.go b/packages/wasmvm/wasmhost/wasmervm.go similarity index 63% rename from packages/vm/wasmhost/wasmervm.go rename to packages/wasmvm/wasmhost/wasmervm.go index 8afb66c419..60297effb7 100644 --- a/packages/vm/wasmhost/wasmervm.go +++ b/packages/wasmvm/wasmhost/wasmervm.go @@ -1,6 +1,7 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 +//go:build wasmer // +build wasmer package wasmhost @@ -18,7 +19,7 @@ type WasmerVM struct { store *wasmer.Store } -var i32 = []wasmer.ValueKind{wasmer.I32, wasmer.I32, wasmer.I32, wasmer.I32, wasmer.I32} +var wasmerI32Params = []wasmer.ValueKind{wasmer.I32, wasmer.I32, wasmer.I32, wasmer.I32, wasmer.I32} func NewWasmerVM() WasmVM { vm := &WasmerVM{} @@ -26,24 +27,19 @@ func NewWasmerVM() WasmVM { return vm } -func (vm *WasmerVM) NewInstance() WasmVM { - return &WasmerVM{ store: vm.store } -} - //TODO func (vm *WasmerVM) Interrupt() { panic("implement me") } -func (vm *WasmerVM) LinkHost(impl WasmVM, host *WasmHost) error { +func (vm *WasmerVM) LinkHost(proc *WasmProcessor) error { + _ = vm.WasmVMBase.LinkHost(proc) + vm.linker = wasmer.NewImportObject() - _ = vm.WasmVMBase.LinkHost(impl, host) funcs := map[string]wasmer.IntoExtern{ - FuncHostGetBytes: vm.importFunc(5, 1, vm.exportHostGetBytes), - FuncHostGetKeyID: vm.importFunc(2, 1, vm.exportHostGetKeyID), - FuncHostGetObjectID: vm.importFunc(3, 1, vm.exportHostGetObjectID), - FuncHostSetBytes: vm.importFunc(5, 0, vm.exportHostSetBytes), + FuncHostStateGet: vm.importFunc(4, 1, vm.exportHostStateGet), + FuncHostStateSet: vm.importFunc(4, 0, vm.exportHostStateSet), } vm.linker.Register(ModuleWasmLib, funcs) @@ -61,13 +57,6 @@ func (vm *WasmerVM) LinkHost(impl WasmVM, host *WasmHost) error { return nil } -func (vm *WasmerVM) importFunc(nrParams, nrResults int, function func([]wasmer.Value) ([]wasmer.Value, error)) *wasmer.Extern { - params := wasmer.NewValueTypes(i32[:nrParams]...) - results := wasmer.NewValueTypes(i32[:nrResults]...) - funcType := wasmer.NewFunctionType(params, results) - return wasmer.NewFunction(vm.store, funcType, function).IntoExtern() -} - func (vm *WasmerVM) LoadWasm(wasmData []byte) error { var err error vm.module, err = wasmer.NewModule(vm.store, wasmData) @@ -82,6 +71,10 @@ func (vm *WasmerVM) LoadWasm(wasmData []byte) error { return err } +func (vm *WasmerVM) NewInstance() WasmVM { + return &WasmerVM{store: vm.store} +} + func (vm *WasmerVM) RunFunction(functionName string, args ...interface{}) error { export, err := vm.instance.Exports.GetFunction(functionName) if err != nil { @@ -98,12 +91,10 @@ func (vm *WasmerVM) RunScFunction(index int32) error { if err != nil { return err } - frame := vm.PreCall() err = vm.Run(func() error { _, err = export(index) return err }) - vm.PostCall(frame) return err } @@ -116,7 +107,7 @@ func (vm *WasmerVM) exportAbort(args []wasmer.Value) ([]wasmer.Value, error) { fileName := args[1].I32() line := args[2].I32() col := args[3].I32() - vm.EnvAbort(errMsg, fileName, line, col) + vm.HostAbort(errMsg, fileName, line, col) return nil, nil } @@ -129,37 +120,27 @@ func (vm *WasmerVM) exportFdWrite(args []wasmer.Value) ([]wasmer.Value, error) { return []wasmer.Value{wasmer.NewI32(ret)}, nil } -func (vm *WasmerVM) exportHostGetBytes(args []wasmer.Value) ([]wasmer.Value, error) { - objID := args[0].I32() - keyID := args[1].I32() - typeID := args[2].I32() - stringRef := args[3].I32() - size := args[4].I32() - ret := vm.HostGetBytes(objID, keyID, typeID, stringRef, size) - return []wasmer.Value{wasmer.NewI32(ret)}, nil -} - -func (vm *WasmerVM) exportHostGetKeyID(args []wasmer.Value) ([]wasmer.Value, error) { +func (vm *WasmerVM) exportHostStateGet(args []wasmer.Value) ([]wasmer.Value, error) { keyRef := args[0].I32() - size := args[1].I32() - ret := vm.HostGetKeyID(keyRef, size) + keyLen := args[1].I32() + valRef := args[2].I32() + valLen := args[3].I32() + ret := vm.HostStateGet(keyRef, keyLen, valRef, valLen) return []wasmer.Value{wasmer.NewI32(ret)}, nil } -func (vm *WasmerVM) exportHostGetObjectID(args []wasmer.Value) ([]wasmer.Value, error) { - objID := args[0].I32() - keyID := args[1].I32() - typeID := args[2].I32() - ret := vm.HostGetObjectID(objID, keyID, typeID) - return []wasmer.Value{wasmer.NewI32(ret)}, nil +func (vm *WasmerVM) exportHostStateSet(args []wasmer.Value) ([]wasmer.Value, error) { + keyRef := args[0].I32() + keyLen := args[1].I32() + valRef := args[2].I32() + valLen := args[3].I32() + vm.HostStateSet(keyRef, keyLen, valRef, valLen) + return nil, nil } -func (vm *WasmerVM) exportHostSetBytes(args []wasmer.Value) ([]wasmer.Value, error) { - objID := args[0].I32() - keyID := args[1].I32() - typeID := args[2].I32() - stringRef := args[3].I32() - size := args[4].I32() - vm.HostSetBytes(objID, keyID, typeID, stringRef, size) - return nil, nil +func (vm *WasmerVM) importFunc(nrParams, nrResults int, function func([]wasmer.Value) ([]wasmer.Value, error)) *wasmer.Extern { + params := wasmer.NewValueTypes(wasmerI32Params[:nrParams]...) + results := wasmer.NewValueTypes(wasmerI32Params[:nrResults]...) + funcType := wasmer.NewFunctionType(params, results) + return wasmer.NewFunction(vm.store, funcType, function).IntoExtern() } diff --git a/packages/wasmvm/wasmhost/wasmfunctable.go b/packages/wasmvm/wasmhost/wasmfunctable.go new file mode 100644 index 0000000000..adf45eeb80 --- /dev/null +++ b/packages/wasmvm/wasmhost/wasmfunctable.go @@ -0,0 +1,47 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmhost + +import ( + "github.com/iotaledger/wasp/packages/iscp" +) + +type WasmFuncTable struct { + codeToFunc map[uint32]string + funcToCode map[string]uint32 + funcToIndex map[string]int32 +} + +func NewWasmFuncTable() *WasmFuncTable { + return &WasmFuncTable{ + codeToFunc: make(map[uint32]string), + funcToCode: make(map[string]uint32), + funcToIndex: make(map[string]int32), + } +} + +func (t *WasmFuncTable) FunctionFromCode(code uint32) string { + return t.codeToFunc[code] +} + +func (t *WasmFuncTable) SetExport(index int32, functionName string) { + funcIndex, ok := t.funcToIndex[functionName] + if ok { + // paranoia check + if funcIndex != index { + panic("SetExport: duplicate function name") + } + return + } + + hashedName := uint32(iscp.Hn(functionName)) + _, ok = t.codeToFunc[hashedName] + if ok { + panic("SetExport: duplicate hashed name") + } + + t.codeToFunc[hashedName] = functionName + t.funcToCode[functionName] = hashedName + t.funcToIndex[functionName] = index +} diff --git a/packages/vm/wasmhost/wasmgovm.go b/packages/wasmvm/wasmhost/wasmgovm.go similarity index 76% rename from packages/vm/wasmhost/wasmgovm.go rename to packages/wasmvm/wasmhost/wasmgovm.go index 6e0a7e64ab..abd13da7e5 100644 --- a/packages/vm/wasmhost/wasmgovm.go +++ b/packages/wasmvm/wasmhost/wasmgovm.go @@ -7,7 +7,7 @@ import ( "errors" "strings" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" ) // provide implementation for Wasm-only function @@ -15,20 +15,18 @@ func Connect(h wasmlib.ScHost) wasmlib.ScHost { return wasmlib.ConnectHost(h) } +type ScOnloadFunc func(index int32) + type WasmGoVM struct { WasmVMBase scName string - onLoad func() + onLoad ScOnloadFunc } -func NewWasmGoVM(scName string, onLoad func()) WasmVM { +func NewWasmGoVM(scName string, onLoad ScOnloadFunc) WasmVM { return &WasmGoVM{scName: scName, onLoad: onLoad} } -func (vm *WasmGoVM) NewInstance() WasmVM { - return nil -} - func (vm *WasmGoVM) Instantiate() error { return nil } @@ -49,17 +47,23 @@ func (vm *WasmGoVM) LoadWasm(wasmData []byte) error { return nil } +func (vm *WasmGoVM) NewInstance() WasmVM { + return nil +} + func (vm *WasmGoVM) RunFunction(functionName string, args ...interface{}) error { if functionName == "on_load" { - vm.onLoad() + // note: on_load is funneled through onload() + vm.onLoad(-1) return nil } return errors.New("WasmGoVM: cannot run function: " + functionName) } -func (vm *WasmGoVM) RunScFunction(index int32) error { +func (vm *WasmGoVM) RunScFunction(index int32) (err error) { return vm.Run(func() error { - wasmlib.OnCall(index) + // note: on_call is funneled through onload() + vm.onLoad(index) return nil }) } diff --git a/packages/vm/wasmproc/wasmprocessor.go b/packages/wasmvm/wasmhost/wasmprocessor.go similarity index 51% rename from packages/vm/wasmproc/wasmprocessor.go rename to packages/wasmvm/wasmhost/wasmprocessor.go index d06e8db726..f033d8b062 100644 --- a/packages/vm/wasmproc/wasmprocessor.go +++ b/packages/wasmvm/wasmhost/wasmprocessor.go @@ -1,97 +1,132 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -package wasmproc +package wasmhost import ( + "errors" "sync" "github.com/iotaledger/hive.go/logger" "github.com/iotaledger/wasp/packages/iscp" - "github.com/iotaledger/wasp/packages/vm/wasmhost" ) type WasmProcessor struct { - wasmhost.WasmHost contextLock sync.Mutex contexts map[int32]*WasmContext currentContextID int32 + funcTable *WasmFuncTable + gasFactorX uint64 instanceLock sync.Mutex log *logger.Logger mainProcessor *WasmProcessor nextContextID int32 scContext *WasmContext - wasmVM func() wasmhost.WasmVM + vm WasmVM + wasmVM func() WasmVM } -var _ iscp.VMProcessor = &WasmProcessor{} +var _ iscp.VMProcessor = new(WasmProcessor) -var GoWasmVM func() wasmhost.WasmVM +var GoWasmVM func() WasmVM // GetProcessor creates a new Wasm VM processor. func GetProcessor(wasmBytes []byte, log *logger.Logger) (iscp.VMProcessor, error) { - proc := &WasmProcessor{log: log, contexts: make(map[int32]*WasmContext), wasmVM: wasmhost.NewWasmTimeVM} - proc.Init() + proc := &WasmProcessor{ + contexts: make(map[int32]*WasmContext), + funcTable: NewWasmFuncTable(), + gasFactorX: 1, + log: log, + wasmVM: NewWasmTimeVM, + } - // By default we will use WasmTimeVM, but this can be overruled by setting GoWasmVm + // By default, we will use WasmTimeVM, but this can be overruled by setting GoWasmVm // This setting will also be propagated to all the sub-processors of this processor if GoWasmVM != nil { proc.wasmVM = GoWasmVM GoWasmVM = nil } + proc.vm = proc.wasmVM() // Run setup on main processor, because we will be sharing stuff with the sub-processors - err := proc.InitVM(proc.wasmVM(), proc) + err := proc.vm.LinkHost(proc) if err != nil { return nil, err } proc.scContext = NewWasmContext("", proc) - wasmhost.Connect(proc.scContext) - err = proc.LoadWasm(wasmBytes) + Connect(proc.scContext) + err = proc.vm.LoadWasm(wasmBytes) if err != nil { return nil, err } - err = proc.RunFunction("on_load") + // proc.vm.GasBudget(1_000_000) + // proc.vm.GasDisable(true) + err = proc.vm.RunFunction("on_load") + // proc.vm.GasDisable(false) + // burned := proc.vm.GasBurned() + // _ = burned if err != nil { return nil, err } return proc, nil } +func (proc *WasmProcessor) GetContext(id int32) *WasmContext { + if id == 0 { + id = proc.currentContextID + } + + if id == 0 { + return proc.scContext + } + + mainProcessor := proc.mainProc() + mainProcessor.contextLock.Lock() + defer mainProcessor.contextLock.Unlock() + + return mainProcessor.contexts[id] +} + +func (proc *WasmProcessor) GetDefaultEntryPoint() iscp.VMProcessorEntryPoint { + return proc.wasmContext(FuncDefault) +} + func (proc *WasmProcessor) GetDescription() string { return "Wasm VM smart contract processor" } func (proc *WasmProcessor) GetEntryPoint(code iscp.Hname) (iscp.VMProcessorEntryPoint, bool) { - function := proc.FunctionFromCode(uint32(code)) + function := proc.funcTable.FunctionFromCode(uint32(code)) if function == "" && code != iscp.EntryPointInit { return nil, false } return proc.wasmContext(function), true } -func (proc *WasmProcessor) GetDefaultEntryPoint() iscp.VMProcessorEntryPoint { - return proc.wasmContext(FuncDefault) -} - -func (proc *WasmProcessor) GetKvStore(id int32) *wasmhost.KvStoreHost { - if id == 0 { - id = proc.currentContextID +func (proc *WasmProcessor) getSubProcessor(vmInstance WasmVM) *WasmProcessor { + processor := &WasmProcessor{ + log: proc.log, + mainProcessor: proc, + vm: vmInstance, + wasmVM: proc.wasmVM, } - - if id == 0 { - return &proc.scContext.KvStoreHost + err := processor.vm.LinkHost(processor) + if err != nil { + panic("cannot link: " + err.Error()) } - mainProcessor := proc - if proc.mainProcessor != nil { - mainProcessor = proc.mainProcessor + processor.scContext = NewWasmContext("", processor) + Connect(processor.scContext) + err = processor.vm.Instantiate() + if err != nil { + panic("cannot instantiate: " + err.Error()) } - mainProcessor.contextLock.Lock() - defer mainProcessor.contextLock.Unlock() + return processor +} - return &mainProcessor.contexts[id].KvStoreHost +func (proc *WasmProcessor) IsView(function string) bool { + return (proc.mainProc().funcTable.funcToIndex[function] & 0x8000) != 0 } func (proc *WasmProcessor) KillContext(id int32) { @@ -100,9 +135,29 @@ func (proc *WasmProcessor) KillContext(id int32) { delete(proc.contexts, id) } +func (proc *WasmProcessor) RunScFunction(functionName string) (err error) { + index, ok := proc.mainProc().funcTable.funcToIndex[functionName] + if !ok { + return errors.New("unknown SC function name: " + functionName) + } + return proc.vm.RunScFunction(index) +} + +//nolint:unused +func (proc *WasmProcessor) gasFactor() uint64 { + return proc.mainProc().gasFactorX +} + +func (proc *WasmProcessor) mainProc() *WasmProcessor { + if proc.mainProcessor == nil { + return proc + } + return proc.mainProcessor +} + func (proc *WasmProcessor) wasmContext(function string) *WasmContext { processor := proc - vmInstance := proc.NewInstance() + vmInstance := proc.vm.NewInstance() if vmInstance != nil { processor = proc.getSubProcessor(vmInstance) } @@ -116,26 +171,3 @@ func (proc *WasmProcessor) wasmContext(function string) *WasmContext { proc.contexts[wc.id] = wc return wc } - -func (proc *WasmProcessor) getSubProcessor(vmInstance wasmhost.WasmVM) *WasmProcessor { - processor := &WasmProcessor{log: proc.log, mainProcessor: proc, wasmVM: proc.wasmVM} - processor.Init() - err := processor.InitVM(vmInstance, processor) - if err != nil { - panic("Cannot clone processor: " + err.Error()) - } - - processor.scContext = NewWasmContext("", processor) - wasmhost.Connect(processor.scContext) - err = processor.Instantiate() - if err != nil { - panic("Cannot instantiate: " + err.Error()) - } - - // TODO reuse on_load data from main processor - err = processor.RunFunction("on_load") - if err != nil { - panic("Cannot run on_load: " + err.Error()) - } - return processor -} diff --git a/packages/vm/wasmhost/wasmtimevm.go b/packages/wasmvm/wasmhost/wasmtimevm.go similarity index 60% rename from packages/vm/wasmhost/wasmtimevm.go rename to packages/wasmvm/wasmhost/wasmtimevm.go index 79ee641033..4254ee3f4a 100644 --- a/packages/vm/wasmhost/wasmtimevm.go +++ b/packages/wasmvm/wasmhost/wasmtimevm.go @@ -11,32 +11,91 @@ import ( type WasmTimeVM struct { WasmVMBase - engine *wasmtime.Engine - instance *wasmtime.Instance - interrupt *wasmtime.InterruptHandle - linker *wasmtime.Linker - memory *wasmtime.Memory - module *wasmtime.Module - store *wasmtime.Store + engine *wasmtime.Engine + instance *wasmtime.Instance + interrupt *wasmtime.InterruptHandle + linker *wasmtime.Linker + memory *wasmtime.Memory + module *wasmtime.Module + store *wasmtime.Store + lastBudget uint64 } func NewWasmTimeVM() WasmVM { vm := &WasmTimeVM{} config := wasmtime.NewConfig() config.SetInterruptable(true) + // config.SetConsumeFuel(true) vm.engine = wasmtime.NewEngineWithConfig(config) return vm } -func (vm *WasmTimeVM) NewInstance() WasmVM { - return &WasmTimeVM{engine: vm.engine, module: vm.module} +// GasBudget sets the gas budget for the VM. +func (vm *WasmTimeVM) GasBudget(budget uint64) { + // save budget so we can later determine how much the VM burned + vm.lastBudget = budget + + // new budget for VM, top up to desired budget + err := vm.store.AddFuel(budget) + if err != nil { + panic("GasBudget.set: " + err.Error()) + } + + // consume 0 fuel to determine remaining budget + remainingBudget, err := vm.store.ConsumeFuel(0) + if err != nil { + panic("GasBudget.determine: " + err.Error()) + } + + if remainingBudget > budget { + // burn excess budget + _, err = vm.store.ConsumeFuel(remainingBudget - budget) + if err != nil { + panic("GasBudget.burn: " + err.Error()) + } + } +} + +// GasBurned will return the gas burned since the last time GasBudget() was called +func (vm *WasmTimeVM) GasBurned() uint64 { + // consume 0 fuel to determine remaining budget + remainingBudget, err := vm.store.ConsumeFuel(0) + if err != nil { + panic("GasBurned.determine: " + err.Error()) + } + + burned := vm.lastBudget - remainingBudget + return burned +} + +func (vm *WasmTimeVM) Instantiate() (err error) { + // vm.GasBudget(1_000_000) + // vm.GasDisable(true) + vm.instance, err = vm.linker.Instantiate(vm.store, vm.module) + // vm.GasDisable(false) + // burned := vm.GasBurned() + // _ = burned + if err != nil { + return err + } + memory := vm.instance.GetExport(vm.store, "memory") + if memory == nil { + return errors.New("no memory export") + } + vm.memory = memory.Memory() + if vm.memory == nil { + return errors.New("not a memory type") + } + return nil } func (vm *WasmTimeVM) Interrupt() { vm.interrupt.Interrupt() } -func (vm *WasmTimeVM) LinkHost(impl WasmVM, host *WasmHost) (err error) { +func (vm *WasmTimeVM) LinkHost(proc *WasmProcessor) (err error) { + _ = vm.WasmVMBase.LinkHost(proc) + vm.store = wasmtime.NewStore(vm.engine) vm.interrupt, err = vm.store.InterruptHandle() if err != nil { @@ -44,21 +103,13 @@ func (vm *WasmTimeVM) LinkHost(impl WasmVM, host *WasmHost) (err error) { } vm.linker = wasmtime.NewLinker(vm.engine) - _ = vm.WasmVMBase.LinkHost(impl, host) - err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostGetBytes, vm.HostGetBytes) - if err != nil { - return err - } - err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostGetKeyID, vm.HostGetKeyID) - if err != nil { - return err - } - err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostGetObjectID, vm.HostGetObjectID) + // new Wasm VM interface + err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostStateGet, vm.HostStateGet) if err != nil { return err } - err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostSetBytes, vm.HostSetBytes) + err = vm.linker.DefineFunc(vm.store, ModuleWasmLib, FuncHostStateSet, vm.HostStateSet) if err != nil { return err } @@ -85,20 +136,8 @@ func (vm *WasmTimeVM) LoadWasm(wasmData []byte) (err error) { return vm.Instantiate() } -func (vm *WasmTimeVM) Instantiate() (err error) { - vm.instance, err = vm.linker.Instantiate(vm.store, vm.module) - if err != nil { - return err - } - memory := vm.instance.GetExport(vm.store, "memory") - if memory == nil { - return errors.New("no memory export") - } - vm.memory = memory.Memory() - if vm.memory == nil { - return errors.New("not a memory type") - } - return nil +func (vm *WasmTimeVM) NewInstance() WasmVM { + return &WasmTimeVM{engine: vm.engine, module: vm.module} } func (vm *WasmTimeVM) RunFunction(functionName string, args ...interface{}) error { diff --git a/packages/vm/wasmhost/wasmvm.go b/packages/wasmvm/wasmhost/wasmvm.go similarity index 51% rename from packages/vm/wasmhost/wasmvm.go rename to packages/wasmvm/wasmhost/wasmvm.go index 57055f451a..72aab26229 100644 --- a/packages/vm/wasmhost/wasmvm.go +++ b/packages/wasmvm/wasmhost/wasmvm.go @@ -7,21 +7,22 @@ import ( "encoding/binary" "errors" "fmt" + "strings" "time" + + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" ) const ( - defaultTimeout = 5 * time.Second - FuncAbort = "abort" - FuncFdWrite = "fd_write" - FuncHostGetBytes = "hostGetBytes" - FuncHostGetKeyID = "hostGetKeyID" - FuncHostGetObjectID = "hostGetObjectID" - FuncHostSetBytes = "hostSetBytes" - ModuleEnv = "env" - ModuleWasi1 = "wasi_unstable" - ModuleWasi2 = "wasi_snapshot_preview1" - ModuleWasmLib = "WasmLib" + defaultTimeout = 5 * time.Second + FuncAbort = "abort" + FuncFdWrite = "fd_write" + FuncHostStateGet = "hostStateGet" + FuncHostStateSet = "hostStateSet" + ModuleEnv = "env" + ModuleWasi1 = "wasi_unstable" + ModuleWasi2 = "wasi_snapshot_preview1" + ModuleWasmLib = "WasmLib" ) var ( @@ -31,17 +32,17 @@ var ( // HostTracing turns on debug tracing for ScHost calls HostTracing = false - // HostTracingAll turns on *all* debug tracing for ScHost calls - HostTracingAll = false - // WasmTimeout set this to non-zero for a one-time override of the defaultTimeout WasmTimeout = 0 * time.Second ) type WasmVM interface { + GasBudget(budget uint64) + GasBurned() uint64 + GasDisable(disable bool) Instantiate() error Interrupt() - LinkHost(impl WasmVM, host *WasmHost) error + LinkHost(proc *WasmProcessor) error LoadWasm(wasmData []byte) error NewInstance() WasmVM RunFunction(functionName string, args ...interface{}) error @@ -53,185 +54,171 @@ type WasmVM interface { } type WasmVMBase struct { - impl WasmVM - host *WasmHost + cachedResult []byte + gasDisabled bool panicErr error - result []byte - resultKeyID int32 + proc *WasmProcessor timeoutStarted bool } -// catchPanicMessage is used in every host function to catch any panic. -// It will save the first panic it encounters in the WasmVMBase so that -// the caller of the Wasm function can retrieve the correct error. -// This is a workaround to WasmTime saving the *last* panic instead of -// the first, thereby reporting the wrong panic error sometimes -func (vm *WasmVMBase) catchPanicMessage() { - panicMsg := recover() - if panicMsg == nil { - return - } - if vm.panicErr == nil { - switch msg := panicMsg.(type) { - case error: - vm.panicErr = msg - default: - vm.panicErr = fmt.Errorf("%v", msg) - } - } - // rethrow and let nature run its course... - panic(panicMsg) +func (vm *WasmVMBase) GasBudget(budget uint64) { + // ignore gas budget } -//nolint:unparam -func (vm *WasmVMBase) getKvStore(id int32) *KvStoreHost { - return vm.host.getKvStore(id) +func (vm *WasmVMBase) GasBurned() uint64 { + // burn nothing + return 0 +} + +func (vm *WasmVMBase) GasDisable(disable bool) { + vm.gasDisabled = disable +} + +func (vm *WasmVMBase) getContext(id int32) *WasmContext { + return vm.proc.GetContext(id) } func (vm *WasmVMBase) HostAbort(errMsg, fileName, line, col int32) { - // crude implementation assumes texts to only use ASCII part of UTF-16 + vm.reportGasBurned() + defer vm.wrapUp() - defer vm.catchPanicMessage() + // crude implementation assumes texts to only use ASCII part of UTF-16 + impl := vm.proc.vm // null-terminated UTF-16 error message str1 := make([]byte, 0) - ptr := vm.impl.VMGetBytes(errMsg, 2) + ptr := impl.VMGetBytes(errMsg, 2) for i := errMsg; ptr[0] != 0; i += 2 { str1 = append(str1, ptr[0]) - ptr = vm.impl.VMGetBytes(i, 2) + ptr = impl.VMGetBytes(i, 2) } // null-terminated UTF-16 file name str2 := make([]byte, 0) - ptr = vm.impl.VMGetBytes(fileName, 2) + ptr = impl.VMGetBytes(fileName, 2) for i := fileName; ptr[0] != 0; i += 2 { str2 = append(str2, ptr[0]) - ptr = vm.impl.VMGetBytes(i, 2) + ptr = impl.VMGetBytes(i, 2) } panic(fmt.Sprintf("AssemblyScript panic: %s (%s %d:%d)", string(str1), string(str2), line, col)) } func (vm *WasmVMBase) HostFdWrite(_fd, iovs, _size, written int32) int32 { - defer vm.catchPanicMessage() + vm.reportGasBurned() + defer vm.wrapUp() + + ctx := vm.getContext(0) + ctx.log().Debugf("HostFdWrite(...)") + impl := vm.proc.vm - host := vm.getKvStore(0) - host.TraceAllf("HostFdWrite(...)") // very basic implementation that expects fd to be stdout and iovs to be only one element - ptr := vm.impl.VMGetBytes(iovs, 8) + ptr := impl.VMGetBytes(iovs, 8) text := int32(binary.LittleEndian.Uint32(ptr[0:4])) size := int32(binary.LittleEndian.Uint32(ptr[4:8])) - msg := vm.impl.VMGetBytes(text, size) - fmt.Print(string(msg)) + // msg := vm.impl.VMGetBytes(text, size) + // fmt.Print(string(msg)) ptr = make([]byte, 4) binary.LittleEndian.PutUint32(ptr, uint32(size)) - vm.impl.VMSetBytes(written, size, ptr) + impl.VMSetBytes(written, size, ptr) + + // strip off "panic: " prefix and call sandbox panic function + vm.HostStateGet(0, wasmlib.FnPanic, text+7, size) return size } -func (vm *WasmVMBase) HostGetBytes(objID, keyID, typeID, stringRef, size int32) int32 { - defer vm.catchPanicMessage() +func (vm *WasmVMBase) HostStateGet(keyRef, keyLen, valRef, valLen int32) int32 { + vm.reportGasBurned() + defer vm.wrapUp() - host := vm.getKvStore(0) - host.TraceAllf("HostGetBytes(o%d,k%d,t%d,r%d,s%d)", objID, keyID, typeID, stringRef, size) + ctx := vm.getContext(0) + impl := vm.proc.vm // only check for existence ? - if size < 0 { - if host.Exists(objID, keyID, typeID) { + if valLen < 0 { + key := impl.VMGetBytes(keyRef, keyLen) + if ctx.StateExists(key) { return 0 } // missing key is indicated by -1 return -1 } - // actual GetBytes request ? - if (typeID & OBJTYPE_CALL) == 0 { - bytes := host.GetBytes(objID, keyID, typeID) - if bytes == nil { + // get value for key request, or get cached result request (keyLen == 0) + if keyLen >= 0 { + if keyLen > 0 { + // retrieve value associated with key + key := impl.VMGetBytes(keyRef, keyLen) + vm.cachedResult = ctx.StateGet(key) + } + if vm.cachedResult == nil { return -1 } - return vm.impl.VMSetBytes(stringRef, size, bytes) + return impl.VMSetBytes(valRef, valLen, vm.cachedResult) } - // func call request - switch typeID { - case OBJTYPE_CALL: - // func call with params, returns result length - vm.resultKeyID = keyID - params := vm.impl.VMGetBytes(stringRef, size) - vm.result = host.CallFunc(objID, keyID, params) - return int32(len(vm.result)) - - case OBJTYPE_CALL + 1: - // retrieve previous func call result - if vm.resultKeyID == keyID { - result := vm.result - vm.result = nil - vm.resultKeyID = 0 - if result == nil { - return -1 - } - return vm.impl.VMSetBytes(stringRef, int32(len(result)), result) - } - } - panic("HostGetBytes: Invalid func call state") + // sandbox func call request, keyLen is func nr + params := impl.VMGetBytes(valRef, valLen) + vm.cachedResult = ctx.Sandbox(keyLen, params) + return int32(len(vm.cachedResult)) } -func (vm *WasmVMBase) HostGetKeyID(keyRef, size int32) int32 { - defer vm.catchPanicMessage() - - host := vm.getKvStore(0) - host.TraceAllf("HostGetKeyID(r%d,s%d)", keyRef, size) - // non-negative size means original key was a string - if size >= 0 { - bytes := vm.impl.VMGetBytes(keyRef, size) - return host.GetKeyIDFromString(string(bytes)) - } +func (vm *WasmVMBase) HostStateSet(keyRef, keyLen, valRef, valLen int32) { + vm.reportGasBurned() + defer vm.wrapUp() - // negative size means original key was a byte slice - bytes := vm.impl.VMGetBytes(keyRef, -size-1) - return host.GetKeyIDFromBytes(bytes) -} + ctx := vm.getContext(0) + impl := vm.proc.vm -func (vm *WasmVMBase) HostGetObjectID(objID, keyID, typeID int32) int32 { - defer vm.catchPanicMessage() - - host := vm.getKvStore(0) - host.TraceAllf("HostGetObjectID(o%d,k%d,t%d)", objID, keyID, typeID) - return host.GetObjectID(objID, keyID, typeID) -} - -func (vm *WasmVMBase) HostSetBytes(objID, keyID, typeID, stringRef, size int32) { - defer vm.catchPanicMessage() + // export name? + if keyRef == 0 { + name := string(impl.VMGetBytes(valRef, valLen)) + if keyLen < 0 { + // ExportWasmTag, log the wasm tag name + if strings.Contains(name, "TYPESCRIPT") { + ctx.proc.gasFactorX = 10 + } + ctx.proc.log.Infof(name) + return + } + ctx.ExportName(keyLen, name) + return + } - host := vm.getKvStore(0) - host.TraceAllf("HostSetBytes(o%d,k%d,t%d,r%d,s%d)", objID, keyID, typeID, stringRef, size) + key := impl.VMGetBytes(keyRef, keyLen) // delete key ? - if size < 0 { - host.DelKey(objID, keyID, typeID) + if valLen < 0 { + ctx.StateDelete(key) return } - bytes := vm.impl.VMGetBytes(stringRef, size) - host.SetBytes(objID, keyID, typeID, bytes) + // set key + value := impl.VMGetBytes(valRef, valLen) + ctx.StateSet(key, value) } func (vm *WasmVMBase) Instantiate() error { return errors.New("cannot be cloned") } -func (vm *WasmVMBase) LinkHost(impl WasmVM, host *WasmHost) error { +func (vm *WasmVMBase) LinkHost(proc *WasmProcessor) error { // trick vm into thinking it doesn't have to start the timeout timer // useful when debugging to prevent timing out on breakpoints vm.timeoutStarted = DisableWasmTimeout - vm.impl = impl - vm.host = host - host.vm = impl + vm.proc = proc return nil } +// reportGasBurned updates the sandbox gas budget with the amount burned by the VM +func (vm *WasmVMBase) reportGasBurned() { + // if !vm.gasDisabled { + // ctx := vm.proc.GetContext(0) + // ctx.GasBurned(vm.proc.vm.GasBurned() / vm.proc.gasFactor()) + // } +} + func (vm *WasmVMBase) Run(runner func() error) (err error) { defer func() { r := recover() @@ -253,6 +240,9 @@ func (vm *WasmVMBase) Run(runner func() error) (err error) { err = vm.panicErr vm.panicErr = nil } + if err != nil && strings.Contains(err.Error(), "all fuel consumed") { + err = errors.New("gas budget exceeded in Wasm VM") + } return err } @@ -270,7 +260,7 @@ func (vm *WasmVMBase) Run(runner func() error) (err error) { case <-done: // runner was done before timeout case <-time.After(timeout): // timeout: interrupt Wasm - vm.impl.Interrupt() + vm.proc.vm.Interrupt() // wait for runner to finish <-done } @@ -284,25 +274,60 @@ func (vm *WasmVMBase) Run(runner func() error) (err error) { err = vm.panicErr vm.panicErr = nil } + if err != nil && strings.Contains(err.Error(), "all fuel consumed") { + err = errors.New("gas budget exceeded in Wasm VM") + } return err } func (vm *WasmVMBase) VMGetBytes(offset, size int32) []byte { - ptr := vm.impl.UnsafeMemory() + ptr := vm.proc.vm.UnsafeMemory() bytes := make([]byte, size) copy(bytes, ptr[offset:offset+size]) return bytes } func (vm *WasmVMBase) VMGetSize() int32 { - ptr := vm.impl.UnsafeMemory() + ptr := vm.proc.vm.UnsafeMemory() return int32(len(ptr)) } func (vm *WasmVMBase) VMSetBytes(offset, size int32, bytes []byte) int32 { if size != 0 { - ptr := vm.impl.UnsafeMemory() + ptr := vm.proc.vm.UnsafeMemory() copy(ptr[offset:offset+size], bytes) } return int32(len(bytes)) } + +// wrapUp is used in every host function to catch any panic. +// It will save the first panic it encounters in the WasmVMBase so that +// the caller of the Wasm function can retrieve the correct error. +// This is a workaround to WasmTime saving the *last* panic instead of +// the first, thereby reporting the wrong panic error sometimes +// wrapUp will also update the Wasm code that initiated the call with +// the remaining gas budget (the Wasp node may have burned some) +func (vm *WasmVMBase) wrapUp() { + panicMsg := recover() + if panicMsg == nil { + // if !vm.gasDisabled { + // // update VM gas budget to reflect what sandbox burned + // ctx := vm.getContext(0) + // vm.proc.vm.GasBudget(ctx.GasBudget() * vm.proc.gasFactor()) + // } + return + } + + // panic means no need to update gas budget + if vm.panicErr == nil { + switch msg := panicMsg.(type) { + case error: + vm.panicErr = msg + default: + vm.panicErr = fmt.Errorf("%v", msg) + } + } + + // rethrow and let nature run its course... + panic(panicMsg) +} diff --git a/packages/wasmvm/wasmlib/Cargo.lock b/packages/wasmvm/wasmlib/Cargo.lock new file mode 100644 index 0000000000..fbada2ac38 --- /dev/null +++ b/packages/wasmvm/wasmlib/Cargo.lock @@ -0,0 +1,250 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bumpalo" +version = "3.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen", +] + +[[package]] +name = "js-sys" +version = "0.3.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a38fc24e30fd564ce974c02bf1d337caddff65be6cc4735a1f7eab22a7440f04" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.116" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "565dbd88872dbe4cc8a46e527f26483c1d1f7afa6b884a3bd6cd893d4f98da74" + +[[package]] +name = "log" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "memory_units" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" + +[[package]] +name = "proc-macro2" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "scoped-tls" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" + +[[package]] +name = "syn" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "unicode-xid" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "wasm-bindgen" +version = "0.2.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f1af7423d8588a3d840681122e72e6a24ddbcb3f0ec385cac0d12d24256c06" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b21c0df030f5a177f3cba22e9bc4322695ec43e7257d865302900290bcdedca" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eb6ec270a31b1d3c7e266b999739109abce8b6c87e4b31fcfcd788b65267395" +dependencies = [ + "cfg-if 1.0.0", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4203d69e40a52ee523b2529a773d5ffc1dc0071801c87b3d270b471b80ed01" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa8a30d46208db204854cadbb5d4baf5fcf8071ba5bf48190c3e59937962ebc" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d958d035c4438e28c70e4321a2911302f10135ce78a9c7834c0cab4123d06a2" + +[[package]] +name = "wasm-bindgen-test" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45c8d417d87eefa0087e62e3c75ad086be39433449e2961add9a5d9ce5acc2f1" +dependencies = [ + "console_error_panic_hook", + "js-sys", + "scoped-tls", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0e560d44db5e73b69a9757a15512fe7e1ef93ed2061c928871a4025798293dd" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "wasmlib" +version = "0.1.0" +dependencies = [ + "console_error_panic_hook", + "wasm-bindgen", + "wasm-bindgen-test", + "wee_alloc", +] + +[[package]] +name = "web-sys" +version = "0.3.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c060b319f29dd25724f09a2ba1418f142f539b2be99fbf4d2d5a8f7330afb8eb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wee_alloc" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "memory_units", + "winapi", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/packages/vm/wasmlib/Cargo.toml b/packages/wasmvm/wasmlib/Cargo.toml similarity index 100% rename from packages/vm/wasmlib/Cargo.toml rename to packages/wasmvm/wasmlib/Cargo.toml diff --git a/packages/vm/wasmlib/LICENSE b/packages/wasmvm/wasmlib/LICENSE similarity index 100% rename from packages/vm/wasmlib/LICENSE rename to packages/wasmvm/wasmlib/LICENSE diff --git a/packages/vm/wasmlib/README.md b/packages/wasmvm/wasmlib/README.md similarity index 100% rename from packages/vm/wasmlib/README.md rename to packages/wasmvm/wasmlib/README.md diff --git a/packages/vm/wasmlib/go/wasmclient/arguments.go b/packages/wasmvm/wasmlib/go/wasmclient/arguments.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/arguments.go rename to packages/wasmvm/wasmlib/go/wasmclient/arguments.go diff --git a/packages/vm/wasmlib/go/wasmclient/clientfunc.go b/packages/wasmvm/wasmlib/go/wasmclient/clientfunc.go similarity index 87% rename from packages/vm/wasmlib/go/wasmclient/clientfunc.go rename to packages/wasmvm/wasmlib/go/wasmclient/clientfunc.go index 07654bbc88..82ab514548 100644 --- a/packages/vm/wasmlib/go/wasmclient/clientfunc.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/clientfunc.go @@ -3,11 +3,11 @@ package wasmclient -import "github.com/iotaledger/hive.go/crypto/ed25519" +import cryptolib "github.com/iotaledger/hive.go/crypto/ed25519" type ClientFunc struct { svc *Service - keyPair *ed25519.KeyPair + keyPair *cryptolib.KeyPair onLedger bool xfer *Transfer } @@ -32,7 +32,7 @@ func (f *ClientFunc) Post(hFuncName uint32, args *Arguments) Request { } // Sign optionally overrides the default keypair from the service -func (f *ClientFunc) Sign(keyPair *ed25519.KeyPair) { +func (f *ClientFunc) Sign(keyPair *cryptolib.KeyPair) { f.keyPair = keyPair } diff --git a/packages/vm/wasmlib/go/wasmclient/clientview.go b/packages/wasmvm/wasmlib/go/wasmclient/clientview.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/clientview.go rename to packages/wasmvm/wasmlib/go/wasmclient/clientview.go diff --git a/packages/vm/wasmlib/go/wasmclient/coreaccounts/service.go b/packages/wasmvm/wasmlib/go/wasmclient/coreaccounts/service.go similarity index 97% rename from packages/vm/wasmlib/go/wasmclient/coreaccounts/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/coreaccounts/service.go index 269b5a35ed..8a87a834fe 100644 --- a/packages/vm/wasmlib/go/wasmclient/coreaccounts/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/coreaccounts/service.go @@ -7,7 +7,7 @@ package coreaccountsclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgAgentID = "a" @@ -171,7 +171,7 @@ type CoreAccountsService struct { func NewCoreAccountsService(cl *wasmclient.ServiceClient, chainID string) (*CoreAccountsService, error) { s := &CoreAccountsService{} - err := s.Service.Init(cl, chainID, 0x3c4b5e02, nil) + err := s.Service.Init(cl, chainID, 0x3c4b5e02) return s, err } diff --git a/packages/vm/wasmlib/go/wasmclient/coreblob/service.go b/packages/wasmvm/wasmlib/go/wasmclient/coreblob/service.go similarity index 96% rename from packages/vm/wasmlib/go/wasmclient/coreblob/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/coreblob/service.go index 208046b63e..a2152dcf0e 100644 --- a/packages/vm/wasmlib/go/wasmclient/coreblob/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/coreblob/service.go @@ -7,7 +7,7 @@ package coreblobclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgBlobs = "this" @@ -124,7 +124,7 @@ type CoreBlobService struct { func NewCoreBlobService(cl *wasmclient.ServiceClient, chainID string) (*CoreBlobService, error) { s := &CoreBlobService{} - err := s.Service.Init(cl, chainID, 0xfd91bc63, nil) + err := s.Service.Init(cl, chainID, 0xfd91bc63) return s, err } diff --git a/packages/vm/wasmlib/go/wasmclient/coreblocklog/service.go b/packages/wasmvm/wasmlib/go/wasmclient/coreblocklog/service.go similarity index 87% rename from packages/vm/wasmlib/go/wasmclient/coreblocklog/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/coreblocklog/service.go index ff8101b85f..2dd01e960d 100644 --- a/packages/vm/wasmlib/go/wasmclient/coreblocklog/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/coreblocklog/service.go @@ -7,7 +7,7 @@ package coreblocklogclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgBlockIndex = "n" @@ -42,8 +42,8 @@ type ControlAddressesResults struct { res wasmclient.Results } -func (r *ControlAddressesResults) BlockIndex() int32 { - return r.res.ToInt32(r.res.Get(ResBlockIndex)) +func (r *ControlAddressesResults) BlockIndex() uint32 { + return r.res.ToUint32(r.res.Get(ResBlockIndex)) } func (r *ControlAddressesResults) GoverningAddress() wasmclient.Address { @@ -61,8 +61,8 @@ type GetBlockInfoView struct { args wasmclient.Arguments } -func (f *GetBlockInfoView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *GetBlockInfoView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } func (f *GetBlockInfoView) Call() GetBlockInfoResults { @@ -86,8 +86,8 @@ type GetEventsForBlockView struct { args wasmclient.Arguments } -func (f *GetEventsForBlockView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *GetEventsForBlockView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } func (f *GetEventsForBlockView) Call() GetEventsForBlockResults { @@ -115,12 +115,12 @@ func (f *GetEventsForContractView) ContractHname(v wasmclient.Hname) { f.args.Set(ArgContractHname, f.args.FromHname(v)) } -func (f *GetEventsForContractView) FromBlock(v int32) { - f.args.Set(ArgFromBlock, f.args.FromInt32(v)) +func (f *GetEventsForContractView) FromBlock(v uint32) { + f.args.Set(ArgFromBlock, f.args.FromUint32(v)) } -func (f *GetEventsForContractView) ToBlock(v int32) { - f.args.Set(ArgToBlock, f.args.FromInt32(v)) +func (f *GetEventsForContractView) ToBlock(v uint32) { + f.args.Set(ArgToBlock, f.args.FromUint32(v)) } func (f *GetEventsForContractView) Call() GetEventsForContractResults { @@ -177,8 +177,8 @@ type GetLatestBlockInfoResults struct { res wasmclient.Results } -func (r *GetLatestBlockInfoResults) BlockIndex() int32 { - return r.res.ToInt32(r.res.Get(ResBlockIndex)) +func (r *GetLatestBlockInfoResults) BlockIndex() uint32 { + return r.res.ToUint32(r.res.Get(ResBlockIndex)) } func (r *GetLatestBlockInfoResults) BlockInfo() []byte { @@ -192,8 +192,8 @@ type GetRequestIDsForBlockView struct { args wasmclient.Arguments } -func (f *GetRequestIDsForBlockView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *GetRequestIDsForBlockView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } func (f *GetRequestIDsForBlockView) Call() GetRequestIDsForBlockResults { @@ -231,12 +231,12 @@ type GetRequestReceiptResults struct { res wasmclient.Results } -func (r *GetRequestReceiptResults) BlockIndex() int32 { - return r.res.ToInt32(r.res.Get(ResBlockIndex)) +func (r *GetRequestReceiptResults) BlockIndex() uint32 { + return r.res.ToUint32(r.res.Get(ResBlockIndex)) } -func (r *GetRequestReceiptResults) RequestIndex() int16 { - return r.res.ToInt16(r.res.Get(ResRequestIndex)) +func (r *GetRequestReceiptResults) RequestIndex() uint16 { + return r.res.ToUint16(r.res.Get(ResRequestIndex)) } func (r *GetRequestReceiptResults) RequestRecord() []byte { @@ -250,8 +250,8 @@ type GetRequestReceiptsForBlockView struct { args wasmclient.Arguments } -func (f *GetRequestReceiptsForBlockView) BlockIndex(v int32) { - f.args.Set(ArgBlockIndex, f.args.FromInt32(v)) +func (f *GetRequestReceiptsForBlockView) BlockIndex(v uint32) { + f.args.Set(ArgBlockIndex, f.args.FromUint32(v)) } func (f *GetRequestReceiptsForBlockView) Call() GetRequestReceiptsForBlockResults { @@ -301,7 +301,7 @@ type CoreBlockLogService struct { func NewCoreBlockLogService(cl *wasmclient.ServiceClient, chainID string) (*CoreBlockLogService, error) { s := &CoreBlockLogService{} - err := s.Service.Init(cl, chainID, 0xf538ef2b, nil) + err := s.Service.Init(cl, chainID, 0xf538ef2b) return s, err } diff --git a/packages/vm/wasmlib/go/wasmclient/coregovernance/service.go b/packages/wasmvm/wasmlib/go/wasmclient/coregovernance/service.go similarity index 98% rename from packages/vm/wasmlib/go/wasmclient/coregovernance/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/coregovernance/service.go index a3f5add5f3..da83a5ce03 100644 --- a/packages/vm/wasmlib/go/wasmclient/coregovernance/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/coregovernance/service.go @@ -7,7 +7,7 @@ package coregovernanceclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgChainOwner = "oi" @@ -321,7 +321,7 @@ type CoreGovernanceService struct { func NewCoreGovernanceService(cl *wasmclient.ServiceClient, chainID string) (*CoreGovernanceService, error) { s := &CoreGovernanceService{} - err := s.Service.Init(cl, chainID, 0x17cf909f, nil) + err := s.Service.Init(cl, chainID, 0x17cf909f) return s, err } diff --git a/packages/vm/wasmlib/go/wasmclient/coreroot/service.go b/packages/wasmvm/wasmlib/go/wasmclient/coreroot/service.go similarity index 97% rename from packages/vm/wasmlib/go/wasmclient/coreroot/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/coreroot/service.go index 735d0e0968..2227a7b9ad 100644 --- a/packages/vm/wasmlib/go/wasmclient/coreroot/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/coreroot/service.go @@ -7,7 +7,7 @@ package corerootclient -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( ArgDeployer = "dp" @@ -138,7 +138,7 @@ type CoreRootService struct { func NewCoreRootService(cl *wasmclient.ServiceClient, chainID string) (*CoreRootService, error) { s := &CoreRootService{} - err := s.Service.Init(cl, chainID, 0xcebf5908, nil) + err := s.Service.Init(cl, chainID, 0xcebf5908) return s, err } diff --git a/packages/vm/wasmlib/go/wasmclient/decoder.go b/packages/wasmvm/wasmlib/go/wasmclient/decoder.go similarity index 96% rename from packages/vm/wasmlib/go/wasmclient/decoder.go rename to packages/wasmvm/wasmlib/go/wasmclient/decoder.go index 11d17e749f..3bf828b445 100644 --- a/packages/vm/wasmlib/go/wasmclient/decoder.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/decoder.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package wasmclient import "encoding/binary" diff --git a/packages/vm/wasmlib/go/wasmclient/encoder.go b/packages/wasmvm/wasmlib/go/wasmclient/encoder.go similarity index 96% rename from packages/vm/wasmlib/go/wasmclient/encoder.go rename to packages/wasmvm/wasmlib/go/wasmclient/encoder.go index 3f4ce6f227..53fbeb8e79 100644 --- a/packages/vm/wasmlib/go/wasmclient/encoder.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/encoder.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package wasmclient import "encoding/binary" diff --git a/packages/vm/wasmlib/go/wasmclient/event.go b/packages/wasmvm/wasmlib/go/wasmclient/event.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/event.go rename to packages/wasmvm/wasmlib/go/wasmclient/event.go diff --git a/packages/vm/wasmlib/go/wasmclient/request.go b/packages/wasmvm/wasmlib/go/wasmclient/request.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/request.go rename to packages/wasmvm/wasmlib/go/wasmclient/request.go diff --git a/packages/vm/wasmlib/go/wasmclient/results.go b/packages/wasmvm/wasmlib/go/wasmclient/results.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/results.go rename to packages/wasmvm/wasmlib/go/wasmclient/results.go diff --git a/packages/vm/wasmlib/go/wasmclient/seed.go b/packages/wasmvm/wasmlib/go/wasmclient/seed.go similarity index 89% rename from packages/vm/wasmlib/go/wasmclient/seed.go rename to packages/wasmvm/wasmlib/go/wasmclient/seed.go index 6c5cc8a7c4..c2b7abfadb 100644 --- a/packages/vm/wasmlib/go/wasmclient/seed.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/seed.go @@ -5,7 +5,7 @@ package wasmclient import ( "github.com/iotaledger/goshimmer/client/wallet/packages/seed" - "github.com/iotaledger/hive.go/crypto/ed25519" + cryptolib "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/wasp/packages/iscp" "github.com/mr-tron/base58" ) @@ -39,7 +39,7 @@ func SeedToAgentID(mySeed string, index uint64) AgentID { return AgentID(base58.Encode(agentID.Bytes())) } -func SeedToKeyPair(mySeed string, index uint64) *ed25519.KeyPair { +func SeedToKeyPair(mySeed string, index uint64) *cryptolib.KeyPair { seedBytes, err := base58.Decode(mySeed) if err != nil { panic(err) diff --git a/packages/vm/wasmlib/go/wasmclient/service.go b/packages/wasmvm/wasmlib/go/wasmclient/service.go similarity index 74% rename from packages/vm/wasmlib/go/wasmclient/service.go rename to packages/wasmvm/wasmlib/go/wasmclient/service.go index fbd0a6778b..57c4d32a62 100644 --- a/packages/vm/wasmlib/go/wasmclient/service.go +++ b/packages/wasmvm/wasmlib/go/wasmclient/service.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/iotaledger/hive.go/crypto/ed25519" + cryptolib "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/wasp/client" "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/iscp/colored" @@ -36,25 +36,26 @@ func (m ResMap) Get(key string) []byte { return m[kv.Key(key)] } +type IEventHandler interface { + CallHandler(topic string, params []string) +} + type Service struct { - chainID *iscp.ChainID - keyPair *ed25519.KeyPair - scHname iscp.Hname - waspClient *client.WaspClient + chainID *iscp.ChainID + eventHandlers []IEventHandler + keyPair *cryptolib.KeyPair + scHname iscp.Hname + waspClient *client.WaspClient } -func (s *Service) Init(svcClient *ServiceClient, chainID string, scHname uint32, eventHandlers map[string]func([]string)) (err error) { +func (s *Service) Init(svcClient *ServiceClient, chainID string, scHname uint32) (err error) { s.waspClient = svcClient.waspClient s.scHname = iscp.Hname(scHname) s.chainID, err = iscp.ChainIDFromString(chainID) if err != nil { return err } - if len(eventHandlers) != 0 { - // TODO allow user to specify event handlers for core contracts? - return s.startEventHandlers(svcClient.eventPort, eventHandlers) - } - return nil + return s.startEventHandlers(svcClient.eventPort) } func (s *Service) AsClientFunc() ClientFunc { @@ -73,7 +74,7 @@ func (s *Service) CallView(viewName string, args ArgMap) (ResMap, error) { return ResMap(res), nil } -func (s *Service) PostRequest(hFuncName uint32, args ArgMap, transfer *Transfer, keyPair *ed25519.KeyPair, onLedger bool) Request { +func (s *Service) PostRequest(hFuncName uint32, args ArgMap, transfer *Transfer, keyPair *cryptolib.KeyPair, onLedger bool) Request { bal, err := makeBalances(transfer) if err != nil { return Request{err: err} @@ -98,25 +99,43 @@ func (s *Service) PostRequest(hFuncName uint32, args ArgMap, transfer *Transfer, return Request{id: &id} } -func (s *Service) postRequestOnLedger(hFuncName uint32, args requestargs.RequestArgs, bal colored.Balances, pair *ed25519.KeyPair) Request { +func (s *Service) postRequestOnLedger(hFuncName uint32, args requestargs.RequestArgs, bal colored.Balances, pair *cryptolib.KeyPair) Request { // TODO implement return Request{} } +func (s *Service) Register(handler IEventHandler) { + for _, h := range s.eventHandlers { + if h == handler { + return + } + } + s.eventHandlers = append(s.eventHandlers, handler) +} + // overrides default contract name func (s *Service) ServiceContractName(contractName string) { s.scHname = iscp.Hn(contractName) } -func (s *Service) SignRequests(keyPair *ed25519.KeyPair) { +func (s *Service) SignRequests(keyPair *cryptolib.KeyPair) { s.keyPair = keyPair } +func (s *Service) Unegister(handler IEventHandler) { + for i, h := range s.eventHandlers { + if h == handler { + s.eventHandlers = append(s.eventHandlers[:i], s.eventHandlers[i+1:]...) + return + } + } +} + func (s *Service) WaitRequest(req Request) error { return s.waspClient.WaitUntilRequestProcessed(s.chainID, *req.id, 1*time.Minute) } -func (s *Service) startEventHandlers(eventPort string, handlers map[string]func([]string)) error { +func (s *Service) startEventHandlers(eventPort string) error { chMsg := make(chan []string, 20) chDone := make(chan bool) err := subscribe.Subscribe(eventPort, chMsg, chDone, true, "") @@ -130,9 +149,10 @@ func (s *Service) startEventHandlers(eventPort string, handlers map[string]func( fmt.Printf("%s\n", event) if msgSplit[0] == "vmmsg" { msg := strings.Split(msgSplit[3], "|") - handler, ok := handlers[msg[0]] - if ok { - handler(msg[1:]) + topic := msg[0] + params := msg[1:] + for _, handler := range s.eventHandlers { + handler.CallHandler(topic, params) } } } diff --git a/packages/vm/wasmlib/go/wasmclient/serviceclient.go b/packages/wasmvm/wasmlib/go/wasmclient/serviceclient.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/serviceclient.go rename to packages/wasmvm/wasmlib/go/wasmclient/serviceclient.go diff --git a/packages/vm/wasmlib/go/wasmclient/transfer.go b/packages/wasmvm/wasmlib/go/wasmclient/transfer.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/transfer.go rename to packages/wasmvm/wasmlib/go/wasmclient/transfer.go diff --git a/packages/vm/wasmlib/go/wasmclient/types.go b/packages/wasmvm/wasmlib/go/wasmclient/types.go similarity index 100% rename from packages/vm/wasmlib/go/wasmclient/types.go rename to packages/wasmvm/wasmlib/go/wasmclient/types.go diff --git a/packages/wasmvm/wasmlib/go/wasmclient/wasmrequests/service.go b/packages/wasmvm/wasmlib/go/wasmclient/wasmrequests/service.go new file mode 100644 index 0000000000..5553665021 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmclient/wasmrequests/service.go @@ -0,0 +1,8 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package wasmrequestsclient diff --git a/packages/wasmvm/wasmlib/go/wasmlib/assets.go b/packages/wasmvm/wasmlib/go/wasmlib/assets.go new file mode 100644 index 0000000000..4d3c14ba18 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/assets.go @@ -0,0 +1,109 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "sort" + + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type ScAssets map[wasmtypes.ScColor]uint64 + +func NewScAssetsFromBytes(buf []byte) ScAssets { + if len(buf) == 0 { + return make(ScAssets) + } + dec := wasmtypes.NewWasmDecoder(buf) + size := wasmtypes.Uint32FromBytes(dec.FixedBytes(wasmtypes.ScUint32Length)) + dict := make(ScAssets, size) + for i := uint32(0); i < size; i++ { + color := wasmtypes.ColorDecode(dec) + dict[color] = wasmtypes.Uint64FromBytes(dec.FixedBytes(wasmtypes.ScUint64Length)) + } + return dict +} + +func (a ScAssets) Bytes() []byte { + keys := make([]wasmtypes.ScColor, 0, len(a)) + for key := range a { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { + return string(keys[i].Bytes()) < string(keys[j].Bytes()) + }) + enc := wasmtypes.NewWasmEncoder() + enc.FixedBytes(wasmtypes.Uint32ToBytes(uint32(len(keys))), wasmtypes.ScUint32Length) + for _, color := range keys { + wasmtypes.ColorEncode(enc, color) + enc.FixedBytes(wasmtypes.Uint64ToBytes(a[color]), wasmtypes.ScUint64Length) + } + return enc.Buf() +} + +func (a ScAssets) Balances() ScBalances { + return ScBalances{assets: a} +} + +type ScBalances struct { + assets ScAssets +} + +func (b ScBalances) Balance(color wasmtypes.ScColor) uint64 { + return b.assets[color] +} + +func (b ScBalances) Colors() []wasmtypes.ScColor { + res := make([]wasmtypes.ScColor, 0, len(b.assets)) + for color := range b.assets { + res = append(res, color) + } + return res +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScTransfers ScAssets + +// create a new transfers object ready to add token transfers +func NewScTransfers() ScTransfers { + return make(ScTransfers) +} + +// create a new transfers object from a balances object +func NewScTransfersFromBalances(balances ScBalances) ScTransfers { + transfer := NewScTransfers() + colors := balances.Colors() + for _, color := range colors { + transfer.Set(color, balances.Balance(color)) + } + return transfer +} + +// create a new transfers object and initialize it with the specified amount of iotas +func NewScTransferIotas(amount uint64) ScTransfers { + return NewScTransfer(wasmtypes.IOTA, amount) +} + +// create a new transfers object and initialize it with the specified token transfer +func NewScTransfer(color wasmtypes.ScColor, amount uint64) ScTransfers { + transfer := NewScTransfers() + transfer.Set(color, amount) + return transfer +} + +func (t ScTransfers) IsEmpty() bool { + for _, val := range t { + if val != 0 { + return false + } + } + return true +} + +// set the specified colored token transfer in the transfers object +// note that this will overwrite any previous amount for the specified color +func (t ScTransfers) Set(color wasmtypes.ScColor, amount uint64) { + t[color] = amount +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/context.go b/packages/wasmvm/wasmlib/go/wasmlib/context.go new file mode 100644 index 0000000000..acb1297bf0 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/context.go @@ -0,0 +1,53 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// encapsulates standard host entities into a simple interface + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract func sandbox interface +type ScFuncContext struct { + ScSandboxFunc +} + +var _ ScFuncCallContext = &ScFuncContext{} + +func (ctx ScFuncContext) Host() ScHost { + return nil +} + +func (ctx ScFuncContext) InitFuncCallContext() { +} + +func (ctx ScFuncContext) InitViewCallContext(hContract wasmtypes.ScHname) wasmtypes.ScHname { + return hContract +} + +// TODO deprecated +func (ctx ScFuncContext) Incoming() ScBalances { + return ctx.IncomingTransfer() +} + +// TODO deprecated +func (ctx ScFuncContext) TransferToAddress(address wasmtypes.ScAddress, transfer ScTransfers) { + ctx.Send(address, transfer) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract view sandbox interface +type ScViewContext struct { + ScSandboxView +} + +var _ ScViewCallContext = &ScViewContext{} + +func (ctx ScViewContext) InitViewCallContext(hContract wasmtypes.ScHname) wasmtypes.ScHname { + return hContract +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/contract.go new file mode 100644 index 0000000000..eec25fb1d5 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/contract.go @@ -0,0 +1,168 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type ScFuncCallContext interface { + ChainID() wasmtypes.ScChainID + InitFuncCallContext() +} + +type ScViewCallContext interface { + InitViewCallContext(hContract wasmtypes.ScHname) wasmtypes.ScHname +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScView struct { + hContract wasmtypes.ScHname + hFunction wasmtypes.ScHname + params *ScDict + resultsProxy *wasmtypes.Proxy +} + +func NewScView(ctx ScViewCallContext, hContract, hFunction wasmtypes.ScHname) *ScView { + // allow context to override default hContract + hContract = ctx.InitViewCallContext(hContract) + v := new(ScView) + v.initView(hContract, hFunction) + return v +} + +func NewCallParamsProxy(v *ScView) wasmtypes.Proxy { + v.params = NewScDict() + return v.params.AsProxy() +} + +func NewCallResultsProxy(v *ScView, resultsProxy *wasmtypes.Proxy) { + v.resultsProxy = resultsProxy +} + +func (v *ScView) Call() { + v.call(nil) +} + +func (v *ScView) call(transfer ScAssets) { + req := wasmrequests.CallRequest{ + Contract: v.hContract, + Function: v.hFunction, + Params: v.params.Bytes(), + Transfer: transfer.Bytes(), + } + res := Sandbox(FnCall, req.Bytes()) + if v.resultsProxy != nil { + *v.resultsProxy = wasmtypes.NewProxy(NewScDictFromBytes(res)) + } +} + +func (v *ScView) initView(hContract, hFunction wasmtypes.ScHname) { + v.hContract = hContract + v.hFunction = hFunction +} + +func (v *ScView) OfContract(hContract wasmtypes.ScHname) *ScView { + v.hContract = hContract + return v +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScInitFunc struct { + ScView +} + +func NewScInitFunc(ctx ScFuncCallContext, hContract, hFunction wasmtypes.ScHname) *ScInitFunc { + f := new(ScInitFunc) + f.initView(hContract, hFunction) + if ctx != nil { + ctx.InitFuncCallContext() + } + return f +} + +func (f *ScInitFunc) Call() { + Panic("cannot call init") +} + +func (f *ScInitFunc) OfContract(hContract wasmtypes.ScHname) *ScInitFunc { + f.hContract = hContract + return f +} + +func (f *ScInitFunc) Params() []interface{} { + var params []interface{} + for k, v := range f.params.dict { + params = append(params, k) + params = append(params, v) + } + return params +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScFunc struct { + ScView + ctx ScFuncCallContext + delay uint32 + transfer ScAssets +} + +func NewScFunc(ctx ScFuncCallContext, hContract, hFunction wasmtypes.ScHname) *ScFunc { + ctx.InitFuncCallContext() + f := new(ScFunc) + f.ctx = ctx + f.initView(hContract, hFunction) + return f +} + +func (f *ScFunc) Call() { + if f.delay != 0 { + Panic("cannot delay a call") + } + f.call(f.transfer) +} + +func (f *ScFunc) Delay(seconds uint32) *ScFunc { + f.delay = seconds + return f +} + +func (f *ScFunc) OfContract(hContract wasmtypes.ScHname) *ScFunc { + f.hContract = hContract + return f +} + +func (f *ScFunc) Post() { + f.PostToChain(f.ctx.ChainID()) +} + +func (f *ScFunc) PostToChain(chainID wasmtypes.ScChainID) { + req := wasmrequests.PostRequest{ + ChainID: chainID, + Contract: f.hContract, + Function: f.hFunction, + Params: f.params.Bytes(), + Transfer: f.transfer.Bytes(), + Delay: f.delay, + } + res := Sandbox(FnPost, req.Bytes()) + if f.resultsProxy != nil { + *f.resultsProxy = wasmtypes.NewProxy(NewScDictFromBytes(res)) + } +} + +func (f *ScFunc) Transfer(transfer ScTransfers) *ScFunc { + f.transfer = ScAssets(transfer) + return f +} + +func (f *ScFunc) TransferIotas(amount uint64) *ScFunc { + f.transfer = make(ScAssets) + f.transfer[wasmtypes.IOTA] = amount + return f +} diff --git a/packages/vm/wasmlib/go/wasmlib/coreaccounts/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/consts.go similarity index 59% rename from packages/vm/wasmlib/go/wasmlib/coreaccounts/consts.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/consts.go index 08325d7f74..a9a3170695 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreaccounts/consts.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/consts.go @@ -7,12 +7,12 @@ package coreaccounts -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "accounts" ScDescription = "Core chain account ledger contract" - HScName = wasmlib.ScHname(0x3c4b5e02) + HScName = wasmtypes.ScHname(0x3c4b5e02) ) const ( @@ -38,11 +38,11 @@ const ( ) const ( - HFuncDeposit = wasmlib.ScHname(0xbdc9102d) - HFuncHarvest = wasmlib.ScHname(0x7b40efbd) - HFuncWithdraw = wasmlib.ScHname(0x9dcc0f41) - HViewAccounts = wasmlib.ScHname(0x3c4b5e02) - HViewBalance = wasmlib.ScHname(0x84168cb4) - HViewGetAccountNonce = wasmlib.ScHname(0x529d7df9) - HViewTotalAssets = wasmlib.ScHname(0xfab0f8d2) + HFuncDeposit = wasmtypes.ScHname(0xbdc9102d) + HFuncHarvest = wasmtypes.ScHname(0x7b40efbd) + HFuncWithdraw = wasmtypes.ScHname(0x9dcc0f41) + HViewAccounts = wasmtypes.ScHname(0x3c4b5e02) + HViewBalance = wasmtypes.ScHname(0x84168cb4) + HViewGetAccountNonce = wasmtypes.ScHname(0x529d7df9) + HViewTotalAssets = wasmtypes.ScHname(0xfab0f8d2) ) diff --git a/packages/vm/wasmlib/go/wasmlib/coreaccounts/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/contract.go similarity index 65% rename from packages/vm/wasmlib/go/wasmlib/coreaccounts/contract.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/contract.go index 849636826b..3f933d7b55 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreaccounts/contract.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/contract.go @@ -7,7 +7,7 @@ package coreaccounts -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type DepositCall struct { Func *wasmlib.ScFunc @@ -51,13 +51,13 @@ var ScFuncs Funcs func (sc Funcs) Deposit(ctx wasmlib.ScFuncCallContext) *DepositCall { f := &DepositCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncDeposit)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) Harvest(ctx wasmlib.ScFuncCallContext) *HarvestCall { f := &HarvestCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncHarvest)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -67,35 +67,57 @@ func (sc Funcs) Withdraw(ctx wasmlib.ScFuncCallContext) *WithdrawCall { func (sc Funcs) Accounts(ctx wasmlib.ScViewCallContext) *AccountsCall { f := &AccountsCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccounts)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) Balance(ctx wasmlib.ScViewCallContext) *BalanceCall { f := &BalanceCall{Func: wasmlib.NewScView(ctx, HScName, HViewBalance)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetAccountNonce(ctx wasmlib.ScViewCallContext) *GetAccountNonceCall { f := &GetAccountNonceCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetAccountNonce)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) TotalAssets(ctx wasmlib.ScViewCallContext) *TotalAssetsCall { f := &TotalAssetsCall{Func: wasmlib.NewScView(ctx, HScName, HViewTotalAssets)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncDeposit, wasmlib.FuncError) - exports.AddFunc(FuncHarvest, wasmlib.FuncError) - exports.AddFunc(FuncWithdraw, wasmlib.FuncError) - exports.AddView(ViewAccounts, wasmlib.ViewError) - exports.AddView(ViewBalance, wasmlib.ViewError) - exports.AddView(ViewGetAccountNonce, wasmlib.ViewError) - exports.AddView(ViewTotalAssets, wasmlib.ViewError) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncDeposit, + FuncHarvest, + FuncWithdraw, + ViewAccounts, + ViewBalance, + ViewGetAccountNonce, + ViewTotalAssets, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + }, + Views: []wasmlib.ScViewContextFunction{ + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/params.go b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/params.go new file mode 100644 index 0000000000..4e16d3efa0 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/params.go @@ -0,0 +1,82 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreaccounts + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableDepositParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableDepositParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) +} + +type MutableDepositParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableDepositParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) +} + +type ImmutableHarvestParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableHarvestParams) WithdrawAmount() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamWithdrawAmount)) +} + +func (s ImmutableHarvestParams) WithdrawColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamWithdrawColor)) +} + +type MutableHarvestParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableHarvestParams) WithdrawAmount() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamWithdrawAmount)) +} + +func (s MutableHarvestParams) WithdrawColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamWithdrawColor)) +} + +type ImmutableBalanceParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableBalanceParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) +} + +type MutableBalanceParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableBalanceParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) +} + +type ImmutableGetAccountNonceParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetAccountNonceParams) AgentID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamAgentID)) +} + +type MutableGetAccountNonceParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetAccountNonceParams) AgentID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamAgentID)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/results.go b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/results.go new file mode 100644 index 0000000000..4e147931f6 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreaccounts/results.go @@ -0,0 +1,120 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreaccounts + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type MapAgentIDToImmutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapAgentIDToImmutableBytes) GetBytes(key wasmtypes.ScAgentID) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) +} + +type ImmutableAccountsResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableAccountsResults) Agents() MapAgentIDToImmutableBytes { + //nolint:gosimple + return MapAgentIDToImmutableBytes{proxy: s.proxy} +} + +type MapAgentIDToMutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapAgentIDToMutableBytes) Clear() { + m.proxy.ClearMap() +} + +func (m MapAgentIDToMutableBytes) GetBytes(key wasmtypes.ScAgentID) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(m.proxy.Key(wasmtypes.AgentIDToBytes(key))) +} + +type MutableAccountsResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableAccountsResults) Agents() MapAgentIDToMutableBytes { + //nolint:gosimple + return MapAgentIDToMutableBytes{proxy: s.proxy} +} + +type MapColorToImmutableInt64 struct { + proxy wasmtypes.Proxy +} + +func (m MapColorToImmutableInt64) GetInt64(key wasmtypes.ScColor) wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(m.proxy.Key(wasmtypes.ColorToBytes(key))) +} + +type ImmutableBalanceResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableBalanceResults) Balances() MapColorToImmutableInt64 { + //nolint:gosimple + return MapColorToImmutableInt64{proxy: s.proxy} +} + +type MapColorToMutableInt64 struct { + proxy wasmtypes.Proxy +} + +func (m MapColorToMutableInt64) Clear() { + m.proxy.ClearMap() +} + +func (m MapColorToMutableInt64) GetInt64(key wasmtypes.ScColor) wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(m.proxy.Key(wasmtypes.ColorToBytes(key))) +} + +type MutableBalanceResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableBalanceResults) Balances() MapColorToMutableInt64 { + //nolint:gosimple + return MapColorToMutableInt64{proxy: s.proxy} +} + +type ImmutableGetAccountNonceResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetAccountNonceResults) AccountNonce() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultAccountNonce)) +} + +type MutableGetAccountNonceResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetAccountNonceResults) AccountNonce() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultAccountNonce)) +} + +type ImmutableTotalAssetsResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableTotalAssetsResults) Balances() MapColorToImmutableInt64 { + //nolint:gosimple + return MapColorToImmutableInt64{proxy: s.proxy} +} + +type MutableTotalAssetsResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableTotalAssetsResults) Balances() MapColorToMutableInt64 { + //nolint:gosimple + return MapColorToMutableInt64{proxy: s.proxy} +} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblob/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/consts.go similarity index 63% rename from packages/vm/wasmlib/go/wasmlib/coreblob/consts.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreblob/consts.go index 34e266cf68..a84ecf8b0c 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreblob/consts.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/consts.go @@ -7,12 +7,12 @@ package coreblob -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "blob" ScDescription = "Core blob contract" - HScName = wasmlib.ScHname(0xfd91bc63) + HScName = wasmtypes.ScHname(0xfd91bc63) ) const ( @@ -35,8 +35,8 @@ const ( ) const ( - HFuncStoreBlob = wasmlib.ScHname(0xddd4c281) - HViewGetBlobField = wasmlib.ScHname(0x1f448130) - HViewGetBlobInfo = wasmlib.ScHname(0xfde4ab46) - HViewListBlobs = wasmlib.ScHname(0x62ca7990) + HFuncStoreBlob = wasmtypes.ScHname(0xddd4c281) + HViewGetBlobField = wasmtypes.ScHname(0x1f448130) + HViewGetBlobInfo = wasmtypes.ScHname(0xfde4ab46) + HViewListBlobs = wasmtypes.ScHname(0x62ca7990) ) diff --git a/packages/vm/wasmlib/go/wasmlib/coreblob/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/contract.go similarity index 60% rename from packages/vm/wasmlib/go/wasmlib/coreblob/contract.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreblob/contract.go index 57b72f9f2e..344bf95aca 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreblob/contract.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/contract.go @@ -7,7 +7,7 @@ package coreblob -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type StoreBlobCall struct { Func *wasmlib.ScFunc @@ -38,32 +38,52 @@ var ScFuncs Funcs func (sc Funcs) StoreBlob(ctx wasmlib.ScFuncCallContext) *StoreBlobCall { f := &StoreBlobCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncStoreBlob)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) + wasmlib.NewCallResultsProxy(&f.Func.ScView, &f.Results.proxy) return f } func (sc Funcs) GetBlobField(ctx wasmlib.ScViewCallContext) *GetBlobFieldCall { f := &GetBlobFieldCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetBlobField)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetBlobInfo(ctx wasmlib.ScViewCallContext) *GetBlobInfoCall { f := &GetBlobInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetBlobInfo)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) ListBlobs(ctx wasmlib.ScViewCallContext) *ListBlobsCall { f := &ListBlobsCall{Func: wasmlib.NewScView(ctx, HScName, HViewListBlobs)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncStoreBlob, wasmlib.FuncError) - exports.AddView(ViewGetBlobField, wasmlib.ViewError) - exports.AddView(ViewGetBlobInfo, wasmlib.ViewError) - exports.AddView(ViewListBlobs, wasmlib.ViewError) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncStoreBlob, + ViewGetBlobField, + ViewGetBlobInfo, + ViewListBlobs, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + wasmlib.FuncError, + }, + Views: []wasmlib.ScViewContextFunction{ + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreblob/params.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/params.go new file mode 100644 index 0000000000..37414ca695 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/params.go @@ -0,0 +1,88 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreblob + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type MapStringToImmutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapStringToImmutableBytes) GetBytes(key string) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(m.proxy.Key(wasmtypes.StringToBytes(key))) +} + +type ImmutableStoreBlobParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableStoreBlobParams) Blobs() MapStringToImmutableBytes { + //nolint:gosimple + return MapStringToImmutableBytes{proxy: s.proxy} +} + +type MapStringToMutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapStringToMutableBytes) Clear() { + m.proxy.ClearMap() +} + +func (m MapStringToMutableBytes) GetBytes(key string) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(m.proxy.Key(wasmtypes.StringToBytes(key))) +} + +type MutableStoreBlobParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableStoreBlobParams) Blobs() MapStringToMutableBytes { + //nolint:gosimple + return MapStringToMutableBytes{proxy: s.proxy} +} + +type ImmutableGetBlobFieldParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlobFieldParams) Field() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamField)) +} + +func (s ImmutableGetBlobFieldParams) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamHash)) +} + +type MutableGetBlobFieldParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlobFieldParams) Field() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamField)) +} + +func (s MutableGetBlobFieldParams) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamHash)) +} + +type ImmutableGetBlobInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlobInfoParams) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamHash)) +} + +type MutableGetBlobInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlobInfoParams) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamHash)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreblob/results.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/results.go new file mode 100644 index 0000000000..085521c318 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblob/results.go @@ -0,0 +1,118 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreblob + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableStoreBlobResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableStoreBlobResults) Hash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ResultHash)) +} + +type MutableStoreBlobResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableStoreBlobResults) Hash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ResultHash)) +} + +type ImmutableGetBlobFieldResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlobFieldResults) Bytes() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultBytes)) +} + +type MutableGetBlobFieldResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlobFieldResults) Bytes() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultBytes)) +} + +type MapStringToImmutableInt32 struct { + proxy wasmtypes.Proxy +} + +func (m MapStringToImmutableInt32) GetInt32(key string) wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(m.proxy.Key(wasmtypes.StringToBytes(key))) +} + +type ImmutableGetBlobInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlobInfoResults) BlobSizes() MapStringToImmutableInt32 { + //nolint:gosimple + return MapStringToImmutableInt32{proxy: s.proxy} +} + +type MapStringToMutableInt32 struct { + proxy wasmtypes.Proxy +} + +func (m MapStringToMutableInt32) Clear() { + m.proxy.ClearMap() +} + +func (m MapStringToMutableInt32) GetInt32(key string) wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(m.proxy.Key(wasmtypes.StringToBytes(key))) +} + +type MutableGetBlobInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlobInfoResults) BlobSizes() MapStringToMutableInt32 { + //nolint:gosimple + return MapStringToMutableInt32{proxy: s.proxy} +} + +type MapHashToImmutableInt32 struct { + proxy wasmtypes.Proxy +} + +func (m MapHashToImmutableInt32) GetInt32(key wasmtypes.ScHash) wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(m.proxy.Key(wasmtypes.HashToBytes(key))) +} + +type ImmutableListBlobsResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableListBlobsResults) BlobSizes() MapHashToImmutableInt32 { + //nolint:gosimple + return MapHashToImmutableInt32{proxy: s.proxy} +} + +type MapHashToMutableInt32 struct { + proxy wasmtypes.Proxy +} + +func (m MapHashToMutableInt32) Clear() { + m.proxy.ClearMap() +} + +func (m MapHashToMutableInt32) GetInt32(key wasmtypes.ScHash) wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(m.proxy.Key(wasmtypes.HashToBytes(key))) +} + +type MutableListBlobsResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableListBlobsResults) BlobSizes() MapHashToMutableInt32 { + //nolint:gosimple + return MapHashToMutableInt32{proxy: s.proxy} +} diff --git a/packages/vm/wasmlib/go/wasmlib/coreblocklog/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/consts.go similarity index 63% rename from packages/vm/wasmlib/go/wasmlib/coreblocklog/consts.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/consts.go index 9b38d5f02d..f6e42bdf03 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreblocklog/consts.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/consts.go @@ -7,12 +7,12 @@ package coreblocklog -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "blocklog" ScDescription = "Core block log contract" - HScName = wasmlib.ScHname(0xf538ef2b) + HScName = wasmtypes.ScHname(0xf538ef2b) ) const ( @@ -49,14 +49,14 @@ const ( ) const ( - HViewControlAddresses = wasmlib.ScHname(0x796bd223) - HViewGetBlockInfo = wasmlib.ScHname(0xbe89f9b3) - HViewGetEventsForBlock = wasmlib.ScHname(0x36232798) - HViewGetEventsForContract = wasmlib.ScHname(0x682a1922) - HViewGetEventsForRequest = wasmlib.ScHname(0x4f8d68e4) - HViewGetLatestBlockInfo = wasmlib.ScHname(0x084a1760) - HViewGetRequestIDsForBlock = wasmlib.ScHname(0x5a20327a) - HViewGetRequestReceipt = wasmlib.ScHname(0xb7f9534f) - HViewGetRequestReceiptsForBlock = wasmlib.ScHname(0x77e3beef) - HViewIsRequestProcessed = wasmlib.ScHname(0xd57d50a9) + HViewControlAddresses = wasmtypes.ScHname(0x796bd223) + HViewGetBlockInfo = wasmtypes.ScHname(0xbe89f9b3) + HViewGetEventsForBlock = wasmtypes.ScHname(0x36232798) + HViewGetEventsForContract = wasmtypes.ScHname(0x682a1922) + HViewGetEventsForRequest = wasmtypes.ScHname(0x4f8d68e4) + HViewGetLatestBlockInfo = wasmtypes.ScHname(0x084a1760) + HViewGetRequestIDsForBlock = wasmtypes.ScHname(0x5a20327a) + HViewGetRequestReceipt = wasmtypes.ScHname(0xb7f9534f) + HViewGetRequestReceiptsForBlock = wasmtypes.ScHname(0x77e3beef) + HViewIsRequestProcessed = wasmtypes.ScHname(0xd57d50a9) ) diff --git a/packages/vm/wasmlib/go/wasmlib/coreblocklog/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/contract.go similarity index 67% rename from packages/vm/wasmlib/go/wasmlib/coreblocklog/contract.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/contract.go index 19da3392e3..683fd48df4 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreblocklog/contract.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/contract.go @@ -7,7 +7,7 @@ package coreblocklog -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type ControlAddressesCall struct { Func *wasmlib.ScView @@ -73,74 +73,104 @@ var ScFuncs Funcs func (sc Funcs) ControlAddresses(ctx wasmlib.ScViewCallContext) *ControlAddressesCall { f := &ControlAddressesCall{Func: wasmlib.NewScView(ctx, HScName, HViewControlAddresses)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetBlockInfo(ctx wasmlib.ScViewCallContext) *GetBlockInfoCall { f := &GetBlockInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetBlockInfo)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetEventsForBlock(ctx wasmlib.ScViewCallContext) *GetEventsForBlockCall { f := &GetEventsForBlockCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetEventsForBlock)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetEventsForContract(ctx wasmlib.ScViewCallContext) *GetEventsForContractCall { f := &GetEventsForContractCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetEventsForContract)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetEventsForRequest(ctx wasmlib.ScViewCallContext) *GetEventsForRequestCall { f := &GetEventsForRequestCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetEventsForRequest)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetLatestBlockInfo(ctx wasmlib.ScViewCallContext) *GetLatestBlockInfoCall { f := &GetLatestBlockInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetLatestBlockInfo)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetRequestIDsForBlock(ctx wasmlib.ScViewCallContext) *GetRequestIDsForBlockCall { f := &GetRequestIDsForBlockCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetRequestIDsForBlock)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetRequestReceipt(ctx wasmlib.ScViewCallContext) *GetRequestReceiptCall { f := &GetRequestReceiptCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetRequestReceipt)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetRequestReceiptsForBlock(ctx wasmlib.ScViewCallContext) *GetRequestReceiptsForBlockCall { f := &GetRequestReceiptsForBlockCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetRequestReceiptsForBlock)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) IsRequestProcessed(ctx wasmlib.ScViewCallContext) *IsRequestProcessedCall { f := &IsRequestProcessedCall{Func: wasmlib.NewScView(ctx, HScName, HViewIsRequestProcessed)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddView(ViewControlAddresses, wasmlib.ViewError) - exports.AddView(ViewGetBlockInfo, wasmlib.ViewError) - exports.AddView(ViewGetEventsForBlock, wasmlib.ViewError) - exports.AddView(ViewGetEventsForContract, wasmlib.ViewError) - exports.AddView(ViewGetEventsForRequest, wasmlib.ViewError) - exports.AddView(ViewGetLatestBlockInfo, wasmlib.ViewError) - exports.AddView(ViewGetRequestIDsForBlock, wasmlib.ViewError) - exports.AddView(ViewGetRequestReceipt, wasmlib.ViewError) - exports.AddView(ViewGetRequestReceiptsForBlock, wasmlib.ViewError) - exports.AddView(ViewIsRequestProcessed, wasmlib.ViewError) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + ViewControlAddresses, + ViewGetBlockInfo, + ViewGetEventsForBlock, + ViewGetEventsForContract, + ViewGetEventsForRequest, + ViewGetLatestBlockInfo, + ViewGetRequestIDsForBlock, + ViewGetRequestReceipt, + ViewGetRequestReceiptsForBlock, + ViewIsRequestProcessed, + }, + Funcs: []wasmlib.ScFuncContextFunction{}, + Views: []wasmlib.ScViewContextFunction{ + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/params.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/params.go new file mode 100644 index 0000000000..e96c04fb0b --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/params.go @@ -0,0 +1,154 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreblocklog + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableGetBlockInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlockInfoParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type MutableGetBlockInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlockInfoParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type ImmutableGetEventsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForBlockParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type MutableGetEventsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForBlockParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type ImmutableGetEventsForContractParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForContractParams) ContractHname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamContractHname)) +} + +func (s ImmutableGetEventsForContractParams) FromBlock() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamFromBlock)) +} + +func (s ImmutableGetEventsForContractParams) ToBlock() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamToBlock)) +} + +type MutableGetEventsForContractParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForContractParams) ContractHname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamContractHname)) +} + +func (s MutableGetEventsForContractParams) FromBlock() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamFromBlock)) +} + +func (s MutableGetEventsForContractParams) ToBlock() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamToBlock)) +} + +type ImmutableGetEventsForRequestParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForRequestParams) RequestID() wasmtypes.ScImmutableRequestID { + return wasmtypes.NewScImmutableRequestID(s.proxy.Root(ParamRequestID)) +} + +type MutableGetEventsForRequestParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForRequestParams) RequestID() wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(s.proxy.Root(ParamRequestID)) +} + +type ImmutableGetRequestIDsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestIDsForBlockParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type MutableGetRequestIDsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestIDsForBlockParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type ImmutableGetRequestReceiptParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestReceiptParams) RequestID() wasmtypes.ScImmutableRequestID { + return wasmtypes.NewScImmutableRequestID(s.proxy.Root(ParamRequestID)) +} + +type MutableGetRequestReceiptParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestReceiptParams) RequestID() wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(s.proxy.Root(ParamRequestID)) +} + +type ImmutableGetRequestReceiptsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestReceiptsForBlockParams) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type MutableGetRequestReceiptsForBlockParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestReceiptsForBlockParams) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ParamBlockIndex)) +} + +type ImmutableIsRequestProcessedParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableIsRequestProcessedParams) RequestID() wasmtypes.ScImmutableRequestID { + return wasmtypes.NewScImmutableRequestID(s.proxy.Root(ParamRequestID)) +} + +type MutableIsRequestProcessedParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableIsRequestProcessedParams) RequestID() wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(s.proxy.Root(ParamRequestID)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/results.go b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/results.go new file mode 100644 index 0000000000..3bede5496f --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreblocklog/results.go @@ -0,0 +1,274 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreblocklog + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableControlAddressesResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableControlAddressesResults) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s ImmutableControlAddressesResults) GoverningAddress() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ResultGoverningAddress)) +} + +func (s ImmutableControlAddressesResults) StateControllerAddress() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ResultStateControllerAddress)) +} + +type MutableControlAddressesResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableControlAddressesResults) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s MutableControlAddressesResults) GoverningAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ResultGoverningAddress)) +} + +func (s MutableControlAddressesResults) StateControllerAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ResultStateControllerAddress)) +} + +type ImmutableGetBlockInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetBlockInfoResults) BlockInfo() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultBlockInfo)) +} + +type MutableGetBlockInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetBlockInfoResults) BlockInfo() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultBlockInfo)) +} + +type ArrayOfImmutableBytes struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfImmutableBytes) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfImmutableBytes) GetBytes(index uint32) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(a.proxy.Index(index)) +} + +type ImmutableGetEventsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForBlockResults) Event() ArrayOfImmutableBytes { + return ArrayOfImmutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type ArrayOfMutableBytes struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableBytes) AppendBytes() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(a.proxy.Append()) +} + +func (a ArrayOfMutableBytes) Clear() { + a.proxy.ClearArray() +} + +func (a ArrayOfMutableBytes) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfMutableBytes) GetBytes(index uint32) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(a.proxy.Index(index)) +} + +type MutableGetEventsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForBlockResults) Event() ArrayOfMutableBytes { + return ArrayOfMutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type ImmutableGetEventsForContractResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForContractResults) Event() ArrayOfImmutableBytes { + return ArrayOfImmutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type MutableGetEventsForContractResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForContractResults) Event() ArrayOfMutableBytes { + return ArrayOfMutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type ImmutableGetEventsForRequestResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetEventsForRequestResults) Event() ArrayOfImmutableBytes { + return ArrayOfImmutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type MutableGetEventsForRequestResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetEventsForRequestResults) Event() ArrayOfMutableBytes { + return ArrayOfMutableBytes{proxy: s.proxy.Root(ResultEvent)} +} + +type ImmutableGetLatestBlockInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetLatestBlockInfoResults) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s ImmutableGetLatestBlockInfoResults) BlockInfo() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultBlockInfo)) +} + +type MutableGetLatestBlockInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetLatestBlockInfoResults) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s MutableGetLatestBlockInfoResults) BlockInfo() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultBlockInfo)) +} + +type ArrayOfImmutableRequestID struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfImmutableRequestID) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfImmutableRequestID) GetRequestID(index uint32) wasmtypes.ScImmutableRequestID { + return wasmtypes.NewScImmutableRequestID(a.proxy.Index(index)) +} + +type ImmutableGetRequestIDsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestIDsForBlockResults) RequestID() ArrayOfImmutableRequestID { + return ArrayOfImmutableRequestID{proxy: s.proxy.Root(ResultRequestID)} +} + +type ArrayOfMutableRequestID struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableRequestID) AppendRequestID() wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(a.proxy.Append()) +} + +func (a ArrayOfMutableRequestID) Clear() { + a.proxy.ClearArray() +} + +func (a ArrayOfMutableRequestID) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfMutableRequestID) GetRequestID(index uint32) wasmtypes.ScMutableRequestID { + return wasmtypes.NewScMutableRequestID(a.proxy.Index(index)) +} + +type MutableGetRequestIDsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestIDsForBlockResults) RequestID() ArrayOfMutableRequestID { + return ArrayOfMutableRequestID{proxy: s.proxy.Root(ResultRequestID)} +} + +type ImmutableGetRequestReceiptResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestReceiptResults) BlockIndex() wasmtypes.ScImmutableUint32 { + return wasmtypes.NewScImmutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s ImmutableGetRequestReceiptResults) RequestIndex() wasmtypes.ScImmutableUint16 { + return wasmtypes.NewScImmutableUint16(s.proxy.Root(ResultRequestIndex)) +} + +func (s ImmutableGetRequestReceiptResults) RequestRecord() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultRequestRecord)) +} + +type MutableGetRequestReceiptResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestReceiptResults) BlockIndex() wasmtypes.ScMutableUint32 { + return wasmtypes.NewScMutableUint32(s.proxy.Root(ResultBlockIndex)) +} + +func (s MutableGetRequestReceiptResults) RequestIndex() wasmtypes.ScMutableUint16 { + return wasmtypes.NewScMutableUint16(s.proxy.Root(ResultRequestIndex)) +} + +func (s MutableGetRequestReceiptResults) RequestRecord() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultRequestRecord)) +} + +type ImmutableGetRequestReceiptsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetRequestReceiptsForBlockResults) RequestRecord() ArrayOfImmutableBytes { + return ArrayOfImmutableBytes{proxy: s.proxy.Root(ResultRequestRecord)} +} + +type MutableGetRequestReceiptsForBlockResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetRequestReceiptsForBlockResults) RequestRecord() ArrayOfMutableBytes { + return ArrayOfMutableBytes{proxy: s.proxy.Root(ResultRequestRecord)} +} + +type ImmutableIsRequestProcessedResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableIsRequestProcessedResults) RequestProcessed() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultRequestProcessed)) +} + +type MutableIsRequestProcessedResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableIsRequestProcessedResults) RequestProcessed() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultRequestProcessed)) +} diff --git a/packages/vm/wasmlib/go/wasmlib/coregovernance/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/consts.go similarity index 66% rename from packages/vm/wasmlib/go/wasmlib/coregovernance/consts.go rename to packages/wasmvm/wasmlib/go/wasmlib/coregovernance/consts.go index 98cb3accc7..f2fd87ab5e 100644 --- a/packages/vm/wasmlib/go/wasmlib/coregovernance/consts.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/consts.go @@ -7,12 +7,12 @@ package coregovernance -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "governance" ScDescription = "Core governance contract" - HScName = wasmlib.ScHname(0x17cf909f) + HScName = wasmtypes.ScHname(0x17cf909f) ) const ( @@ -58,16 +58,16 @@ const ( ) const ( - HFuncAddAllowedStateControllerAddress = wasmlib.ScHname(0x9469d567) - HFuncClaimChainOwnership = wasmlib.ScHname(0x03ff0fc0) - HFuncDelegateChainOwnership = wasmlib.ScHname(0x93ecb6ad) - HFuncRemoveAllowedStateControllerAddress = wasmlib.ScHname(0x31f69447) - HFuncRotateStateController = wasmlib.ScHname(0x244d1038) - HFuncSetChainInfo = wasmlib.ScHname(0x702f5d2b) - HFuncSetContractFee = wasmlib.ScHname(0x8421a42b) - HFuncSetDefaultFee = wasmlib.ScHname(0x3310ecd0) - HViewGetAllowedStateControllerAddresses = wasmlib.ScHname(0xf3505183) - HViewGetChainInfo = wasmlib.ScHname(0x434477e2) - HViewGetFeeInfo = wasmlib.ScHname(0x9fe54b48) - HViewGetMaxBlobSize = wasmlib.ScHname(0xe1db3d28) + HFuncAddAllowedStateControllerAddress = wasmtypes.ScHname(0x9469d567) + HFuncClaimChainOwnership = wasmtypes.ScHname(0x03ff0fc0) + HFuncDelegateChainOwnership = wasmtypes.ScHname(0x93ecb6ad) + HFuncRemoveAllowedStateControllerAddress = wasmtypes.ScHname(0x31f69447) + HFuncRotateStateController = wasmtypes.ScHname(0x244d1038) + HFuncSetChainInfo = wasmtypes.ScHname(0x702f5d2b) + HFuncSetContractFee = wasmtypes.ScHname(0x8421a42b) + HFuncSetDefaultFee = wasmtypes.ScHname(0x3310ecd0) + HViewGetAllowedStateControllerAddresses = wasmtypes.ScHname(0xf3505183) + HViewGetChainInfo = wasmtypes.ScHname(0x434477e2) + HViewGetFeeInfo = wasmtypes.ScHname(0x9fe54b48) + HViewGetMaxBlobSize = wasmtypes.ScHname(0xe1db3d28) ) diff --git a/packages/vm/wasmlib/go/wasmlib/coregovernance/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/contract.go similarity index 71% rename from packages/vm/wasmlib/go/wasmlib/coregovernance/contract.go rename to packages/wasmvm/wasmlib/go/wasmlib/coregovernance/contract.go index 1a6fd89a82..aff2ef1e2d 100644 --- a/packages/vm/wasmlib/go/wasmlib/coregovernance/contract.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/contract.go @@ -7,7 +7,7 @@ package coregovernance -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type AddAllowedStateControllerAddressCall struct { Func *wasmlib.ScFunc @@ -75,7 +75,7 @@ var ScFuncs Funcs func (sc Funcs) AddAllowedStateControllerAddress(ctx wasmlib.ScFuncCallContext) *AddAllowedStateControllerAddressCall { f := &AddAllowedStateControllerAddressCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncAddAllowedStateControllerAddress)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } @@ -85,76 +85,102 @@ func (sc Funcs) ClaimChainOwnership(ctx wasmlib.ScFuncCallContext) *ClaimChainOw func (sc Funcs) DelegateChainOwnership(ctx wasmlib.ScFuncCallContext) *DelegateChainOwnershipCall { f := &DelegateChainOwnershipCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncDelegateChainOwnership)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) RemoveAllowedStateControllerAddress(ctx wasmlib.ScFuncCallContext) *RemoveAllowedStateControllerAddressCall { f := &RemoveAllowedStateControllerAddressCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncRemoveAllowedStateControllerAddress)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) RotateStateController(ctx wasmlib.ScFuncCallContext) *RotateStateControllerCall { f := &RotateStateControllerCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncRotateStateController)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetChainInfo(ctx wasmlib.ScFuncCallContext) *SetChainInfoCall { f := &SetChainInfoCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetChainInfo)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetContractFee(ctx wasmlib.ScFuncCallContext) *SetContractFeeCall { f := &SetContractFeeCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetContractFee)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) SetDefaultFee(ctx wasmlib.ScFuncCallContext) *SetDefaultFeeCall { f := &SetDefaultFeeCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncSetDefaultFee)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GetAllowedStateControllerAddresses(ctx wasmlib.ScViewCallContext) *GetAllowedStateControllerAddressesCall { f := &GetAllowedStateControllerAddressesCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetAllowedStateControllerAddresses)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetChainInfo(ctx wasmlib.ScViewCallContext) *GetChainInfoCall { f := &GetChainInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetChainInfo)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetFeeInfo(ctx wasmlib.ScViewCallContext) *GetFeeInfoCall { f := &GetFeeInfoCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetFeeInfo)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetMaxBlobSize(ctx wasmlib.ScViewCallContext) *GetMaxBlobSizeCall { f := &GetMaxBlobSizeCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetMaxBlobSize)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncAddAllowedStateControllerAddress, wasmlib.FuncError) - exports.AddFunc(FuncClaimChainOwnership, wasmlib.FuncError) - exports.AddFunc(FuncDelegateChainOwnership, wasmlib.FuncError) - exports.AddFunc(FuncRemoveAllowedStateControllerAddress, wasmlib.FuncError) - exports.AddFunc(FuncRotateStateController, wasmlib.FuncError) - exports.AddFunc(FuncSetChainInfo, wasmlib.FuncError) - exports.AddFunc(FuncSetContractFee, wasmlib.FuncError) - exports.AddFunc(FuncSetDefaultFee, wasmlib.FuncError) - exports.AddView(ViewGetAllowedStateControllerAddresses, wasmlib.ViewError) - exports.AddView(ViewGetChainInfo, wasmlib.ViewError) - exports.AddView(ViewGetFeeInfo, wasmlib.ViewError) - exports.AddView(ViewGetMaxBlobSize, wasmlib.ViewError) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncAddAllowedStateControllerAddress, + FuncClaimChainOwnership, + FuncDelegateChainOwnership, + FuncRemoveAllowedStateControllerAddress, + FuncRotateStateController, + FuncSetChainInfo, + FuncSetContractFee, + FuncSetDefaultFee, + ViewGetAllowedStateControllerAddresses, + ViewGetChainInfo, + ViewGetFeeInfo, + ViewGetMaxBlobSize, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + }, + Views: []wasmlib.ScViewContextFunction{ + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + wasmlib.ViewError, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/params.go b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/params.go new file mode 100644 index 0000000000..deb42ba882 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/params.go @@ -0,0 +1,210 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coregovernance + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableAddAllowedStateControllerAddressParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableAddAllowedStateControllerAddressParams) ChainOwner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamChainOwner)) +} + +func (s ImmutableAddAllowedStateControllerAddressParams) FeeColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ParamFeeColor)) +} + +func (s ImmutableAddAllowedStateControllerAddressParams) StateControllerAddress() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type MutableAddAllowedStateControllerAddressParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableAddAllowedStateControllerAddressParams) ChainOwner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamChainOwner)) +} + +func (s MutableAddAllowedStateControllerAddressParams) FeeColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ParamFeeColor)) +} + +func (s MutableAddAllowedStateControllerAddressParams) StateControllerAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type ImmutableDelegateChainOwnershipParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableDelegateChainOwnershipParams) ChainOwner() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamChainOwner)) +} + +type MutableDelegateChainOwnershipParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableDelegateChainOwnershipParams) ChainOwner() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamChainOwner)) +} + +type ImmutableRemoveAllowedStateControllerAddressParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableRemoveAllowedStateControllerAddressParams) StateControllerAddress() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type MutableRemoveAllowedStateControllerAddressParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableRemoveAllowedStateControllerAddressParams) StateControllerAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type ImmutableRotateStateControllerParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableRotateStateControllerParams) StateControllerAddress() wasmtypes.ScImmutableAddress { + return wasmtypes.NewScImmutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type MutableRotateStateControllerParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableRotateStateControllerParams) StateControllerAddress() wasmtypes.ScMutableAddress { + return wasmtypes.NewScMutableAddress(s.proxy.Root(ParamStateControllerAddress)) +} + +type ImmutableSetChainInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableSetChainInfoParams) MaxBlobSize() wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(s.proxy.Root(ParamMaxBlobSize)) +} + +func (s ImmutableSetChainInfoParams) MaxEventSize() wasmtypes.ScImmutableInt16 { + return wasmtypes.NewScImmutableInt16(s.proxy.Root(ParamMaxEventSize)) +} + +func (s ImmutableSetChainInfoParams) MaxEventsPerReq() wasmtypes.ScImmutableInt16 { + return wasmtypes.NewScImmutableInt16(s.proxy.Root(ParamMaxEventsPerReq)) +} + +func (s ImmutableSetChainInfoParams) OwnerFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s ImmutableSetChainInfoParams) ValidatorFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type MutableSetChainInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableSetChainInfoParams) MaxBlobSize() wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(s.proxy.Root(ParamMaxBlobSize)) +} + +func (s MutableSetChainInfoParams) MaxEventSize() wasmtypes.ScMutableInt16 { + return wasmtypes.NewScMutableInt16(s.proxy.Root(ParamMaxEventSize)) +} + +func (s MutableSetChainInfoParams) MaxEventsPerReq() wasmtypes.ScMutableInt16 { + return wasmtypes.NewScMutableInt16(s.proxy.Root(ParamMaxEventsPerReq)) +} + +func (s MutableSetChainInfoParams) OwnerFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s MutableSetChainInfoParams) ValidatorFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type ImmutableSetContractFeeParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableSetContractFeeParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) +} + +func (s ImmutableSetContractFeeParams) OwnerFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s ImmutableSetContractFeeParams) ValidatorFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type MutableSetContractFeeParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableSetContractFeeParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) +} + +func (s MutableSetContractFeeParams) OwnerFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s MutableSetContractFeeParams) ValidatorFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type ImmutableSetDefaultFeeParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableSetDefaultFeeParams) OwnerFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s ImmutableSetDefaultFeeParams) ValidatorFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type MutableSetDefaultFeeParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableSetDefaultFeeParams) OwnerFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamOwnerFee)) +} + +func (s MutableSetDefaultFeeParams) ValidatorFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ParamValidatorFee)) +} + +type ImmutableGetFeeInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetFeeInfoParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) +} + +type MutableGetFeeInfoParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetFeeInfoParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/results.go b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/results.go new file mode 100644 index 0000000000..462252a1be --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coregovernance/results.go @@ -0,0 +1,186 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coregovernance + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ArrayOfImmutableBytes struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfImmutableBytes) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfImmutableBytes) GetBytes(index uint32) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(a.proxy.Index(index)) +} + +type ImmutableGetAllowedStateControllerAddressesResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetAllowedStateControllerAddressesResults) AllowedStateControllerAddresses() ArrayOfImmutableBytes { + return ArrayOfImmutableBytes{proxy: s.proxy.Root(ResultAllowedStateControllerAddresses)} +} + +type ArrayOfMutableBytes struct { + proxy wasmtypes.Proxy +} + +func (a ArrayOfMutableBytes) AppendBytes() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(a.proxy.Append()) +} + +func (a ArrayOfMutableBytes) Clear() { + a.proxy.ClearArray() +} + +func (a ArrayOfMutableBytes) Length() uint32 { + return a.proxy.Length() +} + +func (a ArrayOfMutableBytes) GetBytes(index uint32) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(a.proxy.Index(index)) +} + +type MutableGetAllowedStateControllerAddressesResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetAllowedStateControllerAddressesResults) AllowedStateControllerAddresses() ArrayOfMutableBytes { + return ArrayOfMutableBytes{proxy: s.proxy.Root(ResultAllowedStateControllerAddresses)} +} + +type ImmutableGetChainInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetChainInfoResults) ChainID() wasmtypes.ScImmutableChainID { + return wasmtypes.NewScImmutableChainID(s.proxy.Root(ResultChainID)) +} + +func (s ImmutableGetChainInfoResults) ChainOwnerID() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ResultChainOwnerID)) +} + +func (s ImmutableGetChainInfoResults) DefaultOwnerFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultDefaultOwnerFee)) +} + +func (s ImmutableGetChainInfoResults) DefaultValidatorFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultDefaultValidatorFee)) +} + +func (s ImmutableGetChainInfoResults) Description() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ResultDescription)) +} + +func (s ImmutableGetChainInfoResults) FeeColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ResultFeeColor)) +} + +func (s ImmutableGetChainInfoResults) MaxBlobSize() wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(s.proxy.Root(ResultMaxBlobSize)) +} + +func (s ImmutableGetChainInfoResults) MaxEventSize() wasmtypes.ScImmutableInt16 { + return wasmtypes.NewScImmutableInt16(s.proxy.Root(ResultMaxEventSize)) +} + +func (s ImmutableGetChainInfoResults) MaxEventsPerReq() wasmtypes.ScImmutableInt16 { + return wasmtypes.NewScImmutableInt16(s.proxy.Root(ResultMaxEventsPerReq)) +} + +type MutableGetChainInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetChainInfoResults) ChainID() wasmtypes.ScMutableChainID { + return wasmtypes.NewScMutableChainID(s.proxy.Root(ResultChainID)) +} + +func (s MutableGetChainInfoResults) ChainOwnerID() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ResultChainOwnerID)) +} + +func (s MutableGetChainInfoResults) DefaultOwnerFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultDefaultOwnerFee)) +} + +func (s MutableGetChainInfoResults) DefaultValidatorFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultDefaultValidatorFee)) +} + +func (s MutableGetChainInfoResults) Description() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ResultDescription)) +} + +func (s MutableGetChainInfoResults) FeeColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ResultFeeColor)) +} + +func (s MutableGetChainInfoResults) MaxBlobSize() wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(s.proxy.Root(ResultMaxBlobSize)) +} + +func (s MutableGetChainInfoResults) MaxEventSize() wasmtypes.ScMutableInt16 { + return wasmtypes.NewScMutableInt16(s.proxy.Root(ResultMaxEventSize)) +} + +func (s MutableGetChainInfoResults) MaxEventsPerReq() wasmtypes.ScMutableInt16 { + return wasmtypes.NewScMutableInt16(s.proxy.Root(ResultMaxEventsPerReq)) +} + +type ImmutableGetFeeInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetFeeInfoResults) FeeColor() wasmtypes.ScImmutableColor { + return wasmtypes.NewScImmutableColor(s.proxy.Root(ResultFeeColor)) +} + +func (s ImmutableGetFeeInfoResults) OwnerFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultOwnerFee)) +} + +func (s ImmutableGetFeeInfoResults) ValidatorFee() wasmtypes.ScImmutableInt64 { + return wasmtypes.NewScImmutableInt64(s.proxy.Root(ResultValidatorFee)) +} + +type MutableGetFeeInfoResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetFeeInfoResults) FeeColor() wasmtypes.ScMutableColor { + return wasmtypes.NewScMutableColor(s.proxy.Root(ResultFeeColor)) +} + +func (s MutableGetFeeInfoResults) OwnerFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultOwnerFee)) +} + +func (s MutableGetFeeInfoResults) ValidatorFee() wasmtypes.ScMutableInt64 { + return wasmtypes.NewScMutableInt64(s.proxy.Root(ResultValidatorFee)) +} + +type ImmutableGetMaxBlobSizeResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetMaxBlobSizeResults) MaxBlobSize() wasmtypes.ScImmutableInt32 { + return wasmtypes.NewScImmutableInt32(s.proxy.Root(ResultMaxBlobSize)) +} + +type MutableGetMaxBlobSizeResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetMaxBlobSizeResults) MaxBlobSize() wasmtypes.ScMutableInt32 { + return wasmtypes.NewScMutableInt32(s.proxy.Root(ResultMaxBlobSize)) +} diff --git a/packages/vm/wasmlib/go/wasmlib/coreroot/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/consts.go similarity index 64% rename from packages/vm/wasmlib/go/wasmlib/coreroot/consts.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreroot/consts.go index b791ab59f4..d8736282ad 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreroot/consts.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/consts.go @@ -7,12 +7,12 @@ package coreroot -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" const ( ScName = "root" ScDescription = "Core root contract" - HScName = wasmlib.ScHname(0xcebf5908) + HScName = wasmtypes.ScHname(0xcebf5908) ) const ( @@ -38,9 +38,9 @@ const ( ) const ( - HFuncDeployContract = wasmlib.ScHname(0x28232c27) - HFuncGrantDeployPermission = wasmlib.ScHname(0xf440263a) - HFuncRevokeDeployPermission = wasmlib.ScHname(0x850744f1) - HViewFindContract = wasmlib.ScHname(0xc145ca00) - HViewGetContractRecords = wasmlib.ScHname(0x078b3ef3) + HFuncDeployContract = wasmtypes.ScHname(0x28232c27) + HFuncGrantDeployPermission = wasmtypes.ScHname(0xf440263a) + HFuncRevokeDeployPermission = wasmtypes.ScHname(0x850744f1) + HViewFindContract = wasmtypes.ScHname(0xc145ca00) + HViewGetContractRecords = wasmtypes.ScHname(0x078b3ef3) ) diff --git a/packages/vm/wasmlib/go/wasmlib/coreroot/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/contract.go similarity index 65% rename from packages/vm/wasmlib/go/wasmlib/coreroot/contract.go rename to packages/wasmvm/wasmlib/go/wasmlib/coreroot/contract.go index 400eb1237e..a6ea83ccd0 100644 --- a/packages/vm/wasmlib/go/wasmlib/coreroot/contract.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/contract.go @@ -7,7 +7,7 @@ package coreroot -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" type DeployContractCall struct { Func *wasmlib.ScFunc @@ -41,39 +41,58 @@ var ScFuncs Funcs func (sc Funcs) DeployContract(ctx wasmlib.ScFuncCallContext) *DeployContractCall { f := &DeployContractCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncDeployContract)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) GrantDeployPermission(ctx wasmlib.ScFuncCallContext) *GrantDeployPermissionCall { f := &GrantDeployPermissionCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncGrantDeployPermission)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) RevokeDeployPermission(ctx wasmlib.ScFuncCallContext) *RevokeDeployPermissionCall { f := &RevokeDeployPermissionCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncRevokeDeployPermission)} - f.Func.SetPtrs(&f.Params.id, nil) + f.Params.proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView) return f } func (sc Funcs) FindContract(ctx wasmlib.ScViewCallContext) *FindContractCall { f := &FindContractCall{Func: wasmlib.NewScView(ctx, HScName, HViewFindContract)} - f.Func.SetPtrs(&f.Params.id, &f.Results.id) + f.Params.proxy = wasmlib.NewCallParamsProxy(f.Func) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } func (sc Funcs) GetContractRecords(ctx wasmlib.ScViewCallContext) *GetContractRecordsCall { f := &GetContractRecordsCall{Func: wasmlib.NewScView(ctx, HScName, HViewGetContractRecords)} - f.Func.SetPtrs(nil, &f.Results.id) + wasmlib.NewCallResultsProxy(f.Func, &f.Results.proxy) return f } -func OnLoad() { - exports := wasmlib.NewScExports() - exports.AddFunc(FuncDeployContract, wasmlib.FuncError) - exports.AddFunc(FuncGrantDeployPermission, wasmlib.FuncError) - exports.AddFunc(FuncRevokeDeployPermission, wasmlib.FuncError) - exports.AddView(ViewFindContract, wasmlib.ViewError) - exports.AddView(ViewGetContractRecords, wasmlib.ViewError) +var exportMap = wasmlib.ScExportMap{ + Names: []string{ + FuncDeployContract, + FuncGrantDeployPermission, + FuncRevokeDeployPermission, + ViewFindContract, + ViewGetContractRecords, + }, + Funcs: []wasmlib.ScFuncContextFunction{ + wasmlib.FuncError, + wasmlib.FuncError, + wasmlib.FuncError, + }, + Views: []wasmlib.ScViewContextFunction{ + wasmlib.ViewError, + wasmlib.ViewError, + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreroot/params.go b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/params.go new file mode 100644 index 0000000000..8dac1540e7 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/params.go @@ -0,0 +1,90 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreroot + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableDeployContractParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableDeployContractParams) Description() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamDescription)) +} + +func (s ImmutableDeployContractParams) Name() wasmtypes.ScImmutableString { + return wasmtypes.NewScImmutableString(s.proxy.Root(ParamName)) +} + +func (s ImmutableDeployContractParams) ProgramHash() wasmtypes.ScImmutableHash { + return wasmtypes.NewScImmutableHash(s.proxy.Root(ParamProgramHash)) +} + +type MutableDeployContractParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableDeployContractParams) Description() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamDescription)) +} + +func (s MutableDeployContractParams) Name() wasmtypes.ScMutableString { + return wasmtypes.NewScMutableString(s.proxy.Root(ParamName)) +} + +func (s MutableDeployContractParams) ProgramHash() wasmtypes.ScMutableHash { + return wasmtypes.NewScMutableHash(s.proxy.Root(ParamProgramHash)) +} + +type ImmutableGrantDeployPermissionParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGrantDeployPermissionParams) Deployer() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamDeployer)) +} + +type MutableGrantDeployPermissionParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableGrantDeployPermissionParams) Deployer() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamDeployer)) +} + +type ImmutableRevokeDeployPermissionParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableRevokeDeployPermissionParams) Deployer() wasmtypes.ScImmutableAgentID { + return wasmtypes.NewScImmutableAgentID(s.proxy.Root(ParamDeployer)) +} + +type MutableRevokeDeployPermissionParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableRevokeDeployPermissionParams) Deployer() wasmtypes.ScMutableAgentID { + return wasmtypes.NewScMutableAgentID(s.proxy.Root(ParamDeployer)) +} + +type ImmutableFindContractParams struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableFindContractParams) Hname() wasmtypes.ScImmutableHname { + return wasmtypes.NewScImmutableHname(s.proxy.Root(ParamHname)) +} + +type MutableFindContractParams struct { + proxy wasmtypes.Proxy +} + +func (s MutableFindContractParams) Hname() wasmtypes.ScMutableHname { + return wasmtypes.NewScMutableHname(s.proxy.Root(ParamHname)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/coreroot/results.go b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/results.go new file mode 100644 index 0000000000..6b33a97de4 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/coreroot/results.go @@ -0,0 +1,70 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package coreroot + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ImmutableFindContractResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableFindContractResults) ContractFound() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultContractFound)) +} + +func (s ImmutableFindContractResults) ContractRecData() wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(s.proxy.Root(ResultContractRecData)) +} + +type MutableFindContractResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableFindContractResults) ContractFound() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultContractFound)) +} + +func (s MutableFindContractResults) ContractRecData() wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(s.proxy.Root(ResultContractRecData)) +} + +type MapHnameToImmutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapHnameToImmutableBytes) GetBytes(key wasmtypes.ScHname) wasmtypes.ScImmutableBytes { + return wasmtypes.NewScImmutableBytes(m.proxy.Key(wasmtypes.HnameToBytes(key))) +} + +type ImmutableGetContractRecordsResults struct { + proxy wasmtypes.Proxy +} + +func (s ImmutableGetContractRecordsResults) ContractRegistry() MapHnameToImmutableBytes { + return MapHnameToImmutableBytes{proxy: s.proxy.Root(ResultContractRegistry)} +} + +type MapHnameToMutableBytes struct { + proxy wasmtypes.Proxy +} + +func (m MapHnameToMutableBytes) Clear() { + m.proxy.ClearMap() +} + +func (m MapHnameToMutableBytes) GetBytes(key wasmtypes.ScHname) wasmtypes.ScMutableBytes { + return wasmtypes.NewScMutableBytes(m.proxy.Key(wasmtypes.HnameToBytes(key))) +} + +type MutableGetContractRecordsResults struct { + proxy wasmtypes.Proxy +} + +func (s MutableGetContractRecordsResults) ContractRegistry() MapHnameToMutableBytes { + return MapHnameToMutableBytes{proxy: s.proxy.Root(ResultContractRegistry)} +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/dict.go b/packages/wasmvm/wasmlib/go/wasmlib/dict.go new file mode 100644 index 0000000000..818c5134f0 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/dict.go @@ -0,0 +1,91 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "sort" + + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type ScImmutableDict struct { + dict map[string][]byte +} + +func (d *ScImmutableDict) Exists(key []byte) bool { + return d.dict[string(key)] != nil +} + +func (d *ScImmutableDict) Get(key []byte) []byte { + return d.dict[string(key)] +} + +type ScDict struct { + ScImmutableDict +} + +var _ wasmtypes.IKvStore = new(ScDict) + +func NewScDict() *ScDict { + return &ScDict{ScImmutableDict{dict: make(map[string][]byte)}} +} + +func NewScDictFromBytes(buf []byte) *ScDict { + if len(buf) == 0 { + return NewScDict() + } + dec := wasmtypes.NewWasmDecoder(buf) + size := wasmtypes.Uint32FromBytes(dec.FixedBytes(wasmtypes.ScUint32Length)) + dict := NewScDict() + for i := uint32(0); i < size; i++ { + keyBuf := dec.FixedBytes(wasmtypes.ScUint16Length) + keyLen := wasmtypes.Uint16FromBytes(keyBuf) + key := dec.FixedBytes(uint32(keyLen)) + valBuf := dec.FixedBytes(wasmtypes.ScUint32Length) + valLen := wasmtypes.Uint32FromBytes(valBuf) + val := dec.FixedBytes(valLen) + dict.Set(key, val) + } + return dict +} + +func (d *ScDict) AsProxy() wasmtypes.Proxy { + return wasmtypes.NewProxy(d) +} + +func (d *ScDict) Bytes() []byte { + if d == nil { + return []byte{0, 0, 0, 0} + } + keys := make([]string, 0, len(d.dict)) + for key := range d.dict { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { + return keys[i] < keys[j] + }) + enc := wasmtypes.NewWasmEncoder() + enc.FixedBytes(wasmtypes.Uint32ToBytes(uint32(len(keys))), wasmtypes.ScUint32Length) + for _, k := range keys { + key := []byte(k) + val := d.dict[k] + enc.FixedBytes(wasmtypes.Uint16ToBytes(uint16(len(key))), wasmtypes.ScUint16Length) + enc.FixedBytes(key, uint32(len(key))) + enc.FixedBytes(wasmtypes.Uint32ToBytes(uint32(len(val))), wasmtypes.ScUint32Length) + enc.FixedBytes(val, uint32(len(val))) + } + return enc.Buf() +} + +func (d *ScDict) Delete(key []byte) { + delete(d.dict, string(key)) +} + +func (d *ScDict) Immutable() *ScImmutableDict { + return &d.ScImmutableDict +} + +func (d *ScDict) Set(key, value []byte) { + d.dict[string(key)] = value +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/events.go b/packages/wasmvm/wasmlib/go/wasmlib/events.go new file mode 100644 index 0000000000..92f5c89823 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/events.go @@ -0,0 +1,29 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type EventEncoder struct { + event string +} + +func NewEventEncoder(eventName string) *EventEncoder { + e := &EventEncoder{event: eventName} + timestamp := ScFuncContext{}.Timestamp() + // convert nanoseconds to seconds + e.Encode(wasmtypes.Uint64ToString(timestamp / 1_000_000_000)) + return e +} + +func (e *EventEncoder) Emit() { + ScFuncContext{}.Event(e.event) +} + +func (e *EventEncoder) Encode(value string) { + // TODO encode potential vertical bars that are present in the value string + e.event += "|" + value +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/exports.go b/packages/wasmvm/wasmlib/go/wasmlib/exports.go new file mode 100644 index 0000000000..2267c11a67 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/exports.go @@ -0,0 +1,43 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +type ScExportMap struct { + Names []string + Funcs []ScFuncContextFunction + Views []ScViewContextFunction +} + +func FuncError(ctx ScFuncContext) { + Panic("Invalid core func call") +} + +func ViewError(ctx ScViewContext) { + Panic("Invalid core view call") +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func ScExportsExport(exportMap *ScExportMap) { + ExportName(-1, "WASM::GO") + + for i := range exportMap.Funcs { + ExportName(int32(i), exportMap.Names[i]) + } + + offset := len(exportMap.Funcs) + for i := range exportMap.Views { + ExportName(int32(i)|0x8000, exportMap.Names[offset+i]) + } +} + +func ScExportsCall(index int32, exportMap *ScExportMap) { + if (index & 0x8000) == 0 { + // mutable full function, invoke with a func context + exportMap.Funcs[index](ScFuncContext{}) + return + } + // immutable view function, invoke with a view context + exportMap.Views[index&0x7fff](ScViewContext{}) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/host.go b/packages/wasmvm/wasmlib/go/wasmlib/host.go new file mode 100644 index 0000000000..dc97214259 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/host.go @@ -0,0 +1,62 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type ( + ScFuncContextFunction func(ScFuncContext) + ScViewContextFunction func(ScViewContext) + + ScHost interface { + ExportName(index int32, name string) + Sandbox(funcNr int32, params []byte) []byte + StateDelete(key []byte) + StateExists(key []byte) bool + StateGet(key []byte) []byte + StateSet(key, value []byte) + } +) + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ +var host ScHost + +func init() { + wasmtypes.Base58Encode = func(buf []byte) string { + return string(Sandbox(FnUtilsBase58Encode, buf)) + } + wasmtypes.NewScHname = func(name string) wasmtypes.ScHname { + return wasmtypes.HnameFromBytes(Sandbox(FnUtilsHashName, []byte(name))) + } +} + +func ConnectHost(h ScHost) ScHost { + oldHost := host + host = h + return oldHost +} + +func ExportName(index int32, name string) { + host.ExportName(index, name) +} + +func Sandbox(funcNr int32, params []byte) []byte { + return host.Sandbox(funcNr, params) +} + +func StateDelete(key []byte) { + host.StateDelete(key) +} + +func StateExists(key []byte) bool { + return host.StateExists(key) +} + +func StateGet(key []byte) []byte { + return host.StateGet(key) +} + +func StateSet(key, value []byte) { + host.StateSet(key, value) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go b/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go new file mode 100644 index 0000000000..f2b2cd1c29 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go @@ -0,0 +1,289 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +const ( + FnAccountID = int32(-1) + FnBalance = int32(-2) + FnBalances = int32(-3) + FnBlockContext = int32(-4) + FnCall = int32(-5) + FnCaller = int32(-6) + FnChainID = int32(-7) + FnChainOwnerID = int32(-8) + FnContract = int32(-9) + FnContractCreator = int32(-10) + FnDeployContract = int32(-11) + FnEntropy = int32(-12) + FnEvent = int32(-13) + FnIncomingTransfer = int32(-14) + FnLog = int32(-15) + FnMinted = int32(-16) + FnPanic = int32(-17) + FnParams = int32(-18) + FnPost = int32(-19) + FnRequest = int32(-20) + FnRequestID = int32(-21) + FnResults = int32(-22) + FnSend = int32(-23) + FnStateAnchor = int32(-24) + FnTimestamp = int32(-25) + FnTrace = int32(-26) + FnUtilsBase58Decode = int32(-27) + FnUtilsBase58Encode = int32(-28) + FnUtilsBlsAddress = int32(-29) + FnUtilsBlsAggregate = int32(-30) + FnUtilsBlsValid = int32(-31) + FnUtilsEd25519Address = int32(-32) + FnUtilsEd25519Valid = int32(-33) + FnUtilsHashBlake2b = int32(-34) + FnUtilsHashName = int32(-35) + FnUtilsHashSha3 = int32(-36) +) + +type ScSandbox struct{} + +// TODO go over core contract schemas to set correct unsigned types + +func Log(text string) { + Sandbox(FnLog, []byte(text)) +} + +func Panic(text string) { + Sandbox(FnPanic, []byte(text)) +} + +func Trace(text string) { + Sandbox(FnTrace, []byte(text)) +} + +func NewParamsProxy() wasmtypes.Proxy { + return wasmtypes.NewProxy(NewScDictFromBytes(Sandbox(FnParams, nil))) +} + +// retrieve the agent id of this contract account +func (s ScSandbox) AccountID() wasmtypes.ScAgentID { + return wasmtypes.AgentIDFromBytes(Sandbox(FnAccountID, nil)) +} + +func (s ScSandbox) Balance(color wasmtypes.ScColor) uint64 { + return wasmtypes.Uint64FromBytes(Sandbox(FnBalance, color.Bytes())) +} + +// access the current balances for all assets +func (s ScSandbox) Balances() ScBalances { + return NewScAssetsFromBytes(Sandbox(FnBalances, nil)).Balances() +} + +// calls a smart contract function +func (s ScSandbox) call(hContract, hFunction wasmtypes.ScHname, params *ScDict, transfer ScTransfers) *ScImmutableDict { + req := &wasmrequests.CallRequest{ + Contract: hContract, + Function: hFunction, + Params: params.Bytes(), + Transfer: ScAssets(transfer).Bytes(), + } + res := Sandbox(FnCall, req.Bytes()) + return NewScDictFromBytes(res).Immutable() +} + +// retrieve the chain id of the chain this contract lives on +func (s ScSandbox) ChainID() wasmtypes.ScChainID { + return wasmtypes.ChainIDFromBytes(Sandbox(FnChainID, nil)) +} + +// retrieve the agent id of the owner of the chain this contract lives on +func (s ScSandbox) ChainOwnerID() wasmtypes.ScAgentID { + return wasmtypes.AgentIDFromBytes(Sandbox(FnChainOwnerID, nil)) +} + +// retrieve the hname of this contract +func (s ScSandbox) Contract() wasmtypes.ScHname { + return wasmtypes.HnameFromBytes(Sandbox(FnContract, nil)) +} + +// retrieve the agent id of the creator of this contract +func (s ScSandbox) ContractCreator() wasmtypes.ScAgentID { + return wasmtypes.AgentIDFromBytes(Sandbox(FnContractCreator, nil)) +} + +// logs informational text message +func (s ScSandbox) Log(text string) { + Sandbox(FnLog, []byte(text)) +} + +// logs error text message and then panics +func (s ScSandbox) Panic(text string) { + Sandbox(FnPanic, []byte(text)) +} + +// retrieve parameters passed to the smart contract function that was called +func (s ScSandbox) Params() *ScImmutableDict { + return NewScDictFromBytes(Sandbox(FnParams, nil)).Immutable() +} + +func (s ScSandbox) RawState() ScImmutableState { + return ScImmutableState{} +} + +// panics if condition is not satisfied +func (s ScSandbox) Require(cond bool, msg string) { + if !cond { + s.Panic(msg) + } +} + +func (s ScSandbox) Results(results *ScDict) { + Sandbox(FnResults, results.Bytes()) +} + +// deterministic time stamp fixed at the moment of calling the smart contract +func (s ScSandbox) Timestamp() uint64 { + return wasmtypes.Uint64FromBytes(Sandbox(FnTimestamp, nil)) +} + +// logs debugging trace text message +func (s ScSandbox) Trace(text string) { + Sandbox(FnTrace, []byte(text)) +} + +// access diverse utility functions +func (s ScSandbox) Utility() ScSandboxUtils { + return ScSandboxUtils{} +} + +type ScSandboxView struct { + ScSandbox +} + +// calls a smart contract view +func (s ScSandboxView) Call(hContract, hFunction wasmtypes.ScHname, params *ScDict) *ScImmutableDict { + return s.call(hContract, hFunction, params, nil) +} + +type ScSandboxFunc struct { + ScSandbox +} + +//func (s ScSandbox) BlockContext(construct func(sandbox ScSandbox) interface{}, onClose func(interface{})) interface{} { +// panic("implement me") +//} + +// calls a smart contract function +func (s ScSandboxFunc) Call(hContract, hFunction wasmtypes.ScHname, params *ScDict, transfer ScTransfers) *ScImmutableDict { + return s.call(hContract, hFunction, params, transfer) +} + +// retrieve the agent id of the caller of the smart contract +func (s ScSandboxFunc) Caller() wasmtypes.ScAgentID { + return wasmtypes.AgentIDFromBytes(Sandbox(FnCaller, nil)) +} + +// deploys a smart contract +func (s ScSandboxFunc) DeployContract(programHash wasmtypes.ScHash, name, description string, initParams *ScDict) { + req := &wasmrequests.DeployRequest{ + ProgHash: programHash, + Name: name, + Description: description, + Params: initParams.Bytes(), + } + Sandbox(FnDeployContract, req.Bytes()) +} + +// returns random entropy data for current request. +func (s ScSandboxFunc) Entropy() wasmtypes.ScHash { + return wasmtypes.HashFromBytes(Sandbox(FnEntropy, nil)) +} + +// signals an event on the node that external entities can subscribe to +func (s ScSandboxFunc) Event(msg string) { + Sandbox(FnEvent, []byte(msg)) +} + +// access the incoming balances for all assets +func (s ScSandboxFunc) IncomingTransfer() ScBalances { + buf := Sandbox(FnIncomingTransfer, nil) + return NewScAssetsFromBytes(buf).Balances() +} + +// retrieve the assets that were minted in this transaction +func (s ScSandboxFunc) Minted() ScBalances { + return NewScAssetsFromBytes(Sandbox(FnMinted, nil)).Balances() +} + +// (delayed) posts a smart contract function request +func (s ScSandboxFunc) Post(chainID wasmtypes.ScChainID, hContract, hFunction wasmtypes.ScHname, params *ScDict, transfer ScTransfers, delay uint32) { + req := &wasmrequests.PostRequest{ + ChainID: chainID, + Contract: hContract, + Function: hFunction, + Params: params.Bytes(), + Transfer: ScAssets(transfer).Bytes(), + Delay: delay, + } + Sandbox(FnPost, req.Bytes()) +} + +var ( + entropy []byte + offset = 0 +) + +// generates a random value from 0 to max (exclusive max) using a deterministic RNG +func (s ScSandboxFunc) Random(max uint64) (rnd uint64) { + if max == 0 { + s.Panic("random: max parameter should be non-zero") + } + + // note that entropy gets reset for every request + if len(entropy) == 0 { + // first time in this request, initialize with current request entropy + entropy = s.Entropy().Bytes() + offset = 0 + } + if offset == 32 { + // ran out of entropy data, hash entropy for next pseudo-random entropy + entropy = s.Utility().HashBlake2b(entropy).Bytes() + offset = 0 + } + rnd = wasmtypes.Uint64FromBytes(entropy[offset:offset+8]) % max + offset += 8 + return rnd +} + +func (s ScSandboxFunc) RawState() ScState { + return ScState{} +} + +//func (s ScSandboxFunc) Request() ScRequest { +// panic("implement me") +//} + +// retrieve the request id of this transaction +func (s ScSandboxFunc) RequestID() wasmtypes.ScRequestID { + return wasmtypes.RequestIDFromBytes(Sandbox(FnRequestID, nil)) +} + +// transfer assets to the specified Tangle ledger address +func (s ScSandboxFunc) Send(address wasmtypes.ScAddress, transfer ScTransfers) { + // we need some assets to send + if transfer.IsEmpty() { + return + } + + req := wasmrequests.SendRequest{ + Address: address, + Transfer: ScAssets(transfer).Bytes(), + } + Sandbox(FnSend, req.Bytes()) +} + +//func (s ScSandboxFunc) StateAnchor() interface{} { +// panic("implement me") +//} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/sandboxutils.go b/packages/wasmvm/wasmlib/go/wasmlib/sandboxutils.go new file mode 100644 index 0000000000..291acf9a1c --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/sandboxutils.go @@ -0,0 +1,73 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type ScSandboxUtils struct{} + +// decodes the specified base58-encoded string value to its original bytes +func (u ScSandboxUtils) Base58Decode(value string) []byte { + return Sandbox(FnUtilsBase58Decode, []byte(value)) +} + +// encodes the specified bytes to a base-58-encoded string +func (u ScSandboxUtils) Base58Encode(bytes []byte) string { + return string(Sandbox(FnUtilsBase58Encode, bytes)) +} + +func (u ScSandboxUtils) BlsAddressFromPubKey(pubKey []byte) wasmtypes.ScAddress { + return wasmtypes.AddressFromBytes(Sandbox(FnUtilsBlsAddress, pubKey)) +} + +func (u ScSandboxUtils) BlsAggregateSignatures(pubKeys, sigs [][]byte) ([]byte, []byte) { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.Uint32Encode(enc, uint32(len(pubKeys))) + for _, pubKey := range pubKeys { + enc.Bytes(pubKey) + } + wasmtypes.Uint32Encode(enc, uint32(len(sigs))) + for _, sig := range sigs { + enc.Bytes(sig) + } + result := Sandbox(FnUtilsBlsAggregate, enc.Buf()) + decode := wasmtypes.NewWasmDecoder(result) + return decode.Bytes(), decode.Bytes() +} + +func (u ScSandboxUtils) BlsValidSignature(data, pubKey, signature []byte) bool { + enc := wasmtypes.NewWasmEncoder().Bytes(data).Bytes(pubKey).Bytes(signature) + return wasmtypes.BoolFromBytes(Sandbox(FnUtilsBlsValid, enc.Buf())) +} + +func (u ScSandboxUtils) Ed25519AddressFromPubKey(pubKey []byte) wasmtypes.ScAddress { + return wasmtypes.AddressFromBytes(Sandbox(FnUtilsEd25519Address, pubKey)) +} + +func (u ScSandboxUtils) Ed25519ValidSignature(data, pubKey, signature []byte) bool { + enc := wasmtypes.NewWasmEncoder().Bytes(data).Bytes(pubKey).Bytes(signature) + return wasmtypes.BoolFromBytes(Sandbox(FnUtilsEd25519Valid, enc.Buf())) +} + +// hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash +func (u ScSandboxUtils) HashBlake2b(value []byte) wasmtypes.ScHash { + return wasmtypes.HashFromBytes(Sandbox(FnUtilsHashBlake2b, value)) +} + +// hashes the specified value bytes using sha3 hashing and returns the resulting 32-byte hash +func (u ScSandboxUtils) HashSha3(value []byte) wasmtypes.ScHash { + return wasmtypes.HashFromBytes(Sandbox(FnUtilsHashSha3, value)) +} + +// hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash +func (u ScSandboxUtils) Hname(value string) wasmtypes.ScHname { + return wasmtypes.HnameFromBytes(Sandbox(FnUtilsHashName, []byte(value))) +} + +// converts an integer to its string representation +func (u ScSandboxUtils) String(value int64) string { + return wasmtypes.Int64ToString(value) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/state.go b/packages/wasmvm/wasmlib/go/wasmlib/state.go new file mode 100644 index 0000000000..f4df5d09c4 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/state.go @@ -0,0 +1,40 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmlib + +import ( + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +type ScImmutableState struct{} + +func (d ScImmutableState) Exists(key []byte) bool { + return StateExists(key) +} + +func (d ScImmutableState) Get(key []byte) []byte { + return StateGet(key) +} + +type ScState struct { + ScImmutableState +} + +var _ wasmtypes.IKvStore = ScState{} + +func (d ScState) Delete(key []byte) { + StateDelete(key) +} + +func (d ScState) Immutable() ScImmutableState { + return ScImmutableState{} +} + +func (d ScState) Set(key, value []byte) { + StateSet(key, value) +} + +func NewStateProxy() wasmtypes.Proxy { + return wasmtypes.NewProxy(new(ScState)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/consts.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/consts.go new file mode 100644 index 0000000000..f4df6e6a46 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/consts.go @@ -0,0 +1,16 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package wasmrequests + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +const ( + ScName = "requests" + ScDescription = "WasmLib request structures" + HScName = wasmtypes.ScHname(0x98e19453) +) diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/contract.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/contract.go new file mode 100644 index 0000000000..26d5cdd63a --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/contract.go @@ -0,0 +1,8 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package wasmrequests diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go new file mode 100644 index 0000000000..7429229688 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go @@ -0,0 +1,302 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +package wasmrequests + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + +type CallRequest struct { + Contract wasmtypes.ScHname + Function wasmtypes.ScHname + Params []byte + Transfer []byte +} + +func NewCallRequestFromBytes(buf []byte) *CallRequest { + dec := wasmtypes.NewWasmDecoder(buf) + data := &CallRequest{} + data.Contract = wasmtypes.HnameDecode(dec) + data.Function = wasmtypes.HnameDecode(dec) + data.Params = wasmtypes.BytesDecode(dec) + data.Transfer = wasmtypes.BytesDecode(dec) + dec.Close() + return data +} + +func (o *CallRequest) Bytes() []byte { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.HnameEncode(enc, o.Contract) + wasmtypes.HnameEncode(enc, o.Function) + wasmtypes.BytesEncode(enc, o.Params) + wasmtypes.BytesEncode(enc, o.Transfer) + return enc.Buf() +} + +type ImmutableCallRequest struct { + proxy wasmtypes.Proxy +} + +func (o ImmutableCallRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o ImmutableCallRequest) Value() *CallRequest { + return NewCallRequestFromBytes(o.proxy.Get()) +} + +type MutableCallRequest struct { + proxy wasmtypes.Proxy +} + +func (o MutableCallRequest) Delete() { + o.proxy.Delete() +} + +func (o MutableCallRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o MutableCallRequest) SetValue(value *CallRequest) { + o.proxy.Set(value.Bytes()) +} + +func (o MutableCallRequest) Value() *CallRequest { + return NewCallRequestFromBytes(o.proxy.Get()) +} + +type DeployRequest struct { + Description string + Name string + Params []byte + ProgHash wasmtypes.ScHash +} + +func NewDeployRequestFromBytes(buf []byte) *DeployRequest { + dec := wasmtypes.NewWasmDecoder(buf) + data := &DeployRequest{} + data.Description = wasmtypes.StringDecode(dec) + data.Name = wasmtypes.StringDecode(dec) + data.Params = wasmtypes.BytesDecode(dec) + data.ProgHash = wasmtypes.HashDecode(dec) + dec.Close() + return data +} + +func (o *DeployRequest) Bytes() []byte { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.StringEncode(enc, o.Description) + wasmtypes.StringEncode(enc, o.Name) + wasmtypes.BytesEncode(enc, o.Params) + wasmtypes.HashEncode(enc, o.ProgHash) + return enc.Buf() +} + +type ImmutableDeployRequest struct { + proxy wasmtypes.Proxy +} + +func (o ImmutableDeployRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o ImmutableDeployRequest) Value() *DeployRequest { + return NewDeployRequestFromBytes(o.proxy.Get()) +} + +type MutableDeployRequest struct { + proxy wasmtypes.Proxy +} + +func (o MutableDeployRequest) Delete() { + o.proxy.Delete() +} + +func (o MutableDeployRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o MutableDeployRequest) SetValue(value *DeployRequest) { + o.proxy.Set(value.Bytes()) +} + +func (o MutableDeployRequest) Value() *DeployRequest { + return NewDeployRequestFromBytes(o.proxy.Get()) +} + +type PostRequest struct { + ChainID wasmtypes.ScChainID + Contract wasmtypes.ScHname + Delay uint32 + Function wasmtypes.ScHname + Params []byte + Transfer []byte +} + +func NewPostRequestFromBytes(buf []byte) *PostRequest { + dec := wasmtypes.NewWasmDecoder(buf) + data := &PostRequest{} + data.ChainID = wasmtypes.ChainIDDecode(dec) + data.Contract = wasmtypes.HnameDecode(dec) + data.Delay = wasmtypes.Uint32Decode(dec) + data.Function = wasmtypes.HnameDecode(dec) + data.Params = wasmtypes.BytesDecode(dec) + data.Transfer = wasmtypes.BytesDecode(dec) + dec.Close() + return data +} + +func (o *PostRequest) Bytes() []byte { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.ChainIDEncode(enc, o.ChainID) + wasmtypes.HnameEncode(enc, o.Contract) + wasmtypes.Uint32Encode(enc, o.Delay) + wasmtypes.HnameEncode(enc, o.Function) + wasmtypes.BytesEncode(enc, o.Params) + wasmtypes.BytesEncode(enc, o.Transfer) + return enc.Buf() +} + +type ImmutablePostRequest struct { + proxy wasmtypes.Proxy +} + +func (o ImmutablePostRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o ImmutablePostRequest) Value() *PostRequest { + return NewPostRequestFromBytes(o.proxy.Get()) +} + +type MutablePostRequest struct { + proxy wasmtypes.Proxy +} + +func (o MutablePostRequest) Delete() { + o.proxy.Delete() +} + +func (o MutablePostRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o MutablePostRequest) SetValue(value *PostRequest) { + o.proxy.Set(value.Bytes()) +} + +func (o MutablePostRequest) Value() *PostRequest { + return NewPostRequestFromBytes(o.proxy.Get()) +} + +type SendRequest struct { + Address wasmtypes.ScAddress + Transfer []byte +} + +func NewSendRequestFromBytes(buf []byte) *SendRequest { + dec := wasmtypes.NewWasmDecoder(buf) + data := &SendRequest{} + data.Address = wasmtypes.AddressDecode(dec) + data.Transfer = wasmtypes.BytesDecode(dec) + dec.Close() + return data +} + +func (o *SendRequest) Bytes() []byte { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.AddressEncode(enc, o.Address) + wasmtypes.BytesEncode(enc, o.Transfer) + return enc.Buf() +} + +type ImmutableSendRequest struct { + proxy wasmtypes.Proxy +} + +func (o ImmutableSendRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o ImmutableSendRequest) Value() *SendRequest { + return NewSendRequestFromBytes(o.proxy.Get()) +} + +type MutableSendRequest struct { + proxy wasmtypes.Proxy +} + +func (o MutableSendRequest) Delete() { + o.proxy.Delete() +} + +func (o MutableSendRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o MutableSendRequest) SetValue(value *SendRequest) { + o.proxy.Set(value.Bytes()) +} + +func (o MutableSendRequest) Value() *SendRequest { + return NewSendRequestFromBytes(o.proxy.Get()) +} + +type TransferRequest struct { + AgentID wasmtypes.ScAgentID + Create bool + Transfer []byte +} + +func NewTransferRequestFromBytes(buf []byte) *TransferRequest { + dec := wasmtypes.NewWasmDecoder(buf) + data := &TransferRequest{} + data.AgentID = wasmtypes.AgentIDDecode(dec) + data.Create = wasmtypes.BoolDecode(dec) + data.Transfer = wasmtypes.BytesDecode(dec) + dec.Close() + return data +} + +func (o *TransferRequest) Bytes() []byte { + enc := wasmtypes.NewWasmEncoder() + wasmtypes.AgentIDEncode(enc, o.AgentID) + wasmtypes.BoolEncode(enc, o.Create) + wasmtypes.BytesEncode(enc, o.Transfer) + return enc.Buf() +} + +type ImmutableTransferRequest struct { + proxy wasmtypes.Proxy +} + +func (o ImmutableTransferRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o ImmutableTransferRequest) Value() *TransferRequest { + return NewTransferRequestFromBytes(o.proxy.Get()) +} + +type MutableTransferRequest struct { + proxy wasmtypes.Proxy +} + +func (o MutableTransferRequest) Delete() { + o.proxy.Delete() +} + +func (o MutableTransferRequest) Exists() bool { + return o.proxy.Exists() +} + +func (o MutableTransferRequest) SetValue(value *TransferRequest) { + o.proxy.Set(value.Bytes()) +} + +func (o MutableTransferRequest) Value() *TransferRequest { + return NewTransferRequestFromBytes(o.proxy.Get()) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/codec.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/codec.go new file mode 100644 index 0000000000..df05456283 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/codec.go @@ -0,0 +1,210 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// Base58Encode sandbox function wrapper for simplified use by hashtypes +var Base58Encode func(buf []byte) string + +// WasmDecoder decodes separate entities from a byte buffer +type WasmDecoder struct { + buf []byte +} + +func NewWasmDecoder(buf []byte) *WasmDecoder { + if len(buf) == 0 { + panic("empty decode buffer") + } + return &WasmDecoder{buf: buf} +} + +func (d *WasmDecoder) abort(msg string) { + // make sure a deferred Close() will not trigger another panic + d.buf = nil + panic(msg) +} + +// Byte decodes the next byte from the byte buffer +func (d *WasmDecoder) Byte() byte { + if len(d.buf) == 0 { + d.abort("insufficient bytes") + } + value := d.buf[0] + d.buf = d.buf[1:] + return value +} + +// Bytes decodes the next variable sized slice of bytes from the byte buffer +func (d *WasmDecoder) Bytes() []byte { + length := uint32(d.VluDecode(32)) + return d.FixedBytes(length) +} + +// Close finalizes decoding by panicking if any bytes remain in the byte buffer +func (d *WasmDecoder) Close() { + if len(d.buf) != 0 { + d.abort("extra bytes") + } +} + +// FixedBytes decodes the next fixed size slice of bytes from the byte buffer +func (d *WasmDecoder) FixedBytes(size uint32) []byte { + if uint32(len(d.buf)) < size { + d.abort("insufficient fixed bytes") + } + value := d.buf[:size] + d.buf = d.buf[size:] + return value +} + +// Peek peeks at the next byte in the byte buffer +func (d *WasmDecoder) Peek() byte { + if len(d.buf) == 0 { + d.abort("insufficient peek bytes") + } + return d.buf[0] +} + +// VliDecode: Variable Length Integer decoder, uses modified LEB128 +func (d *WasmDecoder) VliDecode(bits int) int64 { + b := d.Byte() + sign := b & 0x40 + + // first group of 6 bits + value := int64(b & 0x3f) + s := 6 + + // while continuation bit is set + for ; (b & 0x80) != 0; s += 7 { + if s >= bits { + d.abort("integer representation too long") + } + + // next group of 7 bits + b = d.Byte() + value |= int64(b&0x7f) << s + } + + if sign == 0 { + // positive, sign bits are already zero + return value + } + + // negative, extend sign bits + return value | (int64(-1) << s) +} + +// VluDecode: Variable Length Unsigned decoder, uses ULEB128 +func (d *WasmDecoder) VluDecode(bits int) uint64 { + // first group of 7 bits + b := d.Byte() + value := uint64(b & 0x7f) + s := 7 + + // while continuation bit is set + for ; (b & 0x80) != 0; s += 7 { + if s >= bits { + d.abort("unsigned representation too long") + } + + // next group of 7 bits + b = d.Byte() + value |= uint64(b&0x7f) << s + } + return value +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// WasmEncoder encodes separate entities into a byte buffer +type WasmEncoder struct { + buf []byte +} + +func NewWasmEncoder() *WasmEncoder { + return &WasmEncoder{buf: make([]byte, 0, 128)} +} + +// Buf retrieves the encoded byte buffer +func (e *WasmEncoder) Buf() []byte { + return e.buf +} + +// Byte encodes a single byte into the byte buffer +func (e *WasmEncoder) Byte(value uint8) *WasmEncoder { + e.buf = append(e.buf, value) + return e +} + +// Bytes encodes a variable sized slice of bytes into the byte buffer +func (e *WasmEncoder) Bytes(value []byte) *WasmEncoder { + length := len(value) + e.VluEncode(uint64(length)) + return e.FixedBytes(value, uint32(length)) +} + +// FixedBytes encodes a fixed size slice of bytes into the byte buffer +func (e *WasmEncoder) FixedBytes(value []byte, length uint32) *WasmEncoder { + if uint32(len(value)) != length { + panic("invalid fixed bytes length") + } + e.buf = append(e.buf, value...) + return e +} + +// VliEncode Variable Length Integer encoder, uses modified LEB128 +func (e *WasmEncoder) VliEncode(value int64) *WasmEncoder { + // bit 7 is always continuation bit + + // first group: 6 bits of data plus sign bit + // bit 6 encodes 0 as positive and 1 as negative + b := byte(value) & 0x3f + value >>= 6 + + finalValue := int64(0) + if value < 0 { + // 1st byte encodes 1 as negative in bit 6 + b |= 0x40 + // negative value, start with all high bits set to 1 + finalValue = -1 + } + + // keep shifting until all bits are done + for value != finalValue { + // emit with continuation bit + e.buf = append(e.buf, b|0x80) + + // next group of 7 data bits + b = byte(value) & 0x7f + value >>= 7 + } + + // emit without continuation bit to signal end + e.buf = append(e.buf, b) + return e +} + +// VluEncode Variable Length Unsigned encoder, uses ULEB128 +func (e *WasmEncoder) VluEncode(value uint64) *WasmEncoder { + // bit 7 is always continuation bit + + // first group of 7 data bits + b := byte(value) + value >>= 7 + + // keep shifting until all bits are done + for value != 0 { + // emit with continuation bit + e.buf = append(e.buf, b|0x80) + + // next group of 7 data bits + b = byte(value) + value >>= 7 + } + + // emit without continuation bit to signal end + e.buf = append(e.buf, b) + return e +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/proxy.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/proxy.go new file mode 100644 index 0000000000..cbf71d2ee3 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/proxy.go @@ -0,0 +1,126 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type IKvStore interface { + Delete(key []byte) + Exists(key []byte) bool + Get(key []byte) []byte + Set(key, value []byte) +} + +type Proxy struct { + key []byte + kvStore IKvStore +} + +func NewProxy(kvStore IKvStore) Proxy { + return Proxy{kvStore: kvStore} +} + +// Append returns a Proxy for a newly appended null element +// Note that this will essentially return the element at Length() +func (p Proxy) Append() Proxy { + length := p.Length() + p.expand(length + 1) + return p.element(length) +} + +// ClearArray clears an array by deleting all elements +// TODO Note that this does not delete recursive container elements +func (p Proxy) ClearArray() { + for length := p.Length(); length != 0; length-- { + p.element(length - 1).Delete() + } + + // clear the length counter + p.Delete() +} + +// ClearMap clears a map by deleting all elements +// TODO Note that this does not delete recursive container elements +func (p Proxy) ClearMap() { + // TODO clearPrefix + + // clear the length counter + p.Delete() +} + +func (p Proxy) Delete() { + p.kvStore.Delete(p.key) +} + +func (p Proxy) element(index uint32) Proxy { + enc := NewWasmEncoder() + Uint32Encode(enc, index) + return p.sub('#', enc.Buf()) +} + +func (p Proxy) Exists() bool { + return p.kvStore.Exists(p.key) +} + +// TODO have a Grow function that grows an array? +func (p Proxy) expand(length uint32) { + // update the length counter + enc := NewWasmEncoder() + Uint32Encode(enc, length) + p.Set(enc.Buf()) +} + +func (p Proxy) Get() []byte { + return p.kvStore.Get(p.key) +} + +// Index gets a Proxy for an element of an Array by its index +func (p Proxy) Index(index uint32) Proxy { + size := p.Length() + if index >= size { + if index == size { + panic("invalid index: use append") + } + panic("invalid index") + } + return p.element(index) +} + +// Key gets a Proxy for an element of a Map by its key +func (p Proxy) Key(key []byte) Proxy { + return p.sub('.', key) +} + +// Length returns the number of elements in an Array +// Never try to access an index >= Length() +func (p Proxy) Length() uint32 { + // get the length counter + buf := p.Get() + if len(buf) == 0 { + return 0 + } + dec := NewWasmDecoder(buf) + return Uint32Decode(dec) +} + +// Root returns a Proxy for an element of a root container (Params/Results/State). +// The key is always a string. +func (p Proxy) Root(key string) Proxy { + return Proxy{kvStore: p.kvStore, key: []byte(key)} +} + +func (p Proxy) Set(value []byte) { + p.kvStore.Set(p.key, value) +} + +// sub returns a proxy for an element of a container. +// The separator is significant, it prevents potential clashes with other elements. +// Different separators can be used to indicate different sub-containers +func (p Proxy) sub(sep byte, key []byte) Proxy { + if len(p.key) == 0 { + // this must be a root proxy + return Proxy{kvStore: p.kvStore, key: key} + } + return Proxy{kvStore: p.kvStore, key: append(append(p.key, sep), key...)} +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go new file mode 100644 index 0000000000..ab45d51e4f --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go @@ -0,0 +1,108 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ( + ScAddressAlias byte = 2 + ScAddressEd25519 byte = 0 + ScAddressNFT byte = 1 + + ScAddressLength = 33 +) + +type ScAddress struct { + id [ScAddressLength]byte +} + +func (o ScAddress) AsAgentID() ScAgentID { + // agentID for address has Hname zero + return NewScAgentID(o, 0) +} + +func (o ScAddress) Bytes() []byte { + return AddressToBytes(o) +} + +func (o ScAddress) String() string { + return AddressToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// TODO address type-dependent encoding/decoding? +func AddressDecode(dec *WasmDecoder) ScAddress { + addr := ScAddress{} + copy(addr.id[:], dec.FixedBytes(ScAddressLength)) + return addr +} + +func AddressEncode(enc *WasmEncoder, value ScAddress) { + enc.FixedBytes(value.id[:], ScAddressLength) +} + +func AddressFromBytes(buf []byte) ScAddress { + addr := ScAddress{} + if len(buf) == 0 { + return addr + } + if len(buf) != ScAddressLength { + panic("invalid Address length") + } + if buf[0] > ScAddressAlias { + panic("invalid Address type") + } + copy(addr.id[:], buf) + return addr +} + +func AddressToBytes(value ScAddress) []byte { + return value.id[:] +} + +func AddressToString(value ScAddress) string { + // TODO standardize human readable string + return Base58Encode(value.id[:]) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableAddress struct { + proxy Proxy +} + +func NewScImmutableAddress(proxy Proxy) ScImmutableAddress { + return ScImmutableAddress{proxy: proxy} +} + +func (o ScImmutableAddress) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableAddress) String() string { + return AddressToString(o.Value()) +} + +func (o ScImmutableAddress) Value() ScAddress { + return AddressFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableAddress struct { + ScImmutableAddress +} + +func NewScMutableAddress(proxy Proxy) ScMutableAddress { + return ScMutableAddress{ScImmutableAddress{proxy: proxy}} +} + +func (o ScMutableAddress) Delete() { + o.proxy.Delete() +} + +func (o ScMutableAddress) SetValue(value ScAddress) { + o.proxy.Set(AddressToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scagentid.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scagentid.go new file mode 100644 index 0000000000..cf1e26aaf4 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scagentid.go @@ -0,0 +1,118 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScAgentIDLength = ScAddressLength + ScHnameLength + +type ScAgentID struct { + address ScAddress + hname ScHname +} + +func NewScAgentID(address ScAddress, hname ScHname) ScAgentID { + return ScAgentID{address: address, hname: hname} +} + +func (o ScAgentID) Address() ScAddress { + return o.address +} + +func (o ScAgentID) Bytes() []byte { + return AgentIDToBytes(o) +} + +func (o ScAgentID) Hname() ScHname { + return o.hname +} + +func (o ScAgentID) IsAddress() bool { + return o.hname == 0 +} + +func (o ScAgentID) String() string { + return AgentIDToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func AgentIDDecode(dec *WasmDecoder) ScAgentID { + return ScAgentID{ + address: AddressDecode(dec), + hname: HnameDecode(dec), + } +} + +func AgentIDEncode(enc *WasmEncoder, value ScAgentID) { + AddressEncode(enc, value.address) + HnameEncode(enc, value.hname) +} + +func AgentIDFromBytes(buf []byte) ScAgentID { + if len(buf) == 0 { + return ScAgentID{} + } + if len(buf) != ScAgentIDLength { + panic("invalid AgentID length") + } + if buf[0] > ScAddressAlias { + panic("invalid AgentID address type") + } + return ScAgentID{ + address: AddressFromBytes(buf[:ScAddressLength]), + hname: HnameFromBytes(buf[ScAddressLength:]), + } +} + +func AgentIDToBytes(value ScAgentID) []byte { + enc := NewWasmEncoder() + AgentIDEncode(enc, value) + return enc.Buf() +} + +func AgentIDToString(value ScAgentID) string { + // TODO standardize human readable string + return value.address.String() + "::" + value.hname.String() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableAgentID struct { + proxy Proxy +} + +func NewScImmutableAgentID(proxy Proxy) ScImmutableAgentID { + return ScImmutableAgentID{proxy: proxy} +} + +func (o ScImmutableAgentID) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableAgentID) String() string { + return AgentIDToString(o.Value()) +} + +func (o ScImmutableAgentID) Value() ScAgentID { + return AgentIDFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableAgentID struct { + ScImmutableAgentID +} + +func NewScMutableAgentID(proxy Proxy) ScMutableAgentID { + return ScMutableAgentID{ScImmutableAgentID{proxy: proxy}} +} + +func (o ScMutableAgentID) Delete() { + o.proxy.Delete() +} + +func (o ScMutableAgentID) SetValue(value ScAgentID) { + o.proxy.Set(AgentIDToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbool.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbool.go new file mode 100644 index 0000000000..fbdd393fa3 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbool.go @@ -0,0 +1,94 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +const ( + ScBoolLength = 1 + ScBoolFalse = 0x00 + ScBoolTrue = 0xff +) + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func BoolDecode(dec *WasmDecoder) bool { + return dec.Byte() != ScBoolFalse +} + +func BoolEncode(enc *WasmEncoder, value bool) { + if value { + enc.Byte(ScBoolTrue) + return + } + enc.Byte(ScBoolFalse) +} + +func BoolFromBytes(buf []byte) bool { + if len(buf) == 0 { + return false + } + if len(buf) != ScBoolLength { + panic("invalid Bool length") + } + if buf[0] == ScBoolFalse { + return false + } + if buf[0] != ScBoolTrue { + panic("invalid Bool value") + } + return true +} + +func BoolToBytes(value bool) []byte { + if value { + return []byte{ScBoolTrue} + } + return []byte{ScBoolFalse} +} + +func BoolToString(value bool) string { + if value { + return "1" + } + return "0" +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableBool struct { + proxy Proxy +} + +func NewScImmutableBool(proxy Proxy) ScImmutableBool { + return ScImmutableBool{proxy: proxy} +} + +func (o ScImmutableBool) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableBool) String() string { + return BoolToString(o.Value()) +} + +func (o ScImmutableBool) Value() bool { + return BoolFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableBool struct { + ScImmutableBool +} + +func NewScMutableBool(proxy Proxy) ScMutableBool { + return ScMutableBool{ScImmutableBool{proxy: proxy}} +} + +func (o ScMutableBool) Delete() { + o.proxy.Delete() +} + +func (o ScMutableBool) SetValue(value bool) { + o.proxy.Set(BoolToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbytes.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbytes.go new file mode 100644 index 0000000000..1bd204ee0e --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scbytes.go @@ -0,0 +1,66 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func BytesDecode(dec *WasmDecoder) []byte { + return dec.Bytes() +} + +func BytesEncode(enc *WasmEncoder, value []byte) { + enc.Bytes(value) +} + +func BytesFromBytes(buf []byte) []byte { + return buf +} + +func BytesToBytes(buf []byte) []byte { + return buf +} + +func BytesToString(value []byte) string { + return Base58Encode(value) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableBytes struct { + proxy Proxy +} + +func NewScImmutableBytes(proxy Proxy) ScImmutableBytes { + return ScImmutableBytes{proxy: proxy} +} + +func (o ScImmutableBytes) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableBytes) String() string { + return BytesToString(o.Value()) +} + +func (o ScImmutableBytes) Value() []byte { + return BytesFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableBytes struct { + ScImmutableBytes +} + +func NewScMutableBytes(proxy Proxy) ScMutableBytes { + return ScMutableBytes{ScImmutableBytes{proxy: proxy}} +} + +func (o ScMutableBytes) Delete() { + o.proxy.Delete() +} + +func (o ScMutableBytes) SetValue(value []byte) { + o.proxy.Set(BytesToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scchainid.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scchainid.go new file mode 100644 index 0000000000..2aca0682bb --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scchainid.go @@ -0,0 +1,105 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScChainIDLength = 33 + +type ScChainID struct { + id [ScChainIDLength]byte +} + +// Address returns the alias address that the chain ID actually represents +func (o ScChainID) Address() ScAddress { + return AddressFromBytes(o.id[:]) +} + +func (o ScChainID) Bytes() []byte { + return ChainIDToBytes(o) +} + +func (o ScChainID) String() string { + return ChainIDToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func ChainIDDecode(dec *WasmDecoder) ScChainID { + return chainIDFromBytesUnchecked(dec.FixedBytes(ScChainIDLength)) +} + +func ChainIDEncode(enc *WasmEncoder, value ScChainID) { + enc.FixedBytes(value.Bytes(), ScChainIDLength) +} + +func ChainIDFromBytes(buf []byte) ScChainID { + if len(buf) == 0 { + chainID := ScChainID{} + chainID.id[0] = ScAddressAlias + return chainID + } + if len(buf) != ScChainIDLength { + panic("invalid ChainID length") + } + if buf[0] != ScAddressAlias { + panic("invalid ChainID: not an alias address") + } + return chainIDFromBytesUnchecked(buf) +} + +func ChainIDToBytes(value ScChainID) []byte { + return value.id[:] +} + +func ChainIDToString(value ScChainID) string { + // TODO standardize human readable string + return Base58Encode(value.id[:]) +} + +func chainIDFromBytesUnchecked(buf []byte) ScChainID { + o := ScChainID{} + copy(o.id[:], buf) + return o +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableChainID struct { + proxy Proxy +} + +func NewScImmutableChainID(proxy Proxy) ScImmutableChainID { + return ScImmutableChainID{proxy: proxy} +} + +func (o ScImmutableChainID) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableChainID) String() string { + return ChainIDToString(o.Value()) +} + +func (o ScImmutableChainID) Value() ScChainID { + return ChainIDFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableChainID struct { + ScImmutableChainID +} + +func NewScMutableChainID(proxy Proxy) ScMutableChainID { + return ScMutableChainID{ScImmutableChainID{proxy: proxy}} +} + +func (o ScMutableChainID) Delete() { + o.proxy.Delete() +} + +func (o ScMutableChainID) SetValue(value ScChainID) { + o.proxy.Set(ChainIDToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/sccolor.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/sccolor.go new file mode 100644 index 0000000000..ffbe7ead28 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/sccolor.go @@ -0,0 +1,106 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScColorLength = 32 + +type ScColor struct { + id [ScColorLength]byte +} + +var ( + IOTA = ScColor{} + MINT = ScColor{} +) + +func init() { + for i := range MINT.id { + MINT.id[i] = 0xff + } +} + +func (o ScColor) Bytes() []byte { + return ColorToBytes(o) +} + +func (o ScColor) String() string { + return ColorToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func ColorDecode(dec *WasmDecoder) ScColor { + return colorFromBytesUnchecked(dec.FixedBytes(ScColorLength)) +} + +func ColorEncode(enc *WasmEncoder, value ScColor) { + enc.FixedBytes(value.Bytes(), ScColorLength) +} + +func ColorFromBytes(buf []byte) ScColor { + if len(buf) == 0 { + return ScColor{} + } + if len(buf) != ScColorLength { + panic("invalid Color length") + } + return colorFromBytesUnchecked(buf) +} + +func ColorToBytes(value ScColor) []byte { + return value.id[:] +} + +func ColorToString(value ScColor) string { + // TODO standardize human readable string + return Base58Encode(value.id[:]) +} + +func colorFromBytesUnchecked(buf []byte) ScColor { + o := ScColor{} + copy(o.id[:], buf) + return o +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableColor struct { + proxy Proxy +} + +func NewScImmutableColor(proxy Proxy) ScImmutableColor { + return ScImmutableColor{proxy: proxy} +} + +func (o ScImmutableColor) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableColor) String() string { + return ColorToString(o.Value()) +} + +func (o ScImmutableColor) Value() ScColor { + return ColorFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableColor struct { + ScImmutableColor +} + +func NewScMutableColor(proxy Proxy) ScMutableColor { + return ScMutableColor{ScImmutableColor{proxy: proxy}} +} + +func (o ScMutableColor) Delete() { + o.proxy.Delete() +} + +func (o ScMutableColor) SetValue(value ScColor) { + o.proxy.Set(ColorToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schash.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schash.go new file mode 100644 index 0000000000..62ce1349ff --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schash.go @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScHashLength = 32 + +type ScHash struct { + id [ScHashLength]byte +} + +func (o ScHash) Bytes() []byte { + return HashToBytes(o) +} + +func (o ScHash) String() string { + return HashToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func HashDecode(dec *WasmDecoder) ScHash { + return hashFromBytesUnchecked(dec.FixedBytes(ScHashLength)) +} + +func HashEncode(enc *WasmEncoder, value ScHash) { + enc.FixedBytes(value.Bytes(), ScHashLength) +} + +func HashFromBytes(buf []byte) ScHash { + if len(buf) == 0 { + return ScHash{} + } + if len(buf) != ScHashLength { + panic("invalid Hash length") + } + return hashFromBytesUnchecked(buf) +} + +func HashToBytes(value ScHash) []byte { + return value.id[:] +} + +func HashToString(value ScHash) string { + // TODO standardize human readable string + return Base58Encode(value.id[:]) +} + +func hashFromBytesUnchecked(buf []byte) ScHash { + o := ScHash{} + copy(o.id[:], buf) + return o +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableHash struct { + proxy Proxy +} + +func NewScImmutableHash(proxy Proxy) ScImmutableHash { + return ScImmutableHash{proxy: proxy} +} + +func (o ScImmutableHash) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableHash) String() string { + return HashToString(o.Value()) +} + +func (o ScImmutableHash) Value() ScHash { + return HashFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableHash struct { + ScImmutableHash +} + +func NewScMutableHash(proxy Proxy) ScMutableHash { + return ScMutableHash{ScImmutableHash{proxy: proxy}} +} + +func (o ScMutableHash) Delete() { + o.proxy.Delete() +} + +func (o ScMutableHash) SetValue(value ScHash) { + o.proxy.Set(HashToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go new file mode 100644 index 0000000000..0189eaee5c --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go @@ -0,0 +1,97 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "strconv" +) + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScHnameLength = 4 + +type ScHname uint32 + +var NewScHname func(name string) ScHname + +func (o ScHname) Bytes() []byte { + return HnameToBytes(o) +} + +func (o ScHname) String() string { + return HnameToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func HnameDecode(dec *WasmDecoder) ScHname { + return hnameFromBytesUnchecked(dec.FixedBytes(ScHnameLength)) +} + +func HnameEncode(enc *WasmEncoder, value ScHname) { + enc.FixedBytes(value.Bytes(), ScHnameLength) +} + +func HnameFromBytes(buf []byte) ScHname { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScHnameLength { + panic("invalid Hname length") + } + return hnameFromBytesUnchecked(buf) +} + +func HnameToBytes(value ScHname) []byte { + return Uint32ToBytes(uint32(value)) +} + +func HnameToString(value ScHname) string { + res := strconv.FormatUint(uint64(value), 16) + return "0000000"[:8-len(res)] + res +} + +func hnameFromBytesUnchecked(buf []byte) ScHname { + return ScHname(Uint32FromBytes(buf)) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableHname struct { + proxy Proxy +} + +func NewScImmutableHname(proxy Proxy) ScImmutableHname { + return ScImmutableHname{proxy: proxy} +} + +func (o ScImmutableHname) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableHname) String() string { + return HnameToString(o.Value()) +} + +func (o ScImmutableHname) Value() ScHname { + return HnameFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableHname struct { + ScImmutableHname +} + +func NewScMutableHname(proxy Proxy) ScMutableHname { + return ScMutableHname{ScImmutableHname{proxy: proxy}} +} + +func (o ScMutableHname) Delete() { + o.proxy.Delete() +} + +func (o ScMutableHname) SetValue(value ScHname) { + o.proxy.Set(HnameToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint16.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint16.go new file mode 100644 index 0000000000..7cd4eb6931 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint16.go @@ -0,0 +1,79 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +//nolint:dupl +package wasmtypes + +import ( + "strconv" +) + +const ScInt16Length = 2 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Int16Decode(dec *WasmDecoder) int16 { + return int16(dec.VliDecode(16)) +} + +func Int16Encode(enc *WasmEncoder, value int16) { + enc.VliEncode(int64(value)) +} + +func Int16FromBytes(buf []byte) int16 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScInt16Length { + panic("invalid Int16 length") + } + return int16(buf[0]) | int16(buf[1])<<8 +} + +func Int16ToBytes(value int16) []byte { + return []byte{byte(value), byte(value >> 8)} +} + +func Int16ToString(value int16) string { + return strconv.FormatInt(int64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableInt16 struct { + proxy Proxy +} + +func NewScImmutableInt16(proxy Proxy) ScImmutableInt16 { + return ScImmutableInt16{proxy: proxy} +} + +func (o ScImmutableInt16) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableInt16) String() string { + return Int16ToString(o.Value()) +} + +func (o ScImmutableInt16) Value() int16 { + return Int16FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableInt16 struct { + ScImmutableInt16 +} + +func NewScMutableInt16(proxy Proxy) ScMutableInt16 { + return ScMutableInt16{ScImmutableInt16{proxy: proxy}} +} + +func (o ScMutableInt16) Delete() { + o.proxy.Delete() +} + +func (o ScMutableInt16) SetValue(value int16) { + o.proxy.Set(Int16ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint32.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint32.go new file mode 100644 index 0000000000..09a7a69756 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint32.go @@ -0,0 +1,81 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "encoding/binary" + "strconv" +) + +const ScInt32Length = 4 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Int32Decode(dec *WasmDecoder) int32 { + return int32(dec.VliDecode(32)) +} + +func Int32Encode(enc *WasmEncoder, value int32) { + enc.VliEncode(int64(value)) +} + +func Int32FromBytes(buf []byte) int32 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScInt32Length { + panic("invalid Int32 length") + } + return int32(binary.LittleEndian.Uint32(buf)) +} + +func Int32ToBytes(value int32) []byte { + tmp := make([]byte, ScInt32Length) + binary.LittleEndian.PutUint32(tmp, uint32(value)) + return tmp +} + +func Int32ToString(value int32) string { + return strconv.FormatInt(int64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableInt32 struct { + proxy Proxy +} + +func NewScImmutableInt32(proxy Proxy) ScImmutableInt32 { + return ScImmutableInt32{proxy: proxy} +} + +func (o ScImmutableInt32) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableInt32) String() string { + return Int32ToString(o.Value()) +} + +func (o ScImmutableInt32) Value() int32 { + return Int32FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableInt32 struct { + ScImmutableInt32 +} + +func NewScMutableInt32(proxy Proxy) ScMutableInt32 { + return ScMutableInt32{ScImmutableInt32{proxy: proxy}} +} + +func (o ScMutableInt32) Delete() { + o.proxy.Delete() +} + +func (o ScMutableInt32) SetValue(value int32) { + o.proxy.Set(Int32ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint64.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint64.go new file mode 100644 index 0000000000..9bad0aca25 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint64.go @@ -0,0 +1,81 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "encoding/binary" + "strconv" +) + +const ScInt64Length = 8 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Int64Decode(dec *WasmDecoder) int64 { + return dec.VliDecode(64) +} + +func Int64Encode(enc *WasmEncoder, value int64) { + enc.VliEncode(value) +} + +func Int64FromBytes(buf []byte) int64 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScInt64Length { + panic("invalid Int64 length") + } + return int64(binary.LittleEndian.Uint64(buf)) +} + +func Int64ToBytes(value int64) []byte { + tmp := make([]byte, ScInt64Length) + binary.LittleEndian.PutUint64(tmp, uint64(value)) + return tmp +} + +func Int64ToString(value int64) string { + return strconv.FormatInt(value, 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableInt64 struct { + proxy Proxy +} + +func NewScImmutableInt64(proxy Proxy) ScImmutableInt64 { + return ScImmutableInt64{proxy: proxy} +} + +func (o ScImmutableInt64) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableInt64) String() string { + return Int64ToString(o.Value()) +} + +func (o ScImmutableInt64) Value() int64 { + return Int64FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableInt64 struct { + ScImmutableInt64 +} + +func NewScMutableInt64(proxy Proxy) ScMutableInt64 { + return ScMutableInt64{ScImmutableInt64{proxy: proxy}} +} + +func (o ScMutableInt64) Delete() { + o.proxy.Delete() +} + +func (o ScMutableInt64) SetValue(value int64) { + o.proxy.Set(Int64ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint8.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint8.go new file mode 100644 index 0000000000..e82e8f2c18 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scint8.go @@ -0,0 +1,78 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "strconv" +) + +const ScInt8Length = 1 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Int8Decode(dec *WasmDecoder) int8 { + return int8(dec.Byte()) +} + +func Int8Encode(enc *WasmEncoder, value int8) { + enc.Byte(byte(value)) +} + +func Int8FromBytes(buf []byte) int8 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScInt8Length { + panic("invalid Int8 length") + } + return int8(buf[0]) +} + +func Int8ToBytes(value int8) []byte { + return []byte{byte(value)} +} + +func Int8ToString(value int8) string { + return strconv.FormatInt(int64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableInt8 struct { + proxy Proxy +} + +func NewScImmutableInt8(proxy Proxy) ScImmutableInt8 { + return ScImmutableInt8{proxy: proxy} +} + +func (o ScImmutableInt8) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableInt8) String() string { + return Int8ToString(o.Value()) +} + +func (o ScImmutableInt8) Value() int8 { + return Int8FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableInt8 struct { + ScImmutableInt8 +} + +func NewScMutableInt8(proxy Proxy) ScMutableInt8 { + return ScMutableInt8{ScImmutableInt8{proxy: proxy}} +} + +func (o ScMutableInt8) Delete() { + o.proxy.Delete() +} + +func (o ScMutableInt8) SetValue(value int8) { + o.proxy.Set(Int8ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/screquestid.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/screquestid.go new file mode 100644 index 0000000000..0ceb0f29eb --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/screquestid.go @@ -0,0 +1,99 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +const ScRequestIDLength = 34 + +type ScRequestID struct { + id [ScRequestIDLength]byte +} + +func (o ScRequestID) Bytes() []byte { + return RequestIDToBytes(o) +} + +func (o ScRequestID) String() string { + return RequestIDToString(o) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func RequestIDDecode(dec *WasmDecoder) ScRequestID { + return requestIDFromBytesUnchecked(dec.FixedBytes(ScRequestIDLength)) +} + +func RequestIDEncode(enc *WasmEncoder, value ScRequestID) { + enc.FixedBytes(value.Bytes(), ScRequestIDLength) +} + +func RequestIDFromBytes(buf []byte) ScRequestID { + if len(buf) == 0 { + return ScRequestID{} + } + if len(buf) != ScRequestIDLength { + panic("invalid RequestID length") + } + // final uint16 output index must be > ledgerstate.MaxOutputCount + if buf[ScRequestIDLength-2] > 127 || buf[ScRequestIDLength-1] != 0 { + panic("invalid RequestID: output index > 127") + } + return requestIDFromBytesUnchecked(buf) +} + +func RequestIDToBytes(value ScRequestID) []byte { + return value.id[:] +} + +func RequestIDToString(value ScRequestID) string { + // TODO standardize human readable string + return Base58Encode(value.id[:]) +} + +func requestIDFromBytesUnchecked(buf []byte) ScRequestID { + o := ScRequestID{} + copy(o.id[:], buf) + return o +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableRequestID struct { + proxy Proxy +} + +func NewScImmutableRequestID(proxy Proxy) ScImmutableRequestID { + return ScImmutableRequestID{proxy: proxy} +} + +func (o ScImmutableRequestID) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableRequestID) String() string { + return RequestIDToString(o.Value()) +} + +func (o ScImmutableRequestID) Value() ScRequestID { + return RequestIDFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableRequestID struct { + ScImmutableRequestID +} + +func NewScMutableRequestID(proxy Proxy) ScMutableRequestID { + return ScMutableRequestID{ScImmutableRequestID{proxy: proxy}} +} + +func (o ScMutableRequestID) Delete() { + o.proxy.Delete() +} + +func (o ScMutableRequestID) SetValue(value ScRequestID) { + o.proxy.Set(RequestIDToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scstring.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scstring.go new file mode 100644 index 0000000000..66bf3cdc70 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scstring.go @@ -0,0 +1,66 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func StringDecode(dec *WasmDecoder) string { + return string(dec.Bytes()) +} + +func StringEncode(enc *WasmEncoder, value string) { + enc.Bytes([]byte(value)) +} + +func StringFromBytes(buf []byte) string { + return string(buf) +} + +func StringToBytes(value string) []byte { + return []byte(value) +} + +func StringToString(value string) string { + return value +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableString struct { + proxy Proxy +} + +func NewScImmutableString(proxy Proxy) ScImmutableString { + return ScImmutableString{proxy: proxy} +} + +func (o ScImmutableString) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableString) String() string { + return StringToString(o.Value()) +} + +func (o ScImmutableString) Value() string { + return StringFromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableString struct { + ScImmutableString +} + +func NewScMutableString(proxy Proxy) ScMutableString { + return ScMutableString{ScImmutableString{proxy: proxy}} +} + +func (o ScMutableString) Delete() { + o.proxy.Delete() +} + +func (o ScMutableString) SetValue(value string) { + o.proxy.Set(StringToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint16.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint16.go new file mode 100644 index 0000000000..40dacc0d72 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint16.go @@ -0,0 +1,79 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +//nolint:dupl +package wasmtypes + +import ( + "strconv" +) + +const ScUint16Length = 2 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Uint16Decode(dec *WasmDecoder) uint16 { + return uint16(dec.VluDecode(16)) +} + +func Uint16Encode(enc *WasmEncoder, value uint16) { + enc.VluEncode(uint64(value)) +} + +func Uint16FromBytes(buf []byte) uint16 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScUint16Length { + panic("invalid Uint16 length") + } + return uint16(buf[0]) | uint16(buf[1])<<8 +} + +func Uint16ToBytes(value uint16) []byte { + return []byte{byte(value), byte(value >> 8)} +} + +func Uint16ToString(value uint16) string { + return strconv.FormatUint(uint64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableUint16 struct { + proxy Proxy +} + +func NewScImmutableUint16(proxy Proxy) ScImmutableUint16 { + return ScImmutableUint16{proxy: proxy} +} + +func (o ScImmutableUint16) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableUint16) String() string { + return Uint16ToString(o.Value()) +} + +func (o ScImmutableUint16) Value() uint16 { + return Uint16FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableUint16 struct { + ScImmutableUint16 +} + +func NewScMutableUint16(proxy Proxy) ScMutableUint16 { + return ScMutableUint16{ScImmutableUint16{proxy: proxy}} +} + +func (o ScMutableUint16) Delete() { + o.proxy.Delete() +} + +func (o ScMutableUint16) SetValue(value uint16) { + o.proxy.Set(Uint16ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint32.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint32.go new file mode 100644 index 0000000000..02947d1c3f --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint32.go @@ -0,0 +1,81 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "encoding/binary" + "strconv" +) + +const ScUint32Length = 4 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Uint32Decode(dec *WasmDecoder) uint32 { + return uint32(dec.VluDecode(32)) +} + +func Uint32Encode(enc *WasmEncoder, value uint32) { + enc.VluEncode(uint64(value)) +} + +func Uint32FromBytes(buf []byte) uint32 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScUint32Length { + panic("invalid Uint32 length") + } + return binary.LittleEndian.Uint32(buf) +} + +func Uint32ToBytes(value uint32) []byte { + tmp := make([]byte, ScUint32Length) + binary.LittleEndian.PutUint32(tmp, value) + return tmp +} + +func Uint32ToString(value uint32) string { + return strconv.FormatUint(uint64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableUint32 struct { + proxy Proxy +} + +func NewScImmutableUint32(proxy Proxy) ScImmutableUint32 { + return ScImmutableUint32{proxy: proxy} +} + +func (o ScImmutableUint32) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableUint32) String() string { + return Uint32ToString(o.Value()) +} + +func (o ScImmutableUint32) Value() uint32 { + return Uint32FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableUint32 struct { + ScImmutableUint32 +} + +func NewScMutableUint32(proxy Proxy) ScMutableUint32 { + return ScMutableUint32{ScImmutableUint32{proxy: proxy}} +} + +func (o ScMutableUint32) Delete() { + o.proxy.Delete() +} + +func (o ScMutableUint32) SetValue(value uint32) { + o.proxy.Set(Uint32ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint64.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint64.go new file mode 100644 index 0000000000..6f2d91b638 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint64.go @@ -0,0 +1,81 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "encoding/binary" + "strconv" +) + +const ScUint64Length = 8 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Uint64Decode(dec *WasmDecoder) uint64 { + return dec.VluDecode(64) +} + +func Uint64Encode(enc *WasmEncoder, value uint64) { + enc.VluEncode(value) +} + +func Uint64FromBytes(buf []byte) uint64 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScUint64Length { + panic("invalid Uint64 length") + } + return binary.LittleEndian.Uint64(buf) +} + +func Uint64ToBytes(value uint64) []byte { + tmp := make([]byte, ScUint64Length) + binary.LittleEndian.PutUint64(tmp, value) + return tmp +} + +func Uint64ToString(value uint64) string { + return strconv.FormatUint(value, 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableUint64 struct { + proxy Proxy +} + +func NewScImmutableUint64(proxy Proxy) ScImmutableUint64 { + return ScImmutableUint64{proxy: proxy} +} + +func (o ScImmutableUint64) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableUint64) String() string { + return Uint64ToString(o.Value()) +} + +func (o ScImmutableUint64) Value() uint64 { + return Uint64FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableUint64 struct { + ScImmutableUint64 +} + +func NewScMutableUint64(proxy Proxy) ScMutableUint64 { + return ScMutableUint64{ScImmutableUint64{proxy: proxy}} +} + +func (o ScMutableUint64) Delete() { + o.proxy.Delete() +} + +func (o ScMutableUint64) SetValue(value uint64) { + o.proxy.Set(Uint64ToBytes(value)) +} diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint8.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint8.go new file mode 100644 index 0000000000..0cbc0ce574 --- /dev/null +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scuint8.go @@ -0,0 +1,78 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmtypes + +import ( + "strconv" +) + +const ScUint8Length = 1 + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +func Uint8Decode(dec *WasmDecoder) uint8 { + return dec.Byte() +} + +func Uint8Encode(enc *WasmEncoder, value uint8) { + enc.Byte(value) +} + +func Uint8FromBytes(buf []byte) uint8 { + if len(buf) == 0 { + return 0 + } + if len(buf) != ScUint8Length { + panic("invalid Uint8 length") + } + return buf[0] +} + +func Uint8ToBytes(value uint8) []byte { + return []byte{value} +} + +func Uint8ToString(value uint8) string { + return strconv.FormatUint(uint64(value), 10) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScImmutableUint8 struct { + proxy Proxy +} + +func NewScImmutableUint8(proxy Proxy) ScImmutableUint8 { + return ScImmutableUint8{proxy: proxy} +} + +func (o ScImmutableUint8) Exists() bool { + return o.proxy.Exists() +} + +func (o ScImmutableUint8) String() string { + return Uint8ToString(o.Value()) +} + +func (o ScImmutableUint8) Value() uint8 { + return Uint8FromBytes(o.proxy.Get()) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type ScMutableUint8 struct { + ScImmutableUint8 +} + +func NewScMutableUint8(proxy Proxy) ScMutableUint8 { + return ScMutableUint8{ScImmutableUint8{proxy: proxy}} +} + +func (o ScMutableUint8) Delete() { + o.proxy.Delete() +} + +func (o ScMutableUint8) SetValue(value uint8) { + o.proxy.Set(Uint8ToBytes(value)) +} diff --git a/packages/vm/wasmlib/interfaces/coreaccounts.yaml b/packages/wasmvm/wasmlib/interfaces/coreaccounts.yaml similarity index 100% rename from packages/vm/wasmlib/interfaces/coreaccounts.yaml rename to packages/wasmvm/wasmlib/interfaces/coreaccounts.yaml diff --git a/packages/vm/wasmlib/interfaces/coreblob.yaml b/packages/wasmvm/wasmlib/interfaces/coreblob.yaml similarity index 100% rename from packages/vm/wasmlib/interfaces/coreblob.yaml rename to packages/wasmvm/wasmlib/interfaces/coreblob.yaml diff --git a/packages/vm/wasmlib/interfaces/coreblocklog.yaml b/packages/wasmvm/wasmlib/interfaces/coreblocklog.yaml similarity index 81% rename from packages/vm/wasmlib/interfaces/coreblocklog.yaml rename to packages/wasmvm/wasmlib/interfaces/coreblocklog.yaml index 9c07e01aba..ecdab5b531 100644 --- a/packages/vm/wasmlib/interfaces/coreblocklog.yaml +++ b/packages/wasmvm/wasmlib/interfaces/coreblocklog.yaml @@ -7,24 +7,24 @@ funcs: {} views: controlAddresses: results: - blockIndex=n: Int32 + blockIndex=n: Uint32 governingAddress=g: Address stateControllerAddress=s: Address getBlockInfo: params: - blockIndex=n: Int32 + blockIndex=n: Uint32 results: blockInfo=i: Bytes getEventsForBlock: params: - blockIndex=n: Int32 + blockIndex=n: Uint32 results: event=e: Bytes[] // native contract, so this is an Array16 getEventsForContract: params: contractHname=h: Hname - fromBlock=f: Int32? - toBlock=t: Int32? + fromBlock=f: Uint32? + toBlock=t: Uint32? results: event=e: Bytes[] // native contract, so this is an Array16 getEventsForRequest: @@ -34,23 +34,23 @@ views: event=e: Bytes[] // native contract, so this is an Array16 getLatestBlockInfo: results: - blockIndex=n: Int32 + blockIndex=n: Uint32 blockInfo=i: Bytes getRequestIDsForBlock: params: - blockIndex=n: Int32 + blockIndex=n: Uint32 results: requestID=u: RequestID[] // native contract, so this is an Array16 getRequestReceipt: params: requestID=u: RequestID results: - blockIndex=n: Int32 - requestIndex=r: Int16 + blockIndex=n: Uint32 + requestIndex=r: Uint16 requestRecord=d: Bytes getRequestReceiptsForBlock: params: - blockIndex=n: Int32 + blockIndex=n: Uint32 results: requestRecord=d: Bytes[] // native contract, so this is an Array16 isRequestProcessed: diff --git a/packages/vm/wasmlib/interfaces/coregovernance.yaml b/packages/wasmvm/wasmlib/interfaces/coregovernance.yaml similarity index 100% rename from packages/vm/wasmlib/interfaces/coregovernance.yaml rename to packages/wasmvm/wasmlib/interfaces/coregovernance.yaml diff --git a/packages/vm/wasmlib/interfaces/coreroot.yaml b/packages/wasmvm/wasmlib/interfaces/coreroot.yaml similarity index 100% rename from packages/vm/wasmlib/interfaces/coreroot.yaml rename to packages/wasmvm/wasmlib/interfaces/coreroot.yaml diff --git a/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml b/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml new file mode 100644 index 0000000000..2b94ced241 --- /dev/null +++ b/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml @@ -0,0 +1,37 @@ +name: WasmRequests +description: WasmLib request structures +events: {} +structs: + CallRequest: + contract: Hname + function: Hname + params: Bytes + transfer: Bytes + + DeployRequest: + progHash: Hash + name: String + description: String + params: Bytes + + PostRequest: + chainID: ChainID + contract: Hname + function: Hname + params: Bytes + transfer: Bytes + delay: Uint32 + + SendRequest: + address: Address + transfer: Bytes + + TransferRequest: + agentID: AgentID + create: Bool + transfer: Bytes + +typedefs: {} +state: {} +funcs: {} +views: {} diff --git a/packages/wasmvm/wasmlib/src/assets.rs b/packages/wasmvm/wasmlib/src/assets.rs new file mode 100644 index 0000000000..a92e9eb091 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/assets.rs @@ -0,0 +1,132 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::BTreeMap; + +use crate::*; + +fn read_bytes(assets: &mut BTreeMap, u64>, buf: &[u8]) { + if buf.len() != 0 { + let mut dec = WasmDecoder::new(buf); + let size = uint32_from_bytes(&dec.fixed_bytes(SC_UINT32_LENGTH)); + for _i in 0..size { + let color = color_decode(&mut dec); + let amount_buf = dec.fixed_bytes(SC_UINT64_LENGTH); + let amount = uint64_from_bytes(&amount_buf); + assets.insert(color.to_bytes(), amount); + } + } +} + +#[derive(Clone)] +pub struct ScAssets { + assets: BTreeMap, u64>, +} + +impl ScAssets { + pub fn new(buf: &[u8]) -> ScAssets { + let mut assets = ScAssets { assets: BTreeMap::new() }; + read_bytes(&mut assets.assets, buf); + assets + } + + pub fn balances(&self) -> ScBalances { + ScBalances { assets: self.assets.clone() } + } + + pub fn to_bytes(&self) -> Vec { + let dict = &self.assets; + if dict.len() == 0 { + return vec![0; SC_UINT32_LENGTH]; + } + + let mut enc = WasmEncoder::new(); + enc.fixed_bytes(&uint32_to_bytes(dict.len() as u32), SC_UINT32_LENGTH); + for (key, val) in dict.iter() { + enc.fixed_bytes(key, SC_COLOR_LENGTH); + enc.fixed_bytes(&uint64_to_bytes(*val), SC_UINT64_LENGTH); + } + return enc.buf(); + } +} + +#[derive(Clone)] +pub struct ScBalances { + assets: BTreeMap, u64>, +} + +impl ScBalances { + pub fn balance(&self, color: &ScColor) -> u64 { + let key = color.to_bytes(); + if !self.assets.contains_key(&key) { + return 0; + } + *self.assets.get(&key).unwrap() + } + + pub fn colors(&self) -> Vec { + let mut colors: Vec = Vec::new(); + for color in self.assets.keys() { + colors.push(color_from_bytes(color)); + } + colors + } +} + +#[derive(Clone)] +pub struct ScTransfers { + assets: BTreeMap, u64>, +} + +impl ScTransfers { + pub fn new(buf: &[u8]) -> ScTransfers { + let mut assets = ScTransfers { assets: BTreeMap::new() }; + read_bytes(&mut assets.assets, buf); + assets + } + + pub fn from_balances(balances: ScBalances) -> ScTransfers { + let mut transfers = ScTransfers { assets: BTreeMap::new() }; + let colors = balances.colors(); + for i in 0..colors.len() { + let color = colors.get(i).unwrap(); + transfers.set(color, balances.balance(color)) + } + transfers + } + + pub fn iotas(amount: u64) -> ScTransfers { + ScTransfers::transfer(&ScColor::IOTA, amount) + } + + pub fn is_empty(&self) -> bool { + for (_key, val) in self.assets.iter() { + if *val != 0 { + return false; + } + } + true + } + + pub fn transfer(color: &ScColor, amount: u64) -> ScTransfers { + let mut transfers = ScTransfers { assets: BTreeMap::new() }; + transfers.set(color, amount); + transfers + } + + pub fn as_assets(&self) -> ScAssets { + ScAssets { assets: self.assets.clone() } + } + + pub fn balances(&self) -> ScBalances { + ScBalances { assets: self.assets.clone() } + } + + pub fn set(&mut self, color: &ScColor, amount: u64) { + self.assets.insert(color.to_bytes(), amount); + } + + pub fn to_bytes(&self) -> Vec { + self.as_assets().to_bytes() + } +} diff --git a/packages/wasmvm/wasmlib/src/context.rs b/packages/wasmvm/wasmlib/src/context.rs new file mode 100644 index 0000000000..eafefe643f --- /dev/null +++ b/packages/wasmvm/wasmlib/src/context.rs @@ -0,0 +1,55 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// encapsulates standard host entities into a simple interface + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract interface with mutable access to state +#[derive(Clone, Copy)] +pub struct ScFuncContext {} + +// reuse shared part of interface +impl ScSandbox for ScFuncContext {} + +impl ScSandboxFunc for ScFuncContext {} + +impl ScFuncCallContext for ScFuncContext { + fn can_call_func(&self) { + panic!("can_call_func"); + } +} + +impl ScViewCallContext for ScFuncContext { + fn can_call_view(&self) { + panic!("can_call_view"); + } +} + +impl ScFuncContext { + pub fn incoming(&self) -> ScBalances { + self.incoming_transfer() + } + + pub fn transfer_to_address(&self, address: &ScAddress, transfer: ScTransfers) { + self.send(address, &transfer) + } +} +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract view interface which has only immutable access to state +#[derive(Clone, Copy)] +pub struct ScViewContext {} + +// reuse shared part of interface +impl ScSandbox for ScViewContext {} + +impl ScSandboxView for ScViewContext {} + +impl ScViewCallContext for ScViewContext { + fn can_call_view(&self) { + panic!("can_call_view"); + } +} diff --git a/packages/wasmvm/wasmlib/src/contract.rs b/packages/wasmvm/wasmlib/src/contract.rs new file mode 100644 index 0000000000..0b29a52c1c --- /dev/null +++ b/packages/wasmvm/wasmlib/src/contract.rs @@ -0,0 +1,176 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// base contract objects + +use std::rc::Rc; + +use crate::*; +use crate::host::*; + +pub trait ScFuncCallContext { + fn can_call_func(&self); +} + +pub trait ScViewCallContext { + fn can_call_view(&self); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +#[derive(Clone)] +pub struct ScView { + h_contract: ScHname, + h_function: ScHname, + params: Rc, + results: Rc, +} + +impl ScView { + pub fn new(h_contract: ScHname, h_function: ScHname) -> ScView { + ScView { + h_contract: h_contract, + h_function: h_function, + params: Rc::new(ScDict::new(&[])), + results: Rc::new(ScDict::new(&[])), + } + } + + pub fn link_params(proxy: &mut Proxy, view: &ScView) { + Proxy::link(proxy, &view.params); + } + + pub fn link_results(proxy: &mut Proxy, view: &ScView) { + Proxy::link(proxy, &view.results); + } + + pub fn call(&self) { + self.call_with_transfer(None); + } + + fn call_with_transfer(&self, transfer: Option) { + let mut req = wasmrequests::CallRequest { + contract: self.h_contract, + function: self.h_function, + params: self.params.to_bytes(), + transfer: vec![0; SC_UINT32_LENGTH], + }; + if let Some(transfer) = transfer { + req.transfer = transfer.to_bytes(); + } + let res = sandbox(FN_CALL, &req.to_bytes()); + self.results.copy(&res); + } + + pub fn of_contract(&self, h_contract: ScHname) -> ScView { + let mut ret = self.clone(); + ret.h_contract = h_contract; + ret + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +#[derive(Clone)] +pub struct ScInitFunc { + view: ScView, +} + +impl ScInitFunc { + pub fn new(h_contract: ScHname, h_function: ScHname) -> ScInitFunc { + ScInitFunc { + view: ScView::new(h_contract, h_function), + } + } + + pub fn link_params(proxy: &mut Proxy, func: &ScInitFunc) { + ScView::link_params(proxy, &func.view); + } + + pub fn link_results(proxy: &mut Proxy, func: &ScInitFunc) { + ScView::link_results(proxy, &func.view); + } + + pub fn call(&self) { + panic("cannot call init") + } + + pub fn of_contract(&self, h_contract: ScHname) -> ScInitFunc { + let mut ret = self.clone(); + ret.view.h_contract = h_contract; + ret + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +#[derive(Clone)] +pub struct ScFunc { + pub view: ScView, + delay: u32, + transfer: ScAssets, +} + +impl ScFunc { + pub fn new(h_contract: ScHname, h_function: ScHname) -> ScFunc { + ScFunc { + view: ScView::new(h_contract, h_function), + delay: 0, + transfer: ScAssets::new(&[]), + } + } + + pub fn link_params(proxy: &mut Proxy, func: &ScFunc) { + ScView::link_params(proxy, &func.view); + } + + pub fn link_results(proxy: &mut Proxy, func: &ScFunc) { + ScView::link_results(proxy, &func.view); + } + + pub fn call(&self) { + if self.delay != 0 { + panic("cannot delay a call") + } + self.view.call_with_transfer(Some(self.transfer.clone())); + } + + pub fn delay(&self, seconds: u32) -> ScFunc { + let mut ret = self.clone(); + ret.delay = seconds; + ret + } + + pub fn of_contract(&self, h_contract: ScHname) -> ScFunc { + let mut ret = self.clone(); + ret.view.h_contract = h_contract; + ret + } + + pub fn post(&self) { + self.post_to_chain(ScFuncContext {}.chain_id()) + } + + pub fn post_to_chain(&self, chain_id: ScChainID) { + let req = wasmrequests::PostRequest { + chain_id: chain_id, + contract: self.view.h_contract, + function: self.view.h_function, + params: self.view.params.to_bytes(), + transfer: self.transfer.to_bytes(), + delay: self.delay, + }; + let res = sandbox(FN_POST, &req.to_bytes()); + self.view.results.copy(&res); + } + + pub fn transfer(&self, transfer: ScTransfers) -> ScFunc { + let mut ret = self.clone(); + ret.transfer = transfer.as_assets(); + ret + } + + pub fn transfer_iotas(&self, amount: u64) -> ScFunc { + self.transfer(ScTransfers::iotas(amount)) + } +} diff --git a/packages/vm/wasmlib/src/coreaccounts/consts.rs b/packages/wasmvm/wasmlib/src/coreaccounts/consts.rs similarity index 100% rename from packages/vm/wasmlib/src/coreaccounts/consts.rs rename to packages/wasmvm/wasmlib/src/coreaccounts/consts.rs diff --git a/packages/vm/wasmlib/src/coreaccounts/contract.rs b/packages/wasmvm/wasmlib/src/coreaccounts/contract.rs similarity index 53% rename from packages/vm/wasmlib/src/coreaccounts/contract.rs rename to packages/wasmvm/wasmlib/src/coreaccounts/contract.rs index 8b6e25016e..fa86cc14b8 100644 --- a/packages/vm/wasmlib/src/coreaccounts/contract.rs +++ b/packages/wasmvm/wasmlib/src/coreaccounts/contract.rs @@ -7,10 +7,8 @@ #![allow(dead_code)] -use std::ptr; - -use crate::*; use crate::coreaccounts::*; +use crate::*; pub struct DepositCall { pub func: ScFunc, @@ -52,65 +50,67 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn deposit(_ctx: & dyn ScFuncCallContext) -> DepositCall { + pub fn deposit(_ctx: &dyn ScFuncCallContext) -> DepositCall { let mut f = DepositCall { func: ScFunc::new(HSC_NAME, HFUNC_DEPOSIT), - params: MutableDepositParams { id: 0 }, + params: MutableDepositParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn harvest(_ctx: & dyn ScFuncCallContext) -> HarvestCall { + pub fn harvest(_ctx: &dyn ScFuncCallContext) -> HarvestCall { let mut f = HarvestCall { func: ScFunc::new(HSC_NAME, HFUNC_HARVEST), - params: MutableHarvestParams { id: 0 }, + params: MutableHarvestParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn withdraw(_ctx: & dyn ScFuncCallContext) -> WithdrawCall { + pub fn withdraw(_ctx: &dyn ScFuncCallContext) -> WithdrawCall { WithdrawCall { func: ScFunc::new(HSC_NAME, HFUNC_WITHDRAW), } } - pub fn accounts(_ctx: & dyn ScViewCallContext) -> AccountsCall { + pub fn accounts(_ctx: &dyn ScViewCallContext) -> AccountsCall { let mut f = AccountsCall { func: ScView::new(HSC_NAME, HVIEW_ACCOUNTS), - results: ImmutableAccountsResults { id: 0 }, + results: ImmutableAccountsResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn balance(_ctx: & dyn ScViewCallContext) -> BalanceCall { + pub fn balance(_ctx: &dyn ScViewCallContext) -> BalanceCall { let mut f = BalanceCall { func: ScView::new(HSC_NAME, HVIEW_BALANCE), - params: MutableBalanceParams { id: 0 }, - results: ImmutableBalanceResults { id: 0 }, + params: MutableBalanceParams { proxy: Proxy::nil() }, + results: ImmutableBalanceResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_account_nonce(_ctx: & dyn ScViewCallContext) -> GetAccountNonceCall { + pub fn get_account_nonce(_ctx: &dyn ScViewCallContext) -> GetAccountNonceCall { let mut f = GetAccountNonceCall { func: ScView::new(HSC_NAME, HVIEW_GET_ACCOUNT_NONCE), - params: MutableGetAccountNonceParams { id: 0 }, - results: ImmutableGetAccountNonceResults { id: 0 }, + params: MutableGetAccountNonceParams { proxy: Proxy::nil() }, + results: ImmutableGetAccountNonceResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn total_assets(_ctx: & dyn ScViewCallContext) -> TotalAssetsCall { + pub fn total_assets(_ctx: &dyn ScViewCallContext) -> TotalAssetsCall { let mut f = TotalAssetsCall { func: ScView::new(HSC_NAME, HVIEW_TOTAL_ASSETS), - results: ImmutableTotalAssetsResults { id: 0 }, + results: ImmutableTotalAssetsResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/packages/vm/wasmlib/src/coreaccounts/mod.rs b/packages/wasmvm/wasmlib/src/coreaccounts/mod.rs similarity index 100% rename from packages/vm/wasmlib/src/coreaccounts/mod.rs rename to packages/wasmvm/wasmlib/src/coreaccounts/mod.rs diff --git a/packages/vm/wasmlib/src/coreaccounts/params.rs b/packages/wasmvm/wasmlib/src/coreaccounts/params.rs similarity index 57% rename from packages/vm/wasmlib/src/coreaccounts/params.rs rename to packages/wasmvm/wasmlib/src/coreaccounts/params.rs index 5c61b19e05..4eb0d3e283 100644 --- a/packages/vm/wasmlib/src/coreaccounts/params.rs +++ b/packages/wasmvm/wasmlib/src/coreaccounts/params.rs @@ -8,102 +8,101 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreaccounts::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDepositParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDepositParams { pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDepositParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDepositParams { pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableHarvestParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableHarvestParams { pub fn withdraw_amount(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_WITHDRAW_AMOUNT.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_WITHDRAW_AMOUNT)) } pub fn withdraw_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_WITHDRAW_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_WITHDRAW_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableHarvestParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableHarvestParams { pub fn withdraw_amount(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_WITHDRAW_AMOUNT.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_WITHDRAW_AMOUNT)) } pub fn withdraw_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_WITHDRAW_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_WITHDRAW_COLOR)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceParams { pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceParams { pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetAccountNonceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetAccountNonceParams { pub fn agent_id(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetAccountNonceParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetAccountNonceParams { pub fn agent_id(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_AGENT_ID.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_AGENT_ID)) } } diff --git a/packages/vm/wasmlib/src/coreaccounts/results.rs b/packages/wasmvm/wasmlib/src/coreaccounts/results.rs similarity index 60% rename from packages/vm/wasmlib/src/coreaccounts/results.rs rename to packages/wasmvm/wasmlib/src/coreaccounts/results.rs index 463868574a..a41a76f297 100644 --- a/packages/vm/wasmlib/src/coreaccounts/results.rs +++ b/packages/wasmvm/wasmlib/src/coreaccounts/results.rs @@ -8,146 +8,145 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreaccounts::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToImmutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToImmutableBytes { pub fn get_bytes(&self, key: &ScAgentID) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, key.get_key_id()) + ScImmutableBytes::new(self.proxy.key(&agent_id_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableAccountsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableAccountsResults { pub fn agents(&self) -> MapAgentIDToImmutableBytes { - MapAgentIDToImmutableBytes { obj_id: self.id } + MapAgentIDToImmutableBytes { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapAgentIDToMutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapAgentIDToMutableBytes { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bytes(&self, key: &ScAgentID) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, key.get_key_id()) + ScMutableBytes::new(self.proxy.key(&agent_id_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableAccountsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableAccountsResults { pub fn agents(&self) -> MapAgentIDToMutableBytes { - MapAgentIDToMutableBytes { obj_id: self.id } + MapAgentIDToMutableBytes { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToImmutableInt64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToImmutableInt64 { pub fn get_int64(&self, key: &ScColor) -> ScImmutableInt64 { - ScImmutableInt64::new(self.obj_id, key.get_key_id()) + ScImmutableInt64::new(self.proxy.key(&color_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableBalanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableBalanceResults { pub fn balances(&self) -> MapColorToImmutableInt64 { - MapColorToImmutableInt64 { obj_id: self.id } + MapColorToImmutableInt64 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapColorToMutableInt64 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapColorToMutableInt64 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_int64(&self, key: &ScColor) -> ScMutableInt64 { - ScMutableInt64::new(self.obj_id, key.get_key_id()) + ScMutableInt64::new(self.proxy.key(&color_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableBalanceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableBalanceResults { pub fn balances(&self) -> MapColorToMutableInt64 { - MapColorToMutableInt64 { obj_id: self.id } + MapColorToMutableInt64 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetAccountNonceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetAccountNonceResults { pub fn account_nonce(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, RESULT_ACCOUNT_NONCE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(RESULT_ACCOUNT_NONCE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetAccountNonceResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetAccountNonceResults { pub fn account_nonce(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, RESULT_ACCOUNT_NONCE.get_key_id()) + ScMutableInt64::new(self.proxy.root(RESULT_ACCOUNT_NONCE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableTotalAssetsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableTotalAssetsResults { pub fn balances(&self) -> MapColorToImmutableInt64 { - MapColorToImmutableInt64 { obj_id: self.id } + MapColorToImmutableInt64 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableTotalAssetsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableTotalAssetsResults { pub fn balances(&self) -> MapColorToMutableInt64 { - MapColorToMutableInt64 { obj_id: self.id } + MapColorToMutableInt64 { proxy: self.proxy.clone() } } } diff --git a/packages/vm/wasmlib/src/coreblob/consts.rs b/packages/wasmvm/wasmlib/src/coreblob/consts.rs similarity index 100% rename from packages/vm/wasmlib/src/coreblob/consts.rs rename to packages/wasmvm/wasmlib/src/coreblob/consts.rs diff --git a/packages/vm/wasmlib/src/coreblob/contract.rs b/packages/wasmvm/wasmlib/src/coreblob/contract.rs similarity index 51% rename from packages/vm/wasmlib/src/coreblob/contract.rs rename to packages/wasmvm/wasmlib/src/coreblob/contract.rs index 0f080a4c02..f1f94cefd3 100644 --- a/packages/vm/wasmlib/src/coreblob/contract.rs +++ b/packages/wasmvm/wasmlib/src/coreblob/contract.rs @@ -7,10 +7,8 @@ #![allow(dead_code)] -use std::ptr; - -use crate::*; use crate::coreblob::*; +use crate::*; pub struct StoreBlobCall { pub func: ScFunc, @@ -39,42 +37,45 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn store_blob(_ctx: & dyn ScFuncCallContext) -> StoreBlobCall { + pub fn store_blob(_ctx: &dyn ScFuncCallContext) -> StoreBlobCall { let mut f = StoreBlobCall { func: ScFunc::new(HSC_NAME, HFUNC_STORE_BLOB), - params: MutableStoreBlobParams { id: 0 }, - results: ImmutableStoreBlobResults { id: 0 }, + params: MutableStoreBlobParams { proxy: Proxy::nil() }, + results: ImmutableStoreBlobResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScFunc::link_params(&mut f.params.proxy, &f.func); + ScFunc::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_blob_field(_ctx: & dyn ScViewCallContext) -> GetBlobFieldCall { + pub fn get_blob_field(_ctx: &dyn ScViewCallContext) -> GetBlobFieldCall { let mut f = GetBlobFieldCall { func: ScView::new(HSC_NAME, HVIEW_GET_BLOB_FIELD), - params: MutableGetBlobFieldParams { id: 0 }, - results: ImmutableGetBlobFieldResults { id: 0 }, + params: MutableGetBlobFieldParams { proxy: Proxy::nil() }, + results: ImmutableGetBlobFieldResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_blob_info(_ctx: & dyn ScViewCallContext) -> GetBlobInfoCall { + pub fn get_blob_info(_ctx: &dyn ScViewCallContext) -> GetBlobInfoCall { let mut f = GetBlobInfoCall { func: ScView::new(HSC_NAME, HVIEW_GET_BLOB_INFO), - params: MutableGetBlobInfoParams { id: 0 }, - results: ImmutableGetBlobInfoResults { id: 0 }, + params: MutableGetBlobInfoParams { proxy: Proxy::nil() }, + results: ImmutableGetBlobInfoResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn list_blobs(_ctx: & dyn ScViewCallContext) -> ListBlobsCall { + pub fn list_blobs(_ctx: &dyn ScViewCallContext) -> ListBlobsCall { let mut f = ListBlobsCall { func: ScView::new(HSC_NAME, HVIEW_LIST_BLOBS), - results: ImmutableListBlobsResults { id: 0 }, + results: ImmutableListBlobsResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/packages/vm/wasmlib/src/coreblob/mod.rs b/packages/wasmvm/wasmlib/src/coreblob/mod.rs similarity index 100% rename from packages/vm/wasmlib/src/coreblob/mod.rs rename to packages/wasmvm/wasmlib/src/coreblob/mod.rs diff --git a/packages/vm/wasmlib/src/coreblob/params.rs b/packages/wasmvm/wasmlib/src/coreblob/params.rs similarity index 59% rename from packages/vm/wasmlib/src/coreblob/params.rs rename to packages/wasmvm/wasmlib/src/coreblob/params.rs index 736edcdcfd..e57029ccfd 100644 --- a/packages/vm/wasmlib/src/coreblob/params.rs +++ b/packages/wasmvm/wasmlib/src/coreblob/params.rs @@ -8,106 +8,105 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreblob::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableBytes { pub fn get_bytes(&self, key: &str) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, key.get_key_id()) + ScImmutableBytes::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableStoreBlobParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableStoreBlobParams { pub fn blobs(&self) -> MapStringToImmutableBytes { - MapStringToImmutableBytes { obj_id: self.id } + MapStringToImmutableBytes { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableBytes { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bytes(&self, key: &str) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, key.get_key_id()) + ScMutableBytes::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableStoreBlobParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableStoreBlobParams { pub fn blobs(&self) -> MapStringToMutableBytes { - MapStringToMutableBytes { obj_id: self.id } + MapStringToMutableBytes { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetBlobFieldParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetBlobFieldParams { pub fn field(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_FIELD.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_FIELD)) } pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetBlobFieldParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetBlobFieldParams { pub fn field(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_FIELD.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_FIELD)) } pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetBlobInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetBlobInfoParams { pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetBlobInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetBlobInfoParams { pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_HASH)) } } diff --git a/packages/vm/wasmlib/src/coreblob/results.rs b/packages/wasmvm/wasmlib/src/coreblob/results.rs similarity index 60% rename from packages/vm/wasmlib/src/coreblob/results.rs rename to packages/wasmvm/wasmlib/src/coreblob/results.rs index c040ca1241..5cf71cd7ec 100644 --- a/packages/vm/wasmlib/src/coreblob/results.rs +++ b/packages/wasmvm/wasmlib/src/coreblob/results.rs @@ -8,146 +8,145 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreblob::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableStoreBlobResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableStoreBlobResults { pub fn hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, RESULT_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(RESULT_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableStoreBlobResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableStoreBlobResults { pub fn hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, RESULT_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(RESULT_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetBlobFieldResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetBlobFieldResults { pub fn bytes(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_BYTES.get_key_id()) + ScImmutableBytes::new(self.proxy.root(RESULT_BYTES)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetBlobFieldResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetBlobFieldResults { pub fn bytes(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_BYTES.get_key_id()) + ScMutableBytes::new(self.proxy.root(RESULT_BYTES)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToImmutableInt32 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToImmutableInt32 { pub fn get_int32(&self, key: &str) -> ScImmutableInt32 { - ScImmutableInt32::new(self.obj_id, key.get_key_id()) + ScImmutableInt32::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetBlobInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetBlobInfoResults { pub fn blob_sizes(&self) -> MapStringToImmutableInt32 { - MapStringToImmutableInt32 { obj_id: self.id } + MapStringToImmutableInt32 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapStringToMutableInt32 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapStringToMutableInt32 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_int32(&self, key: &str) -> ScMutableInt32 { - ScMutableInt32::new(self.obj_id, key.get_key_id()) + ScMutableInt32::new(self.proxy.key(&string_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetBlobInfoResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetBlobInfoResults { pub fn blob_sizes(&self) -> MapStringToMutableInt32 { - MapStringToMutableInt32 { obj_id: self.id } + MapStringToMutableInt32 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToImmutableInt32 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToImmutableInt32 { pub fn get_int32(&self, key: &ScHash) -> ScImmutableInt32 { - ScImmutableInt32::new(self.obj_id, key.get_key_id()) + ScImmutableInt32::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableListBlobsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableListBlobsResults { pub fn blob_sizes(&self) -> MapHashToImmutableInt32 { - MapHashToImmutableInt32 { obj_id: self.id } + MapHashToImmutableInt32 { proxy: self.proxy.clone() } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHashToMutableInt32 { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHashToMutableInt32 { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_int32(&self, key: &ScHash) -> ScMutableInt32 { - ScMutableInt32::new(self.obj_id, key.get_key_id()) + ScMutableInt32::new(self.proxy.key(&hash_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableListBlobsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableListBlobsResults { pub fn blob_sizes(&self) -> MapHashToMutableInt32 { - MapHashToMutableInt32 { obj_id: self.id } + MapHashToMutableInt32 { proxy: self.proxy.clone() } } } diff --git a/packages/vm/wasmlib/src/coreblocklog/consts.rs b/packages/wasmvm/wasmlib/src/coreblocklog/consts.rs similarity index 100% rename from packages/vm/wasmlib/src/coreblocklog/consts.rs rename to packages/wasmvm/wasmlib/src/coreblocklog/consts.rs diff --git a/packages/wasmvm/wasmlib/src/coreblocklog/contract.rs b/packages/wasmvm/wasmlib/src/coreblocklog/contract.rs new file mode 100644 index 0000000000..40b9faee86 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/coreblocklog/contract.rs @@ -0,0 +1,180 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] + +use crate::coreblocklog::*; +use crate::*; + +pub struct ControlAddressesCall { + pub func: ScView, + pub results: ImmutableControlAddressesResults, +} + +pub struct GetBlockInfoCall { + pub func: ScView, + pub params: MutableGetBlockInfoParams, + pub results: ImmutableGetBlockInfoResults, +} + +pub struct GetEventsForBlockCall { + pub func: ScView, + pub params: MutableGetEventsForBlockParams, + pub results: ImmutableGetEventsForBlockResults, +} + +pub struct GetEventsForContractCall { + pub func: ScView, + pub params: MutableGetEventsForContractParams, + pub results: ImmutableGetEventsForContractResults, +} + +pub struct GetEventsForRequestCall { + pub func: ScView, + pub params: MutableGetEventsForRequestParams, + pub results: ImmutableGetEventsForRequestResults, +} + +pub struct GetLatestBlockInfoCall { + pub func: ScView, + pub results: ImmutableGetLatestBlockInfoResults, +} + +pub struct GetRequestIDsForBlockCall { + pub func: ScView, + pub params: MutableGetRequestIDsForBlockParams, + pub results: ImmutableGetRequestIDsForBlockResults, +} + +pub struct GetRequestReceiptCall { + pub func: ScView, + pub params: MutableGetRequestReceiptParams, + pub results: ImmutableGetRequestReceiptResults, +} + +pub struct GetRequestReceiptsForBlockCall { + pub func: ScView, + pub params: MutableGetRequestReceiptsForBlockParams, + pub results: ImmutableGetRequestReceiptsForBlockResults, +} + +pub struct IsRequestProcessedCall { + pub func: ScView, + pub params: MutableIsRequestProcessedParams, + pub results: ImmutableIsRequestProcessedResults, +} + +pub struct ScFuncs { +} + +impl ScFuncs { + pub fn control_addresses(_ctx: &dyn ScViewCallContext) -> ControlAddressesCall { + let mut f = ControlAddressesCall { + func: ScView::new(HSC_NAME, HVIEW_CONTROL_ADDRESSES), + results: ImmutableControlAddressesResults { proxy: Proxy::nil() }, + }; + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_block_info(_ctx: &dyn ScViewCallContext) -> GetBlockInfoCall { + let mut f = GetBlockInfoCall { + func: ScView::new(HSC_NAME, HVIEW_GET_BLOCK_INFO), + params: MutableGetBlockInfoParams { proxy: Proxy::nil() }, + results: ImmutableGetBlockInfoResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_events_for_block(_ctx: &dyn ScViewCallContext) -> GetEventsForBlockCall { + let mut f = GetEventsForBlockCall { + func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_BLOCK), + params: MutableGetEventsForBlockParams { proxy: Proxy::nil() }, + results: ImmutableGetEventsForBlockResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_events_for_contract(_ctx: &dyn ScViewCallContext) -> GetEventsForContractCall { + let mut f = GetEventsForContractCall { + func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_CONTRACT), + params: MutableGetEventsForContractParams { proxy: Proxy::nil() }, + results: ImmutableGetEventsForContractResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_events_for_request(_ctx: &dyn ScViewCallContext) -> GetEventsForRequestCall { + let mut f = GetEventsForRequestCall { + func: ScView::new(HSC_NAME, HVIEW_GET_EVENTS_FOR_REQUEST), + params: MutableGetEventsForRequestParams { proxy: Proxy::nil() }, + results: ImmutableGetEventsForRequestResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_latest_block_info(_ctx: &dyn ScViewCallContext) -> GetLatestBlockInfoCall { + let mut f = GetLatestBlockInfoCall { + func: ScView::new(HSC_NAME, HVIEW_GET_LATEST_BLOCK_INFO), + results: ImmutableGetLatestBlockInfoResults { proxy: Proxy::nil() }, + }; + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_request_i_ds_for_block(_ctx: &dyn ScViewCallContext) -> GetRequestIDsForBlockCall { + let mut f = GetRequestIDsForBlockCall { + func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_I_DS_FOR_BLOCK), + params: MutableGetRequestIDsForBlockParams { proxy: Proxy::nil() }, + results: ImmutableGetRequestIDsForBlockResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_request_receipt(_ctx: &dyn ScViewCallContext) -> GetRequestReceiptCall { + let mut f = GetRequestReceiptCall { + func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_RECEIPT), + params: MutableGetRequestReceiptParams { proxy: Proxy::nil() }, + results: ImmutableGetRequestReceiptResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn get_request_receipts_for_block(_ctx: &dyn ScViewCallContext) -> GetRequestReceiptsForBlockCall { + let mut f = GetRequestReceiptsForBlockCall { + func: ScView::new(HSC_NAME, HVIEW_GET_REQUEST_RECEIPTS_FOR_BLOCK), + params: MutableGetRequestReceiptsForBlockParams { proxy: Proxy::nil() }, + results: ImmutableGetRequestReceiptsForBlockResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } + + pub fn is_request_processed(_ctx: &dyn ScViewCallContext) -> IsRequestProcessedCall { + let mut f = IsRequestProcessedCall { + func: ScView::new(HSC_NAME, HVIEW_IS_REQUEST_PROCESSED), + params: MutableIsRequestProcessedParams { proxy: Proxy::nil() }, + results: ImmutableIsRequestProcessedResults { proxy: Proxy::nil() }, + }; + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); + f + } +} diff --git a/packages/vm/wasmlib/src/coreblocklog/mod.rs b/packages/wasmvm/wasmlib/src/coreblocklog/mod.rs similarity index 100% rename from packages/vm/wasmlib/src/coreblocklog/mod.rs rename to packages/wasmvm/wasmlib/src/coreblocklog/mod.rs diff --git a/packages/wasmvm/wasmlib/src/coreblocklog/params.rs b/packages/wasmvm/wasmlib/src/coreblocklog/params.rs new file mode 100644 index 0000000000..ff71589a85 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/coreblocklog/params.rs @@ -0,0 +1,204 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] +#![allow(unused_imports)] + +use crate::coreblocklog::*; +use crate::*; + +#[derive(Clone)] +pub struct ImmutableGetBlockInfoParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetBlockInfoParams { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct MutableGetBlockInfoParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetBlockInfoParams { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForBlockParams { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForBlockParams { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForContractParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForContractParams { + pub fn contract_hname(&self) -> ScImmutableHname { + ScImmutableHname::new(self.proxy.root(PARAM_CONTRACT_HNAME)) + } + + pub fn from_block(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_FROM_BLOCK)) + } + + pub fn to_block(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_TO_BLOCK)) + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForContractParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForContractParams { + pub fn contract_hname(&self) -> ScMutableHname { + ScMutableHname::new(self.proxy.root(PARAM_CONTRACT_HNAME)) + } + + pub fn from_block(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_FROM_BLOCK)) + } + + pub fn to_block(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_TO_BLOCK)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForRequestParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForRequestParams { + pub fn request_id(&self) -> ScImmutableRequestID { + ScImmutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForRequestParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForRequestParams { + pub fn request_id(&self) -> ScMutableRequestID { + ScMutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestIDsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestIDsForBlockParams { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct MutableGetRequestIDsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestIDsForBlockParams { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestReceiptParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestReceiptParams { + pub fn request_id(&self) -> ScImmutableRequestID { + ScImmutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} + +#[derive(Clone)] +pub struct MutableGetRequestReceiptParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestReceiptParams { + pub fn request_id(&self) -> ScMutableRequestID { + ScMutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestReceiptsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestReceiptsForBlockParams { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct MutableGetRequestReceiptsForBlockParams { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestReceiptsForBlockParams { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(PARAM_BLOCK_INDEX)) + } +} + +#[derive(Clone)] +pub struct ImmutableIsRequestProcessedParams { + pub(crate) proxy: Proxy, +} + +impl ImmutableIsRequestProcessedParams { + pub fn request_id(&self) -> ScImmutableRequestID { + ScImmutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} + +#[derive(Clone)] +pub struct MutableIsRequestProcessedParams { + pub(crate) proxy: Proxy, +} + +impl MutableIsRequestProcessedParams { + pub fn request_id(&self) -> ScMutableRequestID { + ScMutableRequestID::new(self.proxy.root(PARAM_REQUEST_ID)) + } +} diff --git a/packages/wasmvm/wasmlib/src/coreblocklog/results.rs b/packages/wasmvm/wasmlib/src/coreblocklog/results.rs new file mode 100644 index 0000000000..983409e75a --- /dev/null +++ b/packages/wasmvm/wasmlib/src/coreblocklog/results.rs @@ -0,0 +1,348 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] +#![allow(unused_imports)] + +use crate::coreblocklog::*; +use crate::*; + +#[derive(Clone)] +pub struct ImmutableControlAddressesResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableControlAddressesResults { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn governing_address(&self) -> ScImmutableAddress { + ScImmutableAddress::new(self.proxy.root(RESULT_GOVERNING_ADDRESS)) + } + + pub fn state_controller_address(&self) -> ScImmutableAddress { + ScImmutableAddress::new(self.proxy.root(RESULT_STATE_CONTROLLER_ADDRESS)) + } +} + +#[derive(Clone)] +pub struct MutableControlAddressesResults { + pub(crate) proxy: Proxy, +} + +impl MutableControlAddressesResults { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn governing_address(&self) -> ScMutableAddress { + ScMutableAddress::new(self.proxy.root(RESULT_GOVERNING_ADDRESS)) + } + + pub fn state_controller_address(&self) -> ScMutableAddress { + ScMutableAddress::new(self.proxy.root(RESULT_STATE_CONTROLLER_ADDRESS)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetBlockInfoResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetBlockInfoResults { + pub fn block_info(&self) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.root(RESULT_BLOCK_INFO)) + } +} + +#[derive(Clone)] +pub struct MutableGetBlockInfoResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetBlockInfoResults { + pub fn block_info(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.root(RESULT_BLOCK_INFO)) + } +} + +#[derive(Clone)] +pub struct ArrayOfImmutableBytes { + pub(crate) proxy: Proxy, +} + +impl ArrayOfImmutableBytes { + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_bytes(&self, index: u32) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForBlockResults { + pub fn event(&self) -> ArrayOfImmutableBytes { + ArrayOfImmutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct ArrayOfMutableBytes { + pub(crate) proxy: Proxy, +} + +impl ArrayOfMutableBytes { + pub fn append_bytes(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); + } + + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_bytes(&self, index: u32) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForBlockResults { + pub fn event(&self) -> ArrayOfMutableBytes { + ArrayOfMutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForContractResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForContractResults { + pub fn event(&self) -> ArrayOfImmutableBytes { + ArrayOfImmutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForContractResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForContractResults { + pub fn event(&self) -> ArrayOfMutableBytes { + ArrayOfMutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct ImmutableGetEventsForRequestResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetEventsForRequestResults { + pub fn event(&self) -> ArrayOfImmutableBytes { + ArrayOfImmutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct MutableGetEventsForRequestResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetEventsForRequestResults { + pub fn event(&self) -> ArrayOfMutableBytes { + ArrayOfMutableBytes { proxy: self.proxy.root(RESULT_EVENT) } + } +} + +#[derive(Clone)] +pub struct ImmutableGetLatestBlockInfoResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetLatestBlockInfoResults { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn block_info(&self) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.root(RESULT_BLOCK_INFO)) + } +} + +#[derive(Clone)] +pub struct MutableGetLatestBlockInfoResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetLatestBlockInfoResults { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn block_info(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.root(RESULT_BLOCK_INFO)) + } +} + +#[derive(Clone)] +pub struct ArrayOfImmutableRequestID { + pub(crate) proxy: Proxy, +} + +impl ArrayOfImmutableRequestID { + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_request_id(&self, index: u32) -> ScImmutableRequestID { + ScImmutableRequestID::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestIDsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestIDsForBlockResults { + pub fn request_id(&self) -> ArrayOfImmutableRequestID { + ArrayOfImmutableRequestID { proxy: self.proxy.root(RESULT_REQUEST_ID) } + } +} + +#[derive(Clone)] +pub struct ArrayOfMutableRequestID { + pub(crate) proxy: Proxy, +} + +impl ArrayOfMutableRequestID { + pub fn append_request_id(&self) -> ScMutableRequestID { + ScMutableRequestID::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); + } + + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_request_id(&self, index: u32) -> ScMutableRequestID { + ScMutableRequestID::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct MutableGetRequestIDsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestIDsForBlockResults { + pub fn request_id(&self) -> ArrayOfMutableRequestID { + ArrayOfMutableRequestID { proxy: self.proxy.root(RESULT_REQUEST_ID) } + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestReceiptResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestReceiptResults { + pub fn block_index(&self) -> ScImmutableUint32 { + ScImmutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn request_index(&self) -> ScImmutableUint16 { + ScImmutableUint16::new(self.proxy.root(RESULT_REQUEST_INDEX)) + } + + pub fn request_record(&self) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.root(RESULT_REQUEST_RECORD)) + } +} + +#[derive(Clone)] +pub struct MutableGetRequestReceiptResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestReceiptResults { + pub fn block_index(&self) -> ScMutableUint32 { + ScMutableUint32::new(self.proxy.root(RESULT_BLOCK_INDEX)) + } + + pub fn request_index(&self) -> ScMutableUint16 { + ScMutableUint16::new(self.proxy.root(RESULT_REQUEST_INDEX)) + } + + pub fn request_record(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.root(RESULT_REQUEST_RECORD)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetRequestReceiptsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetRequestReceiptsForBlockResults { + pub fn request_record(&self) -> ArrayOfImmutableBytes { + ArrayOfImmutableBytes { proxy: self.proxy.root(RESULT_REQUEST_RECORD) } + } +} + +#[derive(Clone)] +pub struct MutableGetRequestReceiptsForBlockResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetRequestReceiptsForBlockResults { + pub fn request_record(&self) -> ArrayOfMutableBytes { + ArrayOfMutableBytes { proxy: self.proxy.root(RESULT_REQUEST_RECORD) } + } +} + +#[derive(Clone)] +pub struct ImmutableIsRequestProcessedResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableIsRequestProcessedResults { + pub fn request_processed(&self) -> ScImmutableString { + ScImmutableString::new(self.proxy.root(RESULT_REQUEST_PROCESSED)) + } +} + +#[derive(Clone)] +pub struct MutableIsRequestProcessedResults { + pub(crate) proxy: Proxy, +} + +impl MutableIsRequestProcessedResults { + pub fn request_processed(&self) -> ScMutableString { + ScMutableString::new(self.proxy.root(RESULT_REQUEST_PROCESSED)) + } +} diff --git a/packages/vm/wasmlib/src/coregovernance/consts.rs b/packages/wasmvm/wasmlib/src/coregovernance/consts.rs similarity index 100% rename from packages/vm/wasmlib/src/coregovernance/consts.rs rename to packages/wasmvm/wasmlib/src/coregovernance/consts.rs diff --git a/packages/vm/wasmlib/src/coregovernance/contract.rs b/packages/wasmvm/wasmlib/src/coregovernance/contract.rs similarity index 57% rename from packages/vm/wasmlib/src/coregovernance/contract.rs rename to packages/wasmvm/wasmlib/src/coregovernance/contract.rs index 333b15d675..b3a24a56ce 100644 --- a/packages/vm/wasmlib/src/coregovernance/contract.rs +++ b/packages/wasmvm/wasmlib/src/coregovernance/contract.rs @@ -7,10 +7,8 @@ #![allow(dead_code)] -use std::ptr; - -use crate::*; use crate::coregovernance::*; +use crate::*; pub struct AddAllowedStateControllerAddressCall { pub func: ScFunc, @@ -76,109 +74,110 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn add_allowed_state_controller_address(_ctx: & dyn ScFuncCallContext) -> AddAllowedStateControllerAddressCall { + pub fn add_allowed_state_controller_address(_ctx: &dyn ScFuncCallContext) -> AddAllowedStateControllerAddressCall { let mut f = AddAllowedStateControllerAddressCall { func: ScFunc::new(HSC_NAME, HFUNC_ADD_ALLOWED_STATE_CONTROLLER_ADDRESS), - params: MutableAddAllowedStateControllerAddressParams { id: 0 }, + params: MutableAddAllowedStateControllerAddressParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn claim_chain_ownership(_ctx: & dyn ScFuncCallContext) -> ClaimChainOwnershipCall { + pub fn claim_chain_ownership(_ctx: &dyn ScFuncCallContext) -> ClaimChainOwnershipCall { ClaimChainOwnershipCall { func: ScFunc::new(HSC_NAME, HFUNC_CLAIM_CHAIN_OWNERSHIP), } } - pub fn delegate_chain_ownership(_ctx: & dyn ScFuncCallContext) -> DelegateChainOwnershipCall { + pub fn delegate_chain_ownership(_ctx: &dyn ScFuncCallContext) -> DelegateChainOwnershipCall { let mut f = DelegateChainOwnershipCall { func: ScFunc::new(HSC_NAME, HFUNC_DELEGATE_CHAIN_OWNERSHIP), - params: MutableDelegateChainOwnershipParams { id: 0 }, + params: MutableDelegateChainOwnershipParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn remove_allowed_state_controller_address(_ctx: & dyn ScFuncCallContext) -> RemoveAllowedStateControllerAddressCall { + pub fn remove_allowed_state_controller_address(_ctx: &dyn ScFuncCallContext) -> RemoveAllowedStateControllerAddressCall { let mut f = RemoveAllowedStateControllerAddressCall { func: ScFunc::new(HSC_NAME, HFUNC_REMOVE_ALLOWED_STATE_CONTROLLER_ADDRESS), - params: MutableRemoveAllowedStateControllerAddressParams { id: 0 }, + params: MutableRemoveAllowedStateControllerAddressParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn rotate_state_controller(_ctx: & dyn ScFuncCallContext) -> RotateStateControllerCall { + pub fn rotate_state_controller(_ctx: &dyn ScFuncCallContext) -> RotateStateControllerCall { let mut f = RotateStateControllerCall { func: ScFunc::new(HSC_NAME, HFUNC_ROTATE_STATE_CONTROLLER), - params: MutableRotateStateControllerParams { id: 0 }, + params: MutableRotateStateControllerParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_chain_info(_ctx: & dyn ScFuncCallContext) -> SetChainInfoCall { + pub fn set_chain_info(_ctx: &dyn ScFuncCallContext) -> SetChainInfoCall { let mut f = SetChainInfoCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_CHAIN_INFO), - params: MutableSetChainInfoParams { id: 0 }, + params: MutableSetChainInfoParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_contract_fee(_ctx: & dyn ScFuncCallContext) -> SetContractFeeCall { + pub fn set_contract_fee(_ctx: &dyn ScFuncCallContext) -> SetContractFeeCall { let mut f = SetContractFeeCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_CONTRACT_FEE), - params: MutableSetContractFeeParams { id: 0 }, + params: MutableSetContractFeeParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn set_default_fee(_ctx: & dyn ScFuncCallContext) -> SetDefaultFeeCall { + pub fn set_default_fee(_ctx: &dyn ScFuncCallContext) -> SetDefaultFeeCall { let mut f = SetDefaultFeeCall { func: ScFunc::new(HSC_NAME, HFUNC_SET_DEFAULT_FEE), - params: MutableSetDefaultFeeParams { id: 0 }, + params: MutableSetDefaultFeeParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn get_allowed_state_controller_addresses(_ctx: & dyn ScViewCallContext) -> GetAllowedStateControllerAddressesCall { + pub fn get_allowed_state_controller_addresses(_ctx: &dyn ScViewCallContext) -> GetAllowedStateControllerAddressesCall { let mut f = GetAllowedStateControllerAddressesCall { func: ScView::new(HSC_NAME, HVIEW_GET_ALLOWED_STATE_CONTROLLER_ADDRESSES), - results: ImmutableGetAllowedStateControllerAddressesResults { id: 0 }, + results: ImmutableGetAllowedStateControllerAddressesResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_chain_info(_ctx: & dyn ScViewCallContext) -> GetChainInfoCall { + pub fn get_chain_info(_ctx: &dyn ScViewCallContext) -> GetChainInfoCall { let mut f = GetChainInfoCall { func: ScView::new(HSC_NAME, HVIEW_GET_CHAIN_INFO), - results: ImmutableGetChainInfoResults { id: 0 }, + results: ImmutableGetChainInfoResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_fee_info(_ctx: & dyn ScViewCallContext) -> GetFeeInfoCall { + pub fn get_fee_info(_ctx: &dyn ScViewCallContext) -> GetFeeInfoCall { let mut f = GetFeeInfoCall { func: ScView::new(HSC_NAME, HVIEW_GET_FEE_INFO), - params: MutableGetFeeInfoParams { id: 0 }, - results: ImmutableGetFeeInfoResults { id: 0 }, + params: MutableGetFeeInfoParams { proxy: Proxy::nil() }, + results: ImmutableGetFeeInfoResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_max_blob_size(_ctx: & dyn ScViewCallContext) -> GetMaxBlobSizeCall { + pub fn get_max_blob_size(_ctx: &dyn ScViewCallContext) -> GetMaxBlobSizeCall { let mut f = GetMaxBlobSizeCall { func: ScView::new(HSC_NAME, HVIEW_GET_MAX_BLOB_SIZE), - results: ImmutableGetMaxBlobSizeResults { id: 0 }, + results: ImmutableGetMaxBlobSizeResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/packages/vm/wasmlib/src/coregovernance/mod.rs b/packages/wasmvm/wasmlib/src/coregovernance/mod.rs similarity index 100% rename from packages/vm/wasmlib/src/coregovernance/mod.rs rename to packages/wasmvm/wasmlib/src/coregovernance/mod.rs diff --git a/packages/vm/wasmlib/src/coregovernance/params.rs b/packages/wasmvm/wasmlib/src/coregovernance/params.rs similarity index 55% rename from packages/vm/wasmlib/src/coregovernance/params.rs rename to packages/wasmvm/wasmlib/src/coregovernance/params.rs index e995d10b14..95fed7c058 100644 --- a/packages/vm/wasmlib/src/coregovernance/params.rs +++ b/packages/wasmvm/wasmlib/src/coregovernance/params.rs @@ -8,254 +8,253 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coregovernance::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableAddAllowedStateControllerAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableAddAllowedStateControllerAddressParams { pub fn chain_owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CHAIN_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER)) } pub fn fee_color(&self) -> ScImmutableColor { - ScImmutableColor::new(self.id, PARAM_FEE_COLOR.get_key_id()) + ScImmutableColor::new(self.proxy.root(PARAM_FEE_COLOR)) } pub fn state_controller_address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableAddAllowedStateControllerAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableAddAllowedStateControllerAddressParams { pub fn chain_owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CHAIN_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER)) } pub fn fee_color(&self) -> ScMutableColor { - ScMutableColor::new(self.id, PARAM_FEE_COLOR.get_key_id()) + ScMutableColor::new(self.proxy.root(PARAM_FEE_COLOR)) } pub fn state_controller_address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDelegateChainOwnershipParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDelegateChainOwnershipParams { pub fn chain_owner(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_CHAIN_OWNER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDelegateChainOwnershipParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDelegateChainOwnershipParams { pub fn chain_owner(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_CHAIN_OWNER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_CHAIN_OWNER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRemoveAllowedStateControllerAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRemoveAllowedStateControllerAddressParams { pub fn state_controller_address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRemoveAllowedStateControllerAddressParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRemoveAllowedStateControllerAddressParams { pub fn state_controller_address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRotateStateControllerParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRotateStateControllerParams { pub fn state_controller_address(&self) -> ScImmutableAddress { - ScImmutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScImmutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRotateStateControllerParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRotateStateControllerParams { pub fn state_controller_address(&self) -> ScMutableAddress { - ScMutableAddress::new(self.id, PARAM_STATE_CONTROLLER_ADDRESS.get_key_id()) + ScMutableAddress::new(self.proxy.root(PARAM_STATE_CONTROLLER_ADDRESS)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetChainInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetChainInfoParams { pub fn max_blob_size(&self) -> ScImmutableInt32 { - ScImmutableInt32::new(self.id, PARAM_MAX_BLOB_SIZE.get_key_id()) + ScImmutableInt32::new(self.proxy.root(PARAM_MAX_BLOB_SIZE)) } pub fn max_event_size(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, PARAM_MAX_EVENT_SIZE.get_key_id()) + ScImmutableInt16::new(self.proxy.root(PARAM_MAX_EVENT_SIZE)) } pub fn max_events_per_req(&self) -> ScImmutableInt16 { - ScImmutableInt16::new(self.id, PARAM_MAX_EVENTS_PER_REQ.get_key_id()) + ScImmutableInt16::new(self.proxy.root(PARAM_MAX_EVENTS_PER_REQ)) } pub fn owner_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetChainInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetChainInfoParams { pub fn max_blob_size(&self) -> ScMutableInt32 { - ScMutableInt32::new(self.id, PARAM_MAX_BLOB_SIZE.get_key_id()) + ScMutableInt32::new(self.proxy.root(PARAM_MAX_BLOB_SIZE)) } pub fn max_event_size(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, PARAM_MAX_EVENT_SIZE.get_key_id()) + ScMutableInt16::new(self.proxy.root(PARAM_MAX_EVENT_SIZE)) } pub fn max_events_per_req(&self) -> ScMutableInt16 { - ScMutableInt16::new(self.id, PARAM_MAX_EVENTS_PER_REQ.get_key_id()) + ScMutableInt16::new(self.proxy.root(PARAM_MAX_EVENTS_PER_REQ)) } pub fn owner_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetContractFeeParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetContractFeeParams { pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn owner_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetContractFeeParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetContractFeeParams { pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } pub fn owner_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableSetDefaultFeeParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableSetDefaultFeeParams { pub fn owner_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScImmutableInt64 { - ScImmutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScImmutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableSetDefaultFeeParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableSetDefaultFeeParams { pub fn owner_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_OWNER_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_OWNER_FEE)) } pub fn validator_fee(&self) -> ScMutableInt64 { - ScMutableInt64::new(self.id, PARAM_VALIDATOR_FEE.get_key_id()) + ScMutableInt64::new(self.proxy.root(PARAM_VALIDATOR_FEE)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetFeeInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetFeeInfoParams { pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetFeeInfoParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetFeeInfoParams { pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } } diff --git a/packages/wasmvm/wasmlib/src/coregovernance/results.rs b/packages/wasmvm/wasmlib/src/coregovernance/results.rs new file mode 100644 index 0000000000..f9a0e6ef23 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/coregovernance/results.rs @@ -0,0 +1,218 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] +#![allow(unused_imports)] + +use crate::coregovernance::*; +use crate::*; + +#[derive(Clone)] +pub struct ArrayOfImmutableBytes { + pub(crate) proxy: Proxy, +} + +impl ArrayOfImmutableBytes { + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_bytes(&self, index: u32) -> ScImmutableBytes { + ScImmutableBytes::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetAllowedStateControllerAddressesResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetAllowedStateControllerAddressesResults { + pub fn allowed_state_controller_addresses(&self) -> ArrayOfImmutableBytes { + ArrayOfImmutableBytes { proxy: self.proxy.root(RESULT_ALLOWED_STATE_CONTROLLER_ADDRESSES) } + } +} + +#[derive(Clone)] +pub struct ArrayOfMutableBytes { + pub(crate) proxy: Proxy, +} + +impl ArrayOfMutableBytes { + pub fn append_bytes(&self) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.append()) + } + + pub fn clear(&self) { + self.proxy.clear_array(); + } + + pub fn length(&self) -> u32 { + self.proxy.length() + } + + pub fn get_bytes(&self, index: u32) -> ScMutableBytes { + ScMutableBytes::new(self.proxy.index(index)) + } +} + +#[derive(Clone)] +pub struct MutableGetAllowedStateControllerAddressesResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetAllowedStateControllerAddressesResults { + pub fn allowed_state_controller_addresses(&self) -> ArrayOfMutableBytes { + ArrayOfMutableBytes { proxy: self.proxy.root(RESULT_ALLOWED_STATE_CONTROLLER_ADDRESSES) } + } +} + +#[derive(Clone)] +pub struct ImmutableGetChainInfoResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetChainInfoResults { + pub fn chain_id(&self) -> ScImmutableChainID { + ScImmutableChainID::new(self.proxy.root(RESULT_CHAIN_ID)) + } + + pub fn chain_owner_id(&self) -> ScImmutableAgentID { + ScImmutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) + } + + pub fn default_owner_fee(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_DEFAULT_OWNER_FEE)) + } + + pub fn default_validator_fee(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_DEFAULT_VALIDATOR_FEE)) + } + + pub fn description(&self) -> ScImmutableString { + ScImmutableString::new(self.proxy.root(RESULT_DESCRIPTION)) + } + + pub fn fee_color(&self) -> ScImmutableColor { + ScImmutableColor::new(self.proxy.root(RESULT_FEE_COLOR)) + } + + pub fn max_blob_size(&self) -> ScImmutableInt32 { + ScImmutableInt32::new(self.proxy.root(RESULT_MAX_BLOB_SIZE)) + } + + pub fn max_event_size(&self) -> ScImmutableInt16 { + ScImmutableInt16::new(self.proxy.root(RESULT_MAX_EVENT_SIZE)) + } + + pub fn max_events_per_req(&self) -> ScImmutableInt16 { + ScImmutableInt16::new(self.proxy.root(RESULT_MAX_EVENTS_PER_REQ)) + } +} + +#[derive(Clone)] +pub struct MutableGetChainInfoResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetChainInfoResults { + pub fn chain_id(&self) -> ScMutableChainID { + ScMutableChainID::new(self.proxy.root(RESULT_CHAIN_ID)) + } + + pub fn chain_owner_id(&self) -> ScMutableAgentID { + ScMutableAgentID::new(self.proxy.root(RESULT_CHAIN_OWNER_ID)) + } + + pub fn default_owner_fee(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_DEFAULT_OWNER_FEE)) + } + + pub fn default_validator_fee(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_DEFAULT_VALIDATOR_FEE)) + } + + pub fn description(&self) -> ScMutableString { + ScMutableString::new(self.proxy.root(RESULT_DESCRIPTION)) + } + + pub fn fee_color(&self) -> ScMutableColor { + ScMutableColor::new(self.proxy.root(RESULT_FEE_COLOR)) + } + + pub fn max_blob_size(&self) -> ScMutableInt32 { + ScMutableInt32::new(self.proxy.root(RESULT_MAX_BLOB_SIZE)) + } + + pub fn max_event_size(&self) -> ScMutableInt16 { + ScMutableInt16::new(self.proxy.root(RESULT_MAX_EVENT_SIZE)) + } + + pub fn max_events_per_req(&self) -> ScMutableInt16 { + ScMutableInt16::new(self.proxy.root(RESULT_MAX_EVENTS_PER_REQ)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetFeeInfoResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetFeeInfoResults { + pub fn fee_color(&self) -> ScImmutableColor { + ScImmutableColor::new(self.proxy.root(RESULT_FEE_COLOR)) + } + + pub fn owner_fee(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_OWNER_FEE)) + } + + pub fn validator_fee(&self) -> ScImmutableInt64 { + ScImmutableInt64::new(self.proxy.root(RESULT_VALIDATOR_FEE)) + } +} + +#[derive(Clone)] +pub struct MutableGetFeeInfoResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetFeeInfoResults { + pub fn fee_color(&self) -> ScMutableColor { + ScMutableColor::new(self.proxy.root(RESULT_FEE_COLOR)) + } + + pub fn owner_fee(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_OWNER_FEE)) + } + + pub fn validator_fee(&self) -> ScMutableInt64 { + ScMutableInt64::new(self.proxy.root(RESULT_VALIDATOR_FEE)) + } +} + +#[derive(Clone)] +pub struct ImmutableGetMaxBlobSizeResults { + pub(crate) proxy: Proxy, +} + +impl ImmutableGetMaxBlobSizeResults { + pub fn max_blob_size(&self) -> ScImmutableInt32 { + ScImmutableInt32::new(self.proxy.root(RESULT_MAX_BLOB_SIZE)) + } +} + +#[derive(Clone)] +pub struct MutableGetMaxBlobSizeResults { + pub(crate) proxy: Proxy, +} + +impl MutableGetMaxBlobSizeResults { + pub fn max_blob_size(&self) -> ScMutableInt32 { + ScMutableInt32::new(self.proxy.root(RESULT_MAX_BLOB_SIZE)) + } +} diff --git a/packages/vm/wasmlib/src/coreroot/consts.rs b/packages/wasmvm/wasmlib/src/coreroot/consts.rs similarity index 100% rename from packages/vm/wasmlib/src/coreroot/consts.rs rename to packages/wasmvm/wasmlib/src/coreroot/consts.rs diff --git a/packages/vm/wasmlib/src/coreroot/contract.rs b/packages/wasmvm/wasmlib/src/coreroot/contract.rs similarity index 55% rename from packages/vm/wasmlib/src/coreroot/contract.rs rename to packages/wasmvm/wasmlib/src/coreroot/contract.rs index 99fb71ce4c..038c957b54 100644 --- a/packages/vm/wasmlib/src/coreroot/contract.rs +++ b/packages/wasmvm/wasmlib/src/coreroot/contract.rs @@ -7,10 +7,8 @@ #![allow(dead_code)] -use std::ptr; - -use crate::*; use crate::coreroot::*; +use crate::*; pub struct DeployContractCall { pub func: ScFunc, @@ -42,49 +40,50 @@ pub struct ScFuncs { } impl ScFuncs { - pub fn deploy_contract(_ctx: & dyn ScFuncCallContext) -> DeployContractCall { + pub fn deploy_contract(_ctx: &dyn ScFuncCallContext) -> DeployContractCall { let mut f = DeployContractCall { func: ScFunc::new(HSC_NAME, HFUNC_DEPLOY_CONTRACT), - params: MutableDeployContractParams { id: 0 }, + params: MutableDeployContractParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn grant_deploy_permission(_ctx: & dyn ScFuncCallContext) -> GrantDeployPermissionCall { + pub fn grant_deploy_permission(_ctx: &dyn ScFuncCallContext) -> GrantDeployPermissionCall { let mut f = GrantDeployPermissionCall { func: ScFunc::new(HSC_NAME, HFUNC_GRANT_DEPLOY_PERMISSION), - params: MutableGrantDeployPermissionParams { id: 0 }, + params: MutableGrantDeployPermissionParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn revoke_deploy_permission(_ctx: & dyn ScFuncCallContext) -> RevokeDeployPermissionCall { + pub fn revoke_deploy_permission(_ctx: &dyn ScFuncCallContext) -> RevokeDeployPermissionCall { let mut f = RevokeDeployPermissionCall { func: ScFunc::new(HSC_NAME, HFUNC_REVOKE_DEPLOY_PERMISSION), - params: MutableRevokeDeployPermissionParams { id: 0 }, + params: MutableRevokeDeployPermissionParams { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, ptr::null_mut()); + ScFunc::link_params(&mut f.params.proxy, &f.func); f } - pub fn find_contract(_ctx: & dyn ScViewCallContext) -> FindContractCall { + pub fn find_contract(_ctx: &dyn ScViewCallContext) -> FindContractCall { let mut f = FindContractCall { func: ScView::new(HSC_NAME, HVIEW_FIND_CONTRACT), - params: MutableFindContractParams { id: 0 }, - results: ImmutableFindContractResults { id: 0 }, + params: MutableFindContractParams { proxy: Proxy::nil() }, + results: ImmutableFindContractResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(&mut f.params.id, &mut f.results.id); + ScView::link_params(&mut f.params.proxy, &f.func); + ScView::link_results(&mut f.results.proxy, &f.func); f } - pub fn get_contract_records(_ctx: & dyn ScViewCallContext) -> GetContractRecordsCall { + pub fn get_contract_records(_ctx: &dyn ScViewCallContext) -> GetContractRecordsCall { let mut f = GetContractRecordsCall { func: ScView::new(HSC_NAME, HVIEW_GET_CONTRACT_RECORDS), - results: ImmutableGetContractRecordsResults { id: 0 }, + results: ImmutableGetContractRecordsResults { proxy: Proxy::nil() }, }; - f.func.set_ptrs(ptr::null_mut(), &mut f.results.id); + ScView::link_results(&mut f.results.proxy, &f.func); f } } diff --git a/packages/vm/wasmlib/src/coreroot/mod.rs b/packages/wasmvm/wasmlib/src/coreroot/mod.rs similarity index 100% rename from packages/vm/wasmlib/src/coreroot/mod.rs rename to packages/wasmvm/wasmlib/src/coreroot/mod.rs diff --git a/packages/vm/wasmlib/src/coreroot/params.rs b/packages/wasmvm/wasmlib/src/coreroot/params.rs similarity index 58% rename from packages/vm/wasmlib/src/coreroot/params.rs rename to packages/wasmvm/wasmlib/src/coreroot/params.rs index 59257f5334..fb83c178db 100644 --- a/packages/vm/wasmlib/src/coreroot/params.rs +++ b/packages/wasmvm/wasmlib/src/coreroot/params.rs @@ -8,110 +8,109 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreroot::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableDeployContractParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableDeployContractParams { pub fn description(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } pub fn name(&self) -> ScImmutableString { - ScImmutableString::new(self.id, PARAM_NAME.get_key_id()) + ScImmutableString::new(self.proxy.root(PARAM_NAME)) } pub fn program_hash(&self) -> ScImmutableHash { - ScImmutableHash::new(self.id, PARAM_PROGRAM_HASH.get_key_id()) + ScImmutableHash::new(self.proxy.root(PARAM_PROGRAM_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableDeployContractParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableDeployContractParams { pub fn description(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_DESCRIPTION.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_DESCRIPTION)) } pub fn name(&self) -> ScMutableString { - ScMutableString::new(self.id, PARAM_NAME.get_key_id()) + ScMutableString::new(self.proxy.root(PARAM_NAME)) } pub fn program_hash(&self) -> ScMutableHash { - ScMutableHash::new(self.id, PARAM_PROGRAM_HASH.get_key_id()) + ScMutableHash::new(self.proxy.root(PARAM_PROGRAM_HASH)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGrantDeployPermissionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGrantDeployPermissionParams { pub fn deployer(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_DEPLOYER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_DEPLOYER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGrantDeployPermissionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGrantDeployPermissionParams { pub fn deployer(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_DEPLOYER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_DEPLOYER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableRevokeDeployPermissionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableRevokeDeployPermissionParams { pub fn deployer(&self) -> ScImmutableAgentID { - ScImmutableAgentID::new(self.id, PARAM_DEPLOYER.get_key_id()) + ScImmutableAgentID::new(self.proxy.root(PARAM_DEPLOYER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableRevokeDeployPermissionParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableRevokeDeployPermissionParams { pub fn deployer(&self) -> ScMutableAgentID { - ScMutableAgentID::new(self.id, PARAM_DEPLOYER.get_key_id()) + ScMutableAgentID::new(self.proxy.root(PARAM_DEPLOYER)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFindContractParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFindContractParams { pub fn hname(&self) -> ScImmutableHname { - ScImmutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScImmutableHname::new(self.proxy.root(PARAM_HNAME)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFindContractParams { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFindContractParams { pub fn hname(&self) -> ScMutableHname { - ScMutableHname::new(self.id, PARAM_HNAME.get_key_id()) + ScMutableHname::new(self.proxy.root(PARAM_HNAME)) } } diff --git a/packages/vm/wasmlib/src/coreroot/results.rs b/packages/wasmvm/wasmlib/src/coreroot/results.rs similarity index 56% rename from packages/vm/wasmlib/src/coreroot/results.rs rename to packages/wasmvm/wasmlib/src/coreroot/results.rs index 933c193392..6a758f705d 100644 --- a/packages/vm/wasmlib/src/coreroot/results.rs +++ b/packages/wasmvm/wasmlib/src/coreroot/results.rs @@ -8,86 +8,83 @@ #![allow(dead_code)] #![allow(unused_imports)] -use crate::*; use crate::coreroot::*; -use crate::host::*; +use crate::*; -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableFindContractResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableFindContractResults { pub fn contract_found(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_CONTRACT_FOUND.get_key_id()) + ScImmutableBytes::new(self.proxy.root(RESULT_CONTRACT_FOUND)) } pub fn contract_rec_data(&self) -> ScImmutableBytes { - ScImmutableBytes::new(self.id, RESULT_CONTRACT_REC_DATA.get_key_id()) + ScImmutableBytes::new(self.proxy.root(RESULT_CONTRACT_REC_DATA)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableFindContractResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableFindContractResults { pub fn contract_found(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_CONTRACT_FOUND.get_key_id()) + ScMutableBytes::new(self.proxy.root(RESULT_CONTRACT_FOUND)) } pub fn contract_rec_data(&self) -> ScMutableBytes { - ScMutableBytes::new(self.id, RESULT_CONTRACT_REC_DATA.get_key_id()) + ScMutableBytes::new(self.proxy.root(RESULT_CONTRACT_REC_DATA)) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHnameToImmutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHnameToImmutableBytes { pub fn get_bytes(&self, key: ScHname) -> ScImmutableBytes { - ScImmutableBytes::new(self.obj_id, key.get_key_id()) + ScImmutableBytes::new(self.proxy.key(&hname_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct ImmutableGetContractRecordsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl ImmutableGetContractRecordsResults { pub fn contract_registry(&self) -> MapHnameToImmutableBytes { - let map_id = get_object_id(self.id, RESULT_CONTRACT_REGISTRY.get_key_id(), TYPE_MAP); - MapHnameToImmutableBytes { obj_id: map_id } + MapHnameToImmutableBytes { proxy: self.proxy.root(RESULT_CONTRACT_REGISTRY) } } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MapHnameToMutableBytes { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl MapHnameToMutableBytes { pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } pub fn get_bytes(&self, key: ScHname) -> ScMutableBytes { - ScMutableBytes::new(self.obj_id, key.get_key_id()) + ScMutableBytes::new(self.proxy.key(&hname_to_bytes(key))) } } -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct MutableGetContractRecordsResults { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl MutableGetContractRecordsResults { pub fn contract_registry(&self) -> MapHnameToMutableBytes { - let map_id = get_object_id(self.id, RESULT_CONTRACT_REGISTRY.get_key_id(), TYPE_MAP); - MapHnameToMutableBytes { obj_id: map_id } + MapHnameToMutableBytes { proxy: self.proxy.root(RESULT_CONTRACT_REGISTRY) } } } diff --git a/packages/wasmvm/wasmlib/src/dict.rs b/packages/wasmvm/wasmlib/src/dict.rs new file mode 100644 index 0000000000..c418cefdcb --- /dev/null +++ b/packages/wasmvm/wasmlib/src/dict.rs @@ -0,0 +1,116 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::cell::RefCell; +use std::collections::BTreeMap; + +use crate::*; +use crate::host::*; + +pub struct ScImmutableDict { + dict: ScDict, +} + +impl ScImmutableDict { + pub fn new(dict: ScDict) -> ScImmutableDict { + ScImmutableDict { dict } + } + + pub fn exists(&self, key: &[u8]) -> bool { + self.dict.exists(key) + } + + pub fn get(&self, key: &[u8]) -> Vec { + self.dict.get(key) + } +} + +#[derive(Clone)] +pub struct ScDict { + dict: RefCell, Vec>>, + state: bool, +} + +impl ScDict { + pub fn new(buf: &[u8]) -> ScDict { + let dict = ScDict { dict: RefCell::new(BTreeMap::new()), state: false }; + dict.read_bytes(buf); + dict + } + + pub fn state() -> ScDict { + ScDict { dict: RefCell::new(BTreeMap::new()), state: true } + } + + pub fn copy(&self, buf: &[u8]) { + self.dict.borrow_mut().clear(); + self.read_bytes(buf); + } + + pub fn delete(&self, key: &[u8]) { + if self.state { + state_delete(key); + return; + } + self.dict.borrow_mut().remove(key); + } + + pub fn exists(&self, key: &[u8]) -> bool { + if self.state { + return state_exists(key); + } + self.dict.borrow().contains_key(key) + } + + pub fn get(&self, key: &[u8]) -> Vec { + if self.state { + return state_get(key); + } + let dict = self.dict.borrow(); + if !dict.contains_key(key) { + return Vec::new(); + } + dict.get(key).unwrap().to_vec() + } + + pub fn set(&self, key: &[u8], value: &[u8]) { + if self.state { + state_set(key, value); + return; + } + self.dict.borrow_mut().insert(key.to_vec(), value.to_vec()); + } + + fn read_bytes(&self, buf: &[u8]) { + if buf.len() != 0 { + let mut dec = WasmDecoder::new(buf); + let size = uint32_from_bytes(&dec.fixed_bytes(SC_UINT32_LENGTH)); + for _i in 0..size { + let key_buf = dec.fixed_bytes(SC_UINT16_LENGTH); + let key_len = uint16_from_bytes(&key_buf); + let key = dec.fixed_bytes(key_len as usize); + let val_buf = dec.fixed_bytes(SC_UINT32_LENGTH); + let val_len = uint32_from_bytes(&val_buf); + let val = dec.fixed_bytes(val_len as usize); + self.set(&key, &val); + } + } + } + + pub fn to_bytes(&self) -> Vec { + let dict = self.dict.borrow(); + if dict.len() == 0 { + return vec![0; SC_UINT32_LENGTH]; + } + + let mut enc = WasmEncoder::new(); + enc.fixed_bytes(&uint32_to_bytes(dict.len() as u32), SC_UINT32_LENGTH); + for (key, val) in dict.iter() { + enc.fixed_bytes(&uint16_to_bytes(key.len() as u16), SC_UINT16_LENGTH); + enc.fixed_bytes(key, key.len()); + enc.fixed_bytes(&uint32_to_bytes(val.len() as u32), SC_UINT32_LENGTH); + enc.fixed_bytes(val, val.len()); + } + return enc.buf(); + } +} diff --git a/packages/wasmvm/wasmlib/src/events.rs b/packages/wasmvm/wasmlib/src/events.rs new file mode 100644 index 0000000000..afa2b699f5 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/events.rs @@ -0,0 +1,29 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use crate::*; + +// encodes separate entities into a byte buffer +pub struct EventEncoder { + event: String, +} + +impl EventEncoder { + pub fn new(event_name: &str) -> EventEncoder { + let mut e = EventEncoder { event: event_name.to_string() }; + let timestamp = ScFuncContext {}.timestamp(); + e.encode(&uint64_to_string(timestamp / 1_000_000_000)); + e + } + + pub fn emit(&self) { + ScFuncContext {}.event(&self.event); + } + + pub fn encode(&mut self, value: &str) -> &EventEncoder { + // TODO encode potential vertical bars that are present in the value string + self.event += "|"; + self.event += &value; + self + } +} diff --git a/packages/wasmvm/wasmlib/src/exports.rs b/packages/wasmvm/wasmlib/src/exports.rs new file mode 100644 index 0000000000..73842f7c92 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/exports.rs @@ -0,0 +1,60 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// Provide host with details about funcs and views in this smart contract + +use crate::context::*; +use crate::host::*; + +// Note that we do not use the Wasm export symbol table on purpose +// because Wasm does not allow us to determine whether the symbols +// are meant as view or func, or meant as extra public callbacks +// generated by the compilation of the the Wasm code. +// There are only 2 symbols the ISCP host will actually look for +// in the export table: +// on_load (which must be defined by the SC code) and +// on_call (which is defined here as part of WasmLib) + +pub struct ScExportMap { + pub names: &'static [&'static str], + pub funcs: &'static [fn(&ScFuncContext)], + pub views: &'static [fn(&ScViewContext)], +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// context for on_load function to be able to tell host which +// funcs and views are available as entry points to the SC +pub struct ScExports {} + +impl ScExports { + // constructs the symbol export context for the on_load function + pub fn export(export_map: &ScExportMap) { + export_name(-1, "WASM::RUST"); + + for i in 0..export_map.funcs.len() { + export_name(i as i32, export_map.names[i]); + } + + let offset = export_map.funcs.len(); + for i in 0..export_map.views.len() { + export_name(i as i32 | 0x8000, export_map.names[offset + i]); + } + } + + // general entrypoint for the host to call any SC function + // the host will pass the index of one of the entry points + // that was provided by on_load during SC initialization + pub fn call(index: i32, export_map: &ScExportMap) { + if (index & 0x8000) == 0 { + // mutable full function, invoke with a func context + let func = export_map.funcs[index as usize]; + func(&ScFuncContext {}); + return; + } + // immutable view function, invoke with a view context + let view = export_map.views[(index & 0x7fff) as usize]; + view(&ScViewContext {}); + } +} + diff --git a/packages/wasmvm/wasmlib/src/host.rs b/packages/wasmvm/wasmlib/src/host.rs new file mode 100644 index 0000000000..a57dbd8a8c --- /dev/null +++ b/packages/wasmvm/wasmlib/src/host.rs @@ -0,0 +1,77 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// interface WasmLib to the VM host + +// These 2 external functions are funneling the entire +// WasmLib functionality to their counterparts on the host. +#[link(wasm_import_module = "WasmLib")] +extern { + pub fn hostStateGet(key_ref: *const u8, key_len: i32, val_ref: *const u8, val_len: i32) -> i32; + + pub fn hostStateSet(key_ref: *const u8, key_len: i32, val_ref: *const u8, val_len: i32); +} + +pub fn export_name(index: i32, name: &str) { + unsafe { + let buf = name.as_bytes(); + hostStateSet(std::ptr::null(), index, buf.as_ptr(), buf.len() as i32); + } +} + +pub fn sandbox(func_nr: i32, params: &[u8]) -> Vec { + unsafe { + // call sandbox function, result value will be cached by host + // always negative funcNr as keyLen indicates sandbox call + // this removes the need for a separate hostSandbox function + let size = hostStateGet(std::ptr::null(), func_nr, params.as_ptr(), params.len() as i32); + + // zero length, no need to retrieve cached value + if size == 0 { + return Vec::new(); + } + + // retrieve cached value from host + let mut result = vec![0_u8; size as usize]; + hostStateGet(std::ptr::null(), 0, result.as_mut_ptr(), size); + result + } +} + +pub fn state_delete(key: &[u8]) { + unsafe { + hostStateSet(key.as_ptr(), key.len() as i32, std::ptr::null(), -1); + } +} + +pub fn state_exists(key: &[u8]) -> bool { + unsafe { + hostStateGet(key.as_ptr(), key.len() as i32, std::ptr::null(), -1) >= 0 + } +} + +pub fn state_get(key: &[u8]) -> Vec { + unsafe { + // variable sized result expected, + // query size first by passing zero length buffer + // value will be cached by host + let size = hostStateGet(key.as_ptr(), key.len() as i32, std::ptr::null(), 0); + + // -1 means non-existent, return default empty buffer + // zero length, no need to retrieve cached value, return empty buffer + if size <= 0 { + return Vec::new(); + } + + // retrieve cached value from host + let mut result = vec![0_u8; size as usize]; + hostStateGet(std::ptr::null(), 0, result.as_mut_ptr(), size); + result + } +} + +pub fn state_set(key: &[u8], value: &[u8]) { + unsafe { + hostStateSet(key.as_ptr(), key.len() as i32, value.as_ptr(), value.len() as i32); + } +} diff --git a/packages/vm/wasmlib/src/lib.rs b/packages/wasmvm/wasmlib/src/lib.rs similarity index 74% rename from packages/vm/wasmlib/src/lib.rs rename to packages/wasmvm/wasmlib/src/lib.rs index 6b28fa2f1b..ac6f778d62 100644 --- a/packages/vm/wasmlib/src/lib.rs +++ b/packages/wasmvm/wasmlib/src/lib.rs @@ -3,31 +3,32 @@ #![allow(dead_code)] -pub use bytes::*; +pub use assets::*; pub use context::*; pub use contract::*; +pub use dict::*; pub use events::*; -pub use exports::ScExports; -pub use hashtypes::*; -pub use immutable::*; -pub use keys::*; -pub use mutable::*; +pub use exports::*; +pub use sandbox::*; +pub use sandboxutils::*; +pub use wasmtypes::*; -mod bytes; -mod context; -mod contract; +pub mod assets; +pub mod context; +pub mod contract; pub mod coreaccounts; pub mod coreblob; pub mod coreblocklog; pub mod coregovernance; pub mod coreroot; -mod events; -mod exports; -mod hashtypes; +pub mod dict; +pub mod events; +pub mod exports; pub mod host; -mod immutable; -pub mod keys; -mod mutable; +pub mod sandbox; +pub mod sandboxutils; +pub mod wasmrequests; +pub mod wasmtypes; // When the `wee_alloc` feature is enabled, // use `wee_alloc` as the global allocator. diff --git a/packages/wasmvm/wasmlib/src/sandbox.rs b/packages/wasmvm/wasmlib/src/sandbox.rs new file mode 100644 index 0000000000..92d14ae628 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/sandbox.rs @@ -0,0 +1,302 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::rc::Rc; + +use crate::*; +use crate::host::*; + +// @formatter:off +pub const FN_ACCOUNT_ID : i32 = -1; +pub const FN_BALANCE : i32 = -2; +pub const FN_BALANCES : i32 = -3; +pub const FN_BLOCK_CONTEXT : i32 = -4; +pub const FN_CALL : i32 = -5; +pub const FN_CALLER : i32 = -6; +pub const FN_CHAIN_ID : i32 = -7; +pub const FN_CHAIN_OWNER_ID : i32 = -8; +pub const FN_CONTRACT : i32 = -9; +pub const FN_CONTRACT_CREATOR : i32 = -10; +pub const FN_DEPLOY_CONTRACT : i32 = -11; +pub const FN_ENTROPY : i32 = -12; +pub const FN_EVENT : i32 = -13; +pub const FN_INCOMING_TRANSFER : i32 = -14; +pub const FN_LOG : i32 = -15; +pub const FN_MINTED : i32 = -16; +pub const FN_PANIC : i32 = -17; +pub const FN_PARAMS : i32 = -18; +pub const FN_POST : i32 = -19; +pub const FN_REQUEST : i32 = -20; +pub const FN_REQUEST_ID : i32 = -21; +pub const FN_RESULTS : i32 = -22; +pub const FN_SEND : i32 = -23; +pub const FN_STATE_ANCHOR : i32 = -24; +pub const FN_TIMESTAMP : i32 = -25; +pub const FN_TRACE : i32 = -26; +pub const FN_UTILS_BASE58_DECODE : i32 = -27; +pub const FN_UTILS_BASE58_ENCODE : i32 = -28; +pub const FN_UTILS_BLS_ADDRESS : i32 = -29; +pub const FN_UTILS_BLS_AGGREGATE : i32 = -30; +pub const FN_UTILS_BLS_VALID : i32 = -31; +pub const FN_UTILS_ED25519_ADDRESS : i32 = -32; +pub const FN_UTILS_ED25519_VALID : i32 = -33; +pub const FN_UTILS_HASH_BLAKE2B : i32 = -34; +pub const FN_UTILS_HASH_NAME : i32 = -35; +pub const FN_UTILS_HASH_SHA3 : i32 = -36; +// @formatter:on + +// Direct logging of informational text to host log +pub fn log(text: &str) { + sandbox(FN_LOG, text.as_bytes()); +} + +// Direct logging of error to host log, followed by panicking out of the Wasm code +pub fn panic(text: &str) { + sandbox(FN_PANIC, text.as_bytes()); +} + +// Direct logging of debug trace text to host log +pub fn trace(text: &str) { + sandbox(FN_TRACE, text.as_bytes()); +} + +pub fn params_proxy() -> Proxy { + let buf = sandbox(FN_PARAMS, &[]); + Proxy::new(&Rc::new(ScDict::new(&buf))) +} + +pub fn results_proxy() -> Proxy { + Proxy::new(&Rc::new(ScDict::new(&[]))) +} + +pub fn state_proxy() -> Proxy { + Proxy::new(&Rc::new(ScDict::state())) +} + +pub trait ScSandbox { + // retrieve the agent id of self contract account + fn account_id(&self) -> ScAgentID { + agent_id_from_bytes(&sandbox(FN_ACCOUNT_ID, &[])) + } + + fn balance(&self, color: ScColor) -> u64 { + uint64_from_bytes(&sandbox(FN_BALANCE, &color.to_bytes())) + } + + // access the current balances for all assets + fn balances(&self) -> ScBalances { + ScAssets::new(&sandbox(FN_BALANCES, &[])).balances() + } + + // calls a smart contract function + fn call_with_transfer(&self, h_contract: ScHname, h_function: ScHname, params: Option, transfer: Option) -> ScImmutableDict { + let mut req = wasmrequests::CallRequest { + contract: h_contract, + function: h_function, + params: vec![0; SC_UINT32_LENGTH], + transfer: vec![0; SC_UINT32_LENGTH], + }; + if let Some(params) = params { + req.params = params.to_bytes(); + } + if let Some(transfer) = transfer { + req.transfer = transfer.to_bytes(); + } + let buf = sandbox(FN_CALL, &req.to_bytes()); + ScImmutableDict::new(ScDict::new(&buf)) + } + + // retrieve the chain id of the chain self contract lives on + fn chain_id(&self) -> ScChainID { + chain_id_from_bytes(&sandbox(FN_CHAIN_ID, &[])) + } + + // retrieve the agent id of the owner of the chain self contract lives on + fn chain_owner_id(&self) -> ScAgentID { + agent_id_from_bytes(&sandbox(FN_CHAIN_OWNER_ID, &[])) + } + + // retrieve the hname of self contract + fn contract(&self) -> ScHname { + hname_from_bytes(&sandbox(FN_CONTRACT, &[])) + } + + // retrieve the agent id of the creator of self contract + fn contract_creator(&self) -> ScAgentID { + agent_id_from_bytes(&sandbox(FN_CONTRACT_CREATOR, &[])) + } + + // logs informational text message + fn log(&self, text: &str) { + sandbox(FN_LOG, &string_to_bytes(text)); + } + + // logs error text message and then panics + fn panic(&self, text: &str) { + sandbox(FN_PANIC, &string_to_bytes(text)); + } + + // retrieve parameters passed to the smart contract function that was called + fn params(&self) -> ScImmutableDict { + let buf = sandbox(FN_PARAMS, &[]); + ScImmutableDict::new(ScDict::new(&buf)) + } + + // panics if condition is not satisfied + fn require(&self, cond: bool, msg: &str) { + if !cond { + panic(msg) + } + } + + fn results(&self, results: &ScDict) { + sandbox(FN_RESULTS, &results.to_bytes()); + } + + // deterministic time stamp fixed at the moment of calling the smart contract + fn timestamp(&self) -> u64 { + uint64_from_bytes(&sandbox(FN_TIMESTAMP, &[])) + } + + // logs debugging trace text message + fn trace(&self, text: &str) { + sandbox(FN_TRACE, &string_to_bytes(text)); + } + + // access diverse utility functions + fn utility(&self) -> ScSandboxUtils { + ScSandboxUtils {} + } +} + +pub trait ScSandboxView: ScSandbox { + // calls a smart contract view + fn call(&self, h_contract: ScHname, h_function: ScHname, params: Option) -> ScImmutableDict { + return self.call_with_transfer(h_contract, h_function, params, None); + } + + fn raw_state(&self) -> ScImmutableDict { + ScImmutableDict::new(ScDict::state()) + } +} + +pub trait ScSandboxFunc: ScSandbox { + //fn blockContext(&self, construct func(sandbox: ScSandbox) interface{}, onClose func(interface{})) -> interface{} { + // panic("implement me") + //} + + // calls a smart contract func or view + fn call(&self, h_contract: ScHname, h_function: ScHname, params: Option, transfer: Option) -> ScImmutableDict { + return self.call_with_transfer(h_contract, h_function, params, transfer); + } + + // retrieve the agent id of the caller of the smart contract + fn caller(&self) -> ScAgentID { + return agent_id_from_bytes(&sandbox(FN_CALLER, &[])); + } + + // deploys a smart contract + fn deploy_contract(&self, program_hash: &ScHash, name: &str, description: &str, init_params: Option) { + let mut req = wasmrequests::DeployRequest { + prog_hash: program_hash.clone(), + name: name.to_string(), + description: description.to_string(), + params: vec![0; SC_UINT32_LENGTH], + }; + if let Some(init_params) = init_params { + req.params = init_params.to_bytes(); + } + sandbox(FN_DEPLOY_CONTRACT, &req.to_bytes()); + } + + // returns random entropy data for current request. + fn entropy(&self) -> ScHash { + return hash_from_bytes(&sandbox(FN_ENTROPY, &[])); + } + + // signals an event on the node that external entities can subscribe to + fn event(&self, msg: &str) { + sandbox(FN_EVENT, &string_to_bytes(msg)); + } + + // access the incoming balances for all assets + fn incoming_transfer(&self) -> ScBalances { + let buf = sandbox(FN_INCOMING_TRANSFER, &[]); + return ScAssets::new(&buf).balances(); + } + + // retrieve the assets that were minted in self transaction + fn minted(&self) -> ScBalances { + let buf = sandbox(FN_MINTED, &[]); + return ScAssets::new(&buf).balances(); + } + + // (delayed) posts a smart contract function request + fn post(&self, chain_id: ScChainID, h_contract: ScHname, h_function: ScHname, params: ScDict, transfer: ScTransfers, delay: u32) { + let req = wasmrequests::PostRequest { + chain_id, + contract: h_contract, + function: h_function, + params: params.to_bytes(), + transfer: transfer.to_bytes(), + delay: delay, + }; + sandbox(FN_POST, &req.to_bytes()); + } + + // generates a random value from 0 to max (exclusive: max) using a deterministic RNG + fn random(&self, max: u64) -> u64 { + if max == 0 { + self.panic("random: max parameter should be non-zero"); + } + unsafe { + static mut ENTROPY: Vec = Vec::new(); + static mut OFFSET: usize = 0; + // note that entropy gets reset for every request + if ENTROPY.len() == 0 { + // first time in self: request, initialize with current request entropy + ENTROPY = self.entropy().to_bytes(); + OFFSET = 0; + } + if OFFSET == 32 { + // ran out of entropy: data, hash entropy for next pseudo-random entropy + ENTROPY = self.utility().hash_blake2b(&ENTROPY).to_bytes(); + OFFSET = 0; + } + let rnd = uint64_from_bytes(&ENTROPY[OFFSET..OFFSET + 8]) % max; + OFFSET += 8; + return rnd; + } + } + + fn raw_state(&self) -> ScDict { + ScDict::state() + } + + //fn request(&self) -> ScRequest { + // panic("implement me"); + //} + + // retrieve the request id of self transaction + fn request_id(&self) -> ScRequestID { + return request_id_from_bytes(&sandbox(FN_REQUEST_ID, &[])); + } + + // transfer assets to the specified Tangle ledger address + fn send(&self, address: &ScAddress, transfer: &ScTransfers) { + // we need some assets to send + if transfer.is_empty() { + return; + } + + let req = wasmrequests::SendRequest { + address: address.clone(), + transfer: transfer.to_bytes(), + }; + sandbox(FN_SEND, &req.to_bytes()); + } + + //fn stateAnchor(&self) -> interface{} { + // panic("implement me") + //} +} diff --git a/packages/wasmvm/wasmlib/src/sandboxutils.rs b/packages/wasmvm/wasmlib/src/sandboxutils.rs new file mode 100644 index 0000000000..7d9ddffc87 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/sandboxutils.rs @@ -0,0 +1,73 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use crate::*; +use crate::host::*; + +pub struct ScSandboxUtils {} + +impl ScSandboxUtils { + // decodes the specified base58-encoded string value to its original bytes + pub fn base58_ecode(&self, value: &str) -> Vec { + sandbox(FN_UTILS_BASE58_DECODE, &string_to_bytes(value)) + } + + // encodes the specified bytes to a base-58-encoded string + pub fn base58_encode(&self, bytes: &[u8]) -> String { + bytes_to_string(&sandbox(FN_UTILS_BASE58_ENCODE, bytes)) + } + + pub fn bls_address_from_pub_key(&self, pub_key: &[u8]) -> ScAddress { + address_from_bytes(&sandbox(FN_UTILS_BLS_ADDRESS, pub_key)) + } + + pub fn bls_aggregate_signatures(&self, pub_keys: &[&[u8]], sigs: &[&[u8]]) -> Vec> { + let mut enc = WasmEncoder::new(); + uint32_encode(&mut enc, pub_keys.len() as u32); + for i in 0..pub_keys.len() { + enc.bytes(pub_keys[i]); + } + uint32_encode(&mut enc, sigs.len() as u32); + for i in 0..sigs.len() { + enc.bytes(sigs[i]); + } + let res = sandbox(FN_UTILS_BLS_AGGREGATE, &enc.buf()); + let mut dec = WasmDecoder::new(&res); + return [dec.bytes(), dec.bytes()].to_vec(); + } + + pub fn bls_valid_signature(&self, data: &[u8], pub_key: &[u8], signature: &[u8]) -> bool { + let mut enc = WasmEncoder::new(); + enc.bytes(data); + enc.bytes(pub_key); + enc.bytes(signature); + bool_from_bytes(&sandbox(FN_UTILS_BLS_VALID, &enc.buf())) + } + + pub fn ed25519_address_from_pub_key(&self, pub_key: &[u8]) -> ScAddress { + address_from_bytes(&sandbox(FN_UTILS_ED25519_ADDRESS, pub_key)) + } + + pub fn ed25519_valid_signature(&self, data: &[u8], pub_key: &[u8], signature: &[u8]) -> bool { + let mut enc = WasmEncoder::new(); + enc.bytes(data); + enc.bytes(pub_key); + enc.bytes(signature); + bool_from_bytes(&sandbox(FN_UTILS_ED25519_VALID, &enc.buf())) + } + + // hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash + pub fn hash_blake2b(&self, value: &[u8]) -> ScHash { + hash_from_bytes(&sandbox(FN_UTILS_HASH_BLAKE2B, value)) + } + + // hashes the specified value bytes using sha3 hashing and returns the resulting 32-byte hash + pub fn hash_sha3(&self, value: &[u8]) -> ScHash { + hash_from_bytes(&sandbox(FN_UTILS_HASH_SHA3, value)) + } + + // hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash + pub fn hash_name(&self, value: &str) -> ScHname { + hname_from_bytes(&sandbox(FN_UTILS_HASH_NAME, &string_to_bytes(value))) + } +} \ No newline at end of file diff --git a/packages/wasmvm/wasmlib/src/wasmrequests/consts.rs b/packages/wasmvm/wasmlib/src/wasmrequests/consts.rs new file mode 100644 index 0000000000..ad4856cf07 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmrequests/consts.rs @@ -0,0 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] + +use crate::*; + +pub const SC_NAME : &str = "requests"; +pub const SC_DESCRIPTION : &str = "WasmLib request structures"; +pub const HSC_NAME : ScHname = ScHname(0x98e19453); diff --git a/packages/wasmvm/wasmlib/src/wasmrequests/contract.rs b/packages/wasmvm/wasmlib/src/wasmrequests/contract.rs new file mode 100644 index 0000000000..a25e10ee4e --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmrequests/contract.rs @@ -0,0 +1,17 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] + +use crate::wasmrequests::*; +use crate::*; + +pub struct ScFuncs { +} + +impl ScFuncs { +} diff --git a/packages/wasmvm/wasmlib/src/wasmrequests/mod.rs b/packages/wasmvm/wasmlib/src/wasmrequests/mod.rs new file mode 100644 index 0000000000..25c034042a --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmrequests/mod.rs @@ -0,0 +1,16 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(unused_imports)] + +pub use consts::*; +pub use contract::*; +pub use structs::*; + +pub mod consts; +pub mod contract; +pub mod structs; diff --git a/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs b/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs new file mode 100644 index 0000000000..8507a87bea --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs @@ -0,0 +1,343 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +#![allow(dead_code)] +#![allow(unused_imports)] + +use crate::*; + +#[derive(Clone)] +pub struct CallRequest { + pub contract : ScHname, + pub function : ScHname, + pub params : Vec, + pub transfer : Vec, +} + +impl CallRequest { + pub fn from_bytes(bytes: &[u8]) -> CallRequest { + let mut dec = WasmDecoder::new(bytes); + CallRequest { + contract : hname_decode(&mut dec), + function : hname_decode(&mut dec), + params : bytes_decode(&mut dec), + transfer : bytes_decode(&mut dec), + } + } + + pub fn to_bytes(&self) -> Vec { + let mut enc = WasmEncoder::new(); + hname_encode(&mut enc, self.contract); + hname_encode(&mut enc, self.function); + bytes_encode(&mut enc, &self.params); + bytes_encode(&mut enc, &self.transfer); + enc.buf() + } +} + +#[derive(Clone)] +pub struct ImmutableCallRequest { + pub(crate) proxy: Proxy, +} + +impl ImmutableCallRequest { + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn value(&self) -> CallRequest { + CallRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct MutableCallRequest { + pub(crate) proxy: Proxy, +} + +impl MutableCallRequest { + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &CallRequest) { + self.proxy.set(&value.to_bytes()); + } + + pub fn value(&self) -> CallRequest { + CallRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct DeployRequest { + pub description : String, + pub name : String, + pub params : Vec, + pub prog_hash : ScHash, +} + +impl DeployRequest { + pub fn from_bytes(bytes: &[u8]) -> DeployRequest { + let mut dec = WasmDecoder::new(bytes); + DeployRequest { + description : string_decode(&mut dec), + name : string_decode(&mut dec), + params : bytes_decode(&mut dec), + prog_hash : hash_decode(&mut dec), + } + } + + pub fn to_bytes(&self) -> Vec { + let mut enc = WasmEncoder::new(); + string_encode(&mut enc, &self.description); + string_encode(&mut enc, &self.name); + bytes_encode(&mut enc, &self.params); + hash_encode(&mut enc, &self.prog_hash); + enc.buf() + } +} + +#[derive(Clone)] +pub struct ImmutableDeployRequest { + pub(crate) proxy: Proxy, +} + +impl ImmutableDeployRequest { + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn value(&self) -> DeployRequest { + DeployRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct MutableDeployRequest { + pub(crate) proxy: Proxy, +} + +impl MutableDeployRequest { + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &DeployRequest) { + self.proxy.set(&value.to_bytes()); + } + + pub fn value(&self) -> DeployRequest { + DeployRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct PostRequest { + pub chain_id : ScChainID, + pub contract : ScHname, + pub delay : u32, + pub function : ScHname, + pub params : Vec, + pub transfer : Vec, +} + +impl PostRequest { + pub fn from_bytes(bytes: &[u8]) -> PostRequest { + let mut dec = WasmDecoder::new(bytes); + PostRequest { + chain_id : chain_id_decode(&mut dec), + contract : hname_decode(&mut dec), + delay : uint32_decode(&mut dec), + function : hname_decode(&mut dec), + params : bytes_decode(&mut dec), + transfer : bytes_decode(&mut dec), + } + } + + pub fn to_bytes(&self) -> Vec { + let mut enc = WasmEncoder::new(); + chain_id_encode(&mut enc, &self.chain_id); + hname_encode(&mut enc, self.contract); + uint32_encode(&mut enc, self.delay); + hname_encode(&mut enc, self.function); + bytes_encode(&mut enc, &self.params); + bytes_encode(&mut enc, &self.transfer); + enc.buf() + } +} + +#[derive(Clone)] +pub struct ImmutablePostRequest { + pub(crate) proxy: Proxy, +} + +impl ImmutablePostRequest { + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn value(&self) -> PostRequest { + PostRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct MutablePostRequest { + pub(crate) proxy: Proxy, +} + +impl MutablePostRequest { + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &PostRequest) { + self.proxy.set(&value.to_bytes()); + } + + pub fn value(&self) -> PostRequest { + PostRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct SendRequest { + pub address : ScAddress, + pub transfer : Vec, +} + +impl SendRequest { + pub fn from_bytes(bytes: &[u8]) -> SendRequest { + let mut dec = WasmDecoder::new(bytes); + SendRequest { + address : address_decode(&mut dec), + transfer : bytes_decode(&mut dec), + } + } + + pub fn to_bytes(&self) -> Vec { + let mut enc = WasmEncoder::new(); + address_encode(&mut enc, &self.address); + bytes_encode(&mut enc, &self.transfer); + enc.buf() + } +} + +#[derive(Clone)] +pub struct ImmutableSendRequest { + pub(crate) proxy: Proxy, +} + +impl ImmutableSendRequest { + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn value(&self) -> SendRequest { + SendRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct MutableSendRequest { + pub(crate) proxy: Proxy, +} + +impl MutableSendRequest { + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &SendRequest) { + self.proxy.set(&value.to_bytes()); + } + + pub fn value(&self) -> SendRequest { + SendRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct TransferRequest { + pub agent_id : ScAgentID, + pub create : bool, + pub transfer : Vec, +} + +impl TransferRequest { + pub fn from_bytes(bytes: &[u8]) -> TransferRequest { + let mut dec = WasmDecoder::new(bytes); + TransferRequest { + agent_id : agent_id_decode(&mut dec), + create : bool_decode(&mut dec), + transfer : bytes_decode(&mut dec), + } + } + + pub fn to_bytes(&self) -> Vec { + let mut enc = WasmEncoder::new(); + agent_id_encode(&mut enc, &self.agent_id); + bool_encode(&mut enc, self.create); + bytes_encode(&mut enc, &self.transfer); + enc.buf() + } +} + +#[derive(Clone)] +pub struct ImmutableTransferRequest { + pub(crate) proxy: Proxy, +} + +impl ImmutableTransferRequest { + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn value(&self) -> TransferRequest { + TransferRequest::from_bytes(&self.proxy.get()) + } +} + +#[derive(Clone)] +pub struct MutableTransferRequest { + pub(crate) proxy: Proxy, +} + +impl MutableTransferRequest { + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &TransferRequest) { + self.proxy.set(&value.to_bytes()); + } + + pub fn value(&self) -> TransferRequest { + TransferRequest::from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/codec.rs b/packages/wasmvm/wasmlib/src/wasmtypes/codec.rs new file mode 100644 index 0000000000..6c6415f1af --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/codec.rs @@ -0,0 +1,213 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use crate::*; + +pub struct WasmDecoder<'a> { + buf: &'a [u8], +} + +impl WasmDecoder<'_> { + // constructs a decoder + pub fn new(buf: &[u8]) -> WasmDecoder { + if buf.len() == 0 { + panic("empty decode buffer"); + } + WasmDecoder { buf } + } + + // decodes the next variable length substring of bytes from the byte buffer + pub fn bytes(&mut self) -> Vec { + let length = self.vlu_decode(32); + self.fixed_bytes(length as usize) + } + + // decodes an uint8 from the byte buffer + pub fn byte(&mut self) -> u8 { + if self.buf.len() == 0 { + panic("insufficient bytes"); + } + let value = self.buf[0]; + self.buf = &self.buf[1..]; + value + } + + // decodes the next fixed length substring of bytes from the byte buffer + pub fn fixed_bytes(&mut self, size: usize) -> Vec { + if self.buf.len() < size { + panic("insufficient fixed bytes"); + } + let value = &self.buf[..size]; + self.buf = &self.buf[size..]; + value.to_vec() + } + + // peeks at the next byte in the byte buffer + pub fn peek(&self) -> u8 { + if self.buf.len() == 0 { + panic("insufficient peek bytes"); + } + self.buf[0] + } + + // vli (variable length integer) decoder + pub fn vli_decode(&mut self, bits: i32) -> i64 { + let mut b = self.byte(); + let sign = b & 0x40; + + // first group of 6 bits + let mut value = (b & 0x3f) as i64; + let mut s = 6; + + // while continuation bit is set + while (b & 0x80) != 0 { + if s >= bits { + panic("integer representation too long"); + } + + // next group of 7 bits + b = self.byte(); + value |= ((b & 0x7f) as i64) << s; + s += 7; + } + + if sign == 0 { + // positive, sign bits are already zero + return value; + } + + // negative, extend sign bits + value | (-1_i64 << s) + } + + // vlu (variable length unsigned) decoder + pub fn vlu_decode(&mut self, bits: i32) -> u64 { + // first group of 6 bits + let mut b = self.byte(); + let mut value = (b & 0x7f) as u64; + let mut s = 7; + + // while continuation bit is set + while (b & 0x80) != 0 { + if s >= bits { + panic("integer representation too long"); + } + + // next group of 7 bits + b = self.byte(); + value |= ((b & 0x7f) as u64) << s; + s += 7; + } + + value + } +} + +impl Drop for WasmDecoder<'_> { + fn drop(&mut self) { + if self.buf.len() != 0 { + panic("extra bytes"); + } + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// encodes separate entities into a byte buffer +pub struct WasmEncoder { + buf: Vec, +} + +impl WasmEncoder { + // constructs an encoder + pub fn new() -> WasmEncoder { + WasmEncoder { buf: Vec::new() } + } + + // encodes an uint8 into the byte buffer + pub fn byte(&mut self, value: u8) -> &WasmEncoder { + self.buf.push(value); + self + } + + // encodes a variable sized substring of bytes into the byte buffer + pub fn bytes(&mut self, value: &[u8]) -> &WasmEncoder { + let length = value.len(); + self.vlu_encode(length as u64); + self.fixed_bytes(value, length) + } + + // retrieve the encoded byte buffer + pub fn buf(&self) -> Vec { + self.buf.clone() + } + + // encodes a fixed sized substring of bytes into the byte buffer + pub fn fixed_bytes(&mut self, value: &[u8], length: usize) -> &WasmEncoder { + if value.len() != length as usize { + panic(&("invalid fixed bytes length (".to_string() + &length.to_string() + "), found " + &value.len().to_string())); + } + self.buf.extend_from_slice(value); + self + } + + // encodes an int64 into the byte buffer + // note that these are encoded using vli encoding to conserve space + // vli (variable length integer) encoder + pub fn vli_encode(&mut self, mut value: i64) -> &WasmEncoder { + // first group of 6 bits + // 1st byte encodes 0 as positive in bit 6 + let mut b = value as u8 & 0x3f; + value >>= 6; + + let mut final_value = 0_i64; + if value < 0 { + // encode negative value + // 1st byte encodes 1 as negative in bit 6 + b |= 0x40; + final_value = -1_i64; + } + + // keep shifting until all bits are done + while value != final_value { + // emit with continuation bit + self.buf.push(b | 0x80); + + // next group of 7 bits + b = value as u8 & 0x7f; + value >>= 7; + } + + // emit without continuation bit + self.buf.push(b); + self + } + + // encodes an uint64 into the byte buffer + // note that these are encoded using vlu encoding to conserve space + // vlu (variable length unsigned) encoder + pub fn vlu_encode(&mut self, mut value: u64) -> &WasmEncoder { + // first group of 7 bits + // 1st byte encodes 0 as positive in bit 6 + let mut b = value as u8; + value >>= 7; + + // keep shifting until all bits are done + while value != 0 { + // emit with continuation bit + self.buf.push(b | 0x80); + + // next group of 7 bits + b = value as u8; + value >>= 7; + } + + // emit without continuation bit + self.buf.push(b); + self + } +} + +pub fn base58_encode(buf: &[u8]) -> String { + string_from_bytes(&host::sandbox(FN_UTILS_BASE58_ENCODE, buf)) +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/mod.rs b/packages/wasmvm/wasmlib/src/wasmtypes/mod.rs new file mode 100644 index 0000000000..7d2471cb49 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/mod.rs @@ -0,0 +1,46 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +#![allow(unused_imports)] + +pub use codec::*; +pub use proxy::*; +pub use scaddress::*; +pub use scagentid::*; +pub use scbool::*; +pub use scbytes::*; +pub use scchainid::*; +pub use sccolor::*; +pub use schash::*; +pub use schname::*; +pub use scint16::*; +pub use scint32::*; +pub use scint64::*; +pub use scint8::*; +pub use screquestid::*; +pub use scstring::*; +pub use scuint16::*; +pub use scuint32::*; +pub use scuint64::*; +pub use scuint8::*; + +mod codec; +mod proxy; +mod scaddress; +mod scagentid; +mod scbool; +mod scbytes; +mod scchainid; +mod sccolor; +mod schash; +mod schname; +mod scint8; +mod scint16; +mod scint32; +mod scint64; +mod screquestid; +mod scstring; +mod scuint8; +mod scuint16; +mod scuint32; +mod scuint64; diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/proxy.rs b/packages/wasmvm/wasmlib/src/wasmtypes/proxy.rs new file mode 100644 index 0000000000..f69a69a81e --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/proxy.rs @@ -0,0 +1,120 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::*; + +#[derive(Clone)] +pub struct Proxy { + key: Vec, + pub kv_store: Rc, +} + +impl Proxy { + pub fn new(kv_store: &Rc) -> Proxy { + Proxy { kv_store: Rc::clone(kv_store), key: Vec::new() } + } + + pub fn nil() -> Proxy { + Proxy::new(&Rc::new(ScDict::new(&[]))) + } + + pub fn link(proxy: &mut Proxy, kv_store: &Rc) { + proxy.kv_store = Rc::clone(kv_store); + } + + pub fn append(&self) -> Proxy { + let length = self.length(); + self.expand(length + 1); + self.element(length) + } + + pub fn clear_array(&self) { + let mut length = self.length(); + while length != 0 { + length -= 1; + self.element(length).delete(); + } + + // clear the length counter + self.delete(); + } + + pub fn clear_map(&self) { + // TODO clear prefix + + // clear the length counter + self.delete(); + } + + pub fn delete(&self) { + self.kv_store.delete(&self.key); + } + + fn element(&self, index: u32) -> Proxy { + let mut enc = WasmEncoder::new(); + uint32_encode(&mut enc, index); + // 0x23 is '#' + self.sub(0x23, &enc.buf()) + } + + pub fn exists(&self) -> bool { + self.kv_store.exists(&self.key) + } + + pub fn expand(&self, length: u32) { + // update the length counter + let mut enc = WasmEncoder::new(); + uint32_encode(&mut enc, length); + self.set(&enc.buf()); + } + + pub fn get(&self) -> Vec { + self.kv_store.get(&self.key) + } + + pub fn index(&self, index: u32) -> Proxy { + let size = self.length(); + if index >= size { + if index == size { + panic("invalid index: use append"); + } + panic("invalid index"); + } + self.element(index) + } + + pub fn key(&self, key: &[u8]) -> Proxy { + // 0x2e is '.' + self.sub(0x2e, key) + } + + pub fn length(&self) -> u32 { + let buf = self.get(); + if buf.len() == 0 { + return 0; + } + let mut dec = WasmDecoder::new(&buf); + uint32_decode(&mut dec) + } + + pub fn root(&self, key: &str) -> Proxy { + Proxy { kv_store: Rc::clone(&self.kv_store), key: string_to_bytes(key).to_vec() } + } + + pub fn set(&self, value: &[u8]) { + self.kv_store.set(&self.key, value); + } + + fn sub(&self, sep: u8, key: &[u8]) -> Proxy { + if self.key.len() == 0 { + return Proxy { kv_store: Rc::clone(&self.kv_store), key: key.to_vec() }; + } + let mut buf: Vec = self.key.clone(); + buf.push(sep); + buf.extend_from_slice(key); + Proxy { kv_store: Rc::clone(&self.kv_store), key: buf } + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs new file mode 100644 index 0000000000..14193c3b86 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs @@ -0,0 +1,130 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_ADDRESS_ALIAS: u8 = 2; +pub const SC_ADDRESS_ED25519: u8 = 0; +pub const SC_ADDRESS_NFT: u8 = 1; + +pub const SC_ADDRESS_LENGTH: usize = 33; + +#[derive(PartialEq, Clone)] +pub struct ScAddress { + id: [u8; SC_ADDRESS_LENGTH], +} + +impl ScAddress { + pub fn new(buf: &[u8]) -> ScAddress { + address_from_bytes(buf) + } + + pub fn as_agent_id(&self) -> ScAgentID { + ScAgentID::new(self, ScHname(0)) + } + + pub fn to_bytes(&self) -> Vec { + address_to_bytes(self) + } + + pub fn to_string(&self) -> String { + address_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn address_decode(dec: &mut WasmDecoder) -> ScAddress { + address_from_bytes_unchecked(&dec.fixed_bytes(SC_ADDRESS_LENGTH)) +} + +pub fn address_encode(enc: &mut WasmEncoder, value: &ScAddress) { + enc.fixed_bytes(&value.to_bytes(), SC_ADDRESS_LENGTH); +} + +pub fn address_from_bytes(buf: &[u8]) -> ScAddress { + if buf.len() == 0 { + return ScAddress { id: [0; SC_ADDRESS_LENGTH] }; + } + if buf.len() != SC_ADDRESS_LENGTH { + panic("invalid Address length"); + } + if buf[0] > SC_ADDRESS_ALIAS { + panic("invalid Address type"); + } + ScAddress { id: buf.try_into().expect("WTF?") } +} + +pub fn address_to_bytes(value: &ScAddress) -> Vec { + value.id.to_vec() +} + +pub fn address_to_string(value: &ScAddress) -> String { + // TODO standardize human readable string + base58_encode(&value.id) +} + +fn address_from_bytes_unchecked(buf: &[u8]) -> ScAddress { + ScAddress { id: buf.try_into().expect("invalid Address length") } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableAddress { + proxy: Proxy, +} + +impl ScImmutableAddress { + pub fn new(proxy: Proxy) -> ScImmutableAddress { + ScImmutableAddress { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + address_to_string(&self.value()) + } + + pub fn value(&self) -> ScAddress { + address_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScAddress in host container +pub struct ScMutableAddress { + proxy: Proxy, +} + +impl ScMutableAddress { + pub fn new(proxy: Proxy) -> ScMutableAddress { + ScMutableAddress { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScAddress) { + self.proxy.set(&address_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + address_to_string(&self.value()) + } + + pub fn value(&self) -> ScAddress { + address_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs new file mode 100644 index 0000000000..0bddc3a23d --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs @@ -0,0 +1,138 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_AGENT_ID_LENGTH: usize = 37; + +#[derive(PartialEq, Clone)] +pub struct ScAgentID { + address: ScAddress, + hname: ScHname, +} + +impl ScAgentID { + pub fn new(address: &ScAddress, hname: ScHname) -> ScAgentID { + ScAgentID { address: address_from_bytes(&address.to_bytes()), hname: hname_from_bytes(&hname.to_bytes()) } + } + + pub fn address(&self) -> ScAddress { + self.address.clone() + } + + pub fn hname(&self) -> ScHname { + self.hname + } + + pub fn is_address(&self) -> bool { + self.hname == ScHname(0) + } + + pub fn to_bytes(&self) -> Vec { + agent_id_to_bytes(self) + } + + pub fn to_string(&self) -> String { + agent_id_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn agent_id_decode(dec: &mut WasmDecoder) -> ScAgentID { + ScAgentID { address: address_decode(dec), hname: hname_decode(dec) } +} + +pub fn agent_id_encode(enc: &mut WasmEncoder, value: &ScAgentID) { + address_encode(enc, &value.address()); + hname_encode(enc, value.hname()); +} + +pub fn agent_id_from_bytes(buf: &[u8]) -> ScAgentID { + if buf.len() == 0 { + return ScAgentID { address: address_from_bytes(buf), hname: hname_from_bytes(buf) }; + } + if buf.len() != SC_AGENT_ID_LENGTH { + panic("invalid AgentID length"); + } + // max ledgerstate.AliasAddressType + if buf[0] > SC_ADDRESS_ALIAS { + panic("invalid AgentID address type"); + } + ScAgentID { + address: address_from_bytes(&buf[..SC_ADDRESS_LENGTH]), + hname: hname_from_bytes(&buf[SC_ADDRESS_LENGTH..]), + } +} + +pub fn agent_id_to_bytes(value: &ScAgentID) -> Vec { + let mut enc = WasmEncoder::new(); + agent_id_encode(&mut enc, value); + enc.buf() +} + +pub fn agent_id_to_string(value: &ScAgentID) -> String { + // TODO standardize human readable string + value.address.to_string() + "::" + &value.hname.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableAgentID { + proxy: Proxy, +} + +impl ScImmutableAgentID { + pub fn new(proxy: Proxy) -> ScImmutableAgentID { + ScImmutableAgentID { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + agent_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScAgentID { + agent_id_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScAgentID in host container +pub struct ScMutableAgentID { + proxy: Proxy, +} + +impl ScMutableAgentID { + pub fn new(proxy: Proxy) -> ScMutableAgentID { + ScMutableAgentID { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScAgentID) { + self.proxy.set(&agent_id_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + agent_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScAgentID { + agent_id_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scbool.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scbool.rs new file mode 100644 index 0000000000..999b526aa0 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scbool.rs @@ -0,0 +1,113 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_BOOL_LENGTH: usize = 1; +pub const SC_BOOL_FALSE: u8 = 0x00; +pub const SC_BOOL_TRUE: u8 = 0xff; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn bool_decode(dec: &mut WasmDecoder) -> bool { + dec.byte() != SC_BOOL_FALSE +} + +pub fn bool_encode(enc: &mut WasmEncoder, value: bool) { + if value { + enc.byte(SC_BOOL_TRUE); + return; + } + enc.byte(SC_BOOL_FALSE); +} + +pub fn bool_from_bytes(buf: &[u8]) -> bool { + if buf.len() == 0 { + return false; + } + if buf.len() != SC_BOOL_LENGTH { + panic("invalid Bool length"); + } + if buf[0] == SC_BOOL_FALSE { + return false; + } + if buf[0] != SC_BOOL_TRUE { + panic("invalid Bool value"); + } + return true; +} + +pub fn bool_to_bytes(value: bool) -> Vec { + if value { + return [SC_BOOL_TRUE].to_vec(); + } + [SC_BOOL_FALSE].to_vec() +} + +pub fn bool_to_string(value: bool) -> String { + if value { + return "1".to_string(); + } + "0".to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableBool { + proxy: Proxy, +} + +impl ScImmutableBool { + pub fn new(proxy: Proxy) -> ScImmutableBool { + ScImmutableBool { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + bool_to_string(self.value()) + } + + pub fn value(&self) -> bool { + bool_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable bool in host container +pub struct ScMutableBool { + proxy: Proxy, +} + +impl ScMutableBool { + pub fn new(proxy: Proxy) -> ScMutableBool { + ScMutableBool { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: bool) { + self.proxy.set(&bool_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + bool_to_string(self.value()) + } + + pub fn value(&self) -> bool { + bool_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scbytes.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scbytes.rs new file mode 100644 index 0000000000..f2ef4eb4c4 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scbytes.rs @@ -0,0 +1,86 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn bytes_decode(dec: &mut WasmDecoder) -> Vec { + dec.bytes().to_vec() +} + +pub fn bytes_encode(enc: &mut WasmEncoder, value: &[u8]) { + enc.bytes(value); +} + +pub fn bytes_from_bytes(buf: &[u8]) -> Vec { + buf.to_vec() +} + +pub fn bytes_to_bytes(value: &[u8]) -> Vec { + value.to_vec() +} + +pub fn bytes_to_string(value: &[u8]) -> String { + // TODO standardize human readable string + base58_encode(value) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableBytes { + proxy: Proxy, +} + +impl ScImmutableBytes { + pub fn new(proxy: Proxy) -> ScImmutableBytes { + ScImmutableBytes { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + bytes_to_string(&self.value()) + } + + pub fn value(&self) -> Vec { + bytes_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScBytes in host container +pub struct ScMutableBytes { + proxy: Proxy, +} + +impl ScMutableBytes { + pub fn new(proxy: Proxy) -> ScMutableBytes { + ScMutableBytes { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &[u8]) { + self.proxy.set(&bytes_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + bytes_to_string(&self.value()) + } + + pub fn value(&self) -> Vec { + bytes_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scchainid.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scchainid.rs new file mode 100644 index 0000000000..b26f6107fa --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scchainid.rs @@ -0,0 +1,128 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_CHAIN_ID_LENGTH: usize = 33; + +#[derive(PartialEq, Clone)] +pub struct ScChainID { + id: [u8; SC_CHAIN_ID_LENGTH], +} + +impl ScChainID { + pub fn new(buf: &[u8]) -> ScChainID { + chain_id_from_bytes(buf) + } + + pub fn address(&self) -> ScAddress { + address_from_bytes(&self.id) + } + + pub fn to_bytes(&self) -> Vec { + chain_id_to_bytes(self) + } + + pub fn to_string(&self) -> String { + chain_id_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn chain_id_decode(dec: &mut WasmDecoder) -> ScChainID { + chain_id_from_bytes_unchecked(&dec.fixed_bytes(SC_CHAIN_ID_LENGTH)) +} + +pub fn chain_id_encode(enc: &mut WasmEncoder, value: &ScChainID) { + enc.fixed_bytes(&value.to_bytes(), SC_CHAIN_ID_LENGTH); +} + +pub fn chain_id_from_bytes(buf: &[u8]) -> ScChainID { + if buf.len() == 0 { + let mut chain_id = ScChainID { id: [0; SC_CHAIN_ID_LENGTH] }; + chain_id.id[0] = SC_ADDRESS_ALIAS; + return chain_id; + } + if buf.len() != SC_CHAIN_ID_LENGTH { + panic("invalid ChainID length"); + } + if buf[0] != SC_ADDRESS_ALIAS { + panic("invalid ChainID: not an alias address"); + } + ScChainID { id: buf.try_into().expect("WTF?") } +} + +pub fn chain_id_to_bytes(value: &ScChainID) -> Vec { + value.id.to_vec() +} + +pub fn chain_id_to_string(value: &ScChainID) -> String { + // TODO standardize human readable string + base58_encode(&value.id) +} + +fn chain_id_from_bytes_unchecked(buf: &[u8]) -> ScChainID { + ScChainID { id: buf.try_into().expect("invalid ChainID length") } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableChainID { + proxy: Proxy, +} + +impl ScImmutableChainID { + pub fn new(proxy: Proxy) -> ScImmutableChainID { + ScImmutableChainID { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + chain_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScChainID { + chain_id_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScChainID in host container +pub struct ScMutableChainID { + proxy: Proxy, +} + +impl ScMutableChainID { + pub fn new(proxy: Proxy) -> ScMutableChainID { + ScMutableChainID { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScChainID) { + self.proxy.set(&chain_id_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + chain_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScChainID { + chain_id_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/sccolor.rs b/packages/wasmvm/wasmlib/src/wasmtypes/sccolor.rs new file mode 100644 index 0000000000..6246178cd5 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/sccolor.rs @@ -0,0 +1,122 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_COLOR_LENGTH: usize = 32; + +#[derive(PartialEq, Clone, Copy, Eq, Hash)] +pub struct ScColor { + id: [u8; SC_COLOR_LENGTH], +} + +impl ScColor { + pub const IOTA: ScColor = ScColor { id: [0x00; SC_COLOR_LENGTH] }; + pub const MINT: ScColor = ScColor { id: [0xff; SC_COLOR_LENGTH] }; + + pub fn new(buf: &[u8]) -> ScColor { + color_from_bytes(buf) + } + + pub fn to_bytes(&self) -> Vec { + color_to_bytes(self) + } + + pub fn to_string(&self) -> String { + color_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn color_decode(dec: &mut WasmDecoder) -> ScColor { + color_from_bytes_unchecked(&dec.fixed_bytes(SC_COLOR_LENGTH)) +} + +pub fn color_encode(enc: &mut WasmEncoder, value: &ScColor) { + enc.fixed_bytes(&value.to_bytes(), SC_COLOR_LENGTH); +} + +pub fn color_from_bytes(buf: &[u8]) -> ScColor { + if buf.len() == 0 { + return ScColor { id: [0; SC_COLOR_LENGTH] }; + } + if buf.len() != SC_COLOR_LENGTH { + panic("invalid Color length"); + } + ScColor { id: buf.try_into().expect("WTF?") } +} + +pub fn color_to_bytes(value: &ScColor) -> Vec { + value.id.to_vec() +} + +pub fn color_to_string(value: &ScColor) -> String { + // TODO standardize human readable string + base58_encode(&value.id) +} + +fn color_from_bytes_unchecked(buf: &[u8]) -> ScColor { + ScColor { id: buf.try_into().expect("invalid Color length") } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableColor { + proxy: Proxy, +} + +impl ScImmutableColor { + pub fn new(proxy: Proxy) -> ScImmutableColor { + ScImmutableColor { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + color_to_string(&self.value()) + } + + pub fn value(&self) -> ScColor { + color_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScColor in host container +pub struct ScMutableColor { + proxy: Proxy, +} + +impl ScMutableColor { + pub fn new(proxy: Proxy) -> ScMutableColor { + ScMutableColor { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScColor) { + self.proxy.set(&color_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + color_to_string(&self.value()) + } + + pub fn value(&self) -> ScColor { + color_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/schash.rs b/packages/wasmvm/wasmlib/src/wasmtypes/schash.rs new file mode 100644 index 0000000000..6acfa2e893 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/schash.rs @@ -0,0 +1,119 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_HASH_LENGTH: usize = 32; + +#[derive(PartialEq, Clone)] +pub struct ScHash { + id: [u8; SC_HASH_LENGTH], +} + +impl ScHash { + pub fn new(buf: &[u8]) -> ScHash { + hash_from_bytes(buf) + } + + pub fn to_bytes(&self) -> Vec { + hash_to_bytes(self) + } + + pub fn to_string(&self) -> String { + hash_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn hash_decode(dec: &mut WasmDecoder) -> ScHash { + hash_from_bytes_unchecked(&dec.fixed_bytes(SC_HASH_LENGTH)) +} + +pub fn hash_encode(enc: &mut WasmEncoder, value: &ScHash) { + enc.fixed_bytes(&value.to_bytes(), SC_HASH_LENGTH); +} + +pub fn hash_from_bytes(buf: &[u8]) -> ScHash { + if buf.len() == 0 { + return ScHash { id: [0; SC_HASH_LENGTH] }; + } + if buf.len() != SC_HASH_LENGTH { + panic("invalid Hash length"); + } + ScHash { id: buf.try_into().expect("WTF?") } +} + +pub fn hash_to_bytes(value: &ScHash) -> Vec { + value.id.to_vec() +} + +pub fn hash_to_string(value: &ScHash) -> String { + // TODO standardize human readable string + base58_encode(&value.id) +} + +fn hash_from_bytes_unchecked(buf: &[u8]) -> ScHash { + ScHash { id: buf.try_into().expect("invalid Hash length") } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableHash { + proxy: Proxy, +} + +impl ScImmutableHash { + pub fn new(proxy: Proxy) -> ScImmutableHash { + ScImmutableHash { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + hash_to_string(&self.value()) + } + + pub fn value(&self) -> ScHash { + hash_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScHash in host container +pub struct ScMutableHash { + proxy: Proxy, +} + +impl ScMutableHash { + pub fn new(proxy: Proxy) -> ScMutableHash { + ScMutableHash { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScHash) { + self.proxy.set(&hash_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + hash_to_string(&self.value()) + } + + pub fn value(&self) -> ScHash { + hash_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/schname.rs b/packages/wasmvm/wasmlib/src/wasmtypes/schname.rs new file mode 100644 index 0000000000..df048b5c61 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/schname.rs @@ -0,0 +1,119 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_HNAME_LENGTH: usize = 4; + +#[derive(PartialEq, Clone, Copy)] +pub struct ScHname(pub u32); + +impl ScHname { + pub fn new(buf: &[u8]) -> ScHname { + ScHname(uint32_from_bytes(buf)) + } + + pub fn to_bytes(&self) -> Vec { + hname_to_bytes(*self) + } + + pub fn to_string(&self) -> String { + hname_to_string(*self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn hname_decode(dec: &mut WasmDecoder) -> ScHname { + hname_from_bytes(&dec.fixed_bytes(SC_HNAME_LENGTH)) +} + +pub fn hname_encode(enc: &mut WasmEncoder, value: ScHname) { + enc.fixed_bytes(&hname_to_bytes(value), SC_HNAME_LENGTH); +} + +pub fn hname_from_bytes(buf: &[u8]) -> ScHname { + if buf.len() == 0 { + return ScHname(0); + } + if buf.len() != SC_HNAME_LENGTH { + panic("invalid Hname length"); + } + ScHname(u32::from_le_bytes(buf.try_into().expect("WTF?"))) +} + +pub fn hname_to_bytes(value: ScHname) -> Vec { + value.0.to_le_bytes().to_vec() +} + +pub fn hname_to_string(value: ScHname) -> String { + let hexa = "0123456789abcdef".as_bytes(); + let mut res = [0u8; 8]; + let mut val = value.0; + for n in 0..8 { + res[7 - n] = hexa[val as usize & 0x0f]; + val >>= 4; + } + string_from_bytes(&res) +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableHname { + proxy: Proxy, +} + +impl ScImmutableHname { + pub fn new(proxy: Proxy) -> ScImmutableHname { + ScImmutableHname { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + hname_to_string(self.value()) + } + + pub fn value(&self) -> ScHname { + hname_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScHname in host container +pub struct ScMutableHname { + proxy: Proxy, +} + +impl ScMutableHname { + pub fn new(proxy: Proxy) -> ScMutableHname { + ScMutableHname { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: ScHname) { + self.proxy.set(&hname_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + hname_to_string(self.value()) + } + + pub fn value(&self) -> ScHname { + hname_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scint16.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scint16.rs new file mode 100644 index 0000000000..0dc8387eaa --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scint16.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_INT16_LENGTH: usize = 2; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn int16_decode(dec: &mut WasmDecoder) -> i16 { + dec.vli_decode(16) as i16 +} + +pub fn int16_encode(enc: &mut WasmEncoder, value: i16) { + enc.vli_encode(value as i64); +} + +pub fn int16_from_bytes(buf: &[u8]) -> i16 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_INT16_LENGTH { + panic("invalid Int16 length"); + } + i16::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn int16_to_bytes(value: i16) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn int16_to_string(value: i16) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableInt16 { + proxy: Proxy, +} + +impl ScImmutableInt16 { + pub fn new(proxy: Proxy) -> ScImmutableInt16 { + ScImmutableInt16 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + int16_to_string(self.value()) + } + + pub fn value(&self) -> i16 { + int16_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable i16 in host container +pub struct ScMutableInt16 { + proxy: Proxy, +} + +impl ScMutableInt16 { + pub fn new(proxy: Proxy) -> ScMutableInt16 { + ScMutableInt16 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: i16) { + self.proxy.set(&int16_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + int16_to_string(self.value()) + } + + pub fn value(&self) -> i16 { + int16_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scint32.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scint32.rs new file mode 100644 index 0000000000..217c9f77cb --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scint32.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_INT32_LENGTH: usize = 4; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn int32_decode(dec: &mut WasmDecoder) -> i32 { + dec.vli_decode(32) as i32 +} + +pub fn int32_encode(enc: &mut WasmEncoder, value: i32) { + enc.vli_encode(value as i64); +} + +pub fn int32_from_bytes(buf: &[u8]) -> i32 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_INT32_LENGTH { + panic("invalid Int32 length"); + } + i32::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn int32_to_bytes(value: i32) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn int32_to_string(value: i32) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableInt32 { + proxy: Proxy, +} + +impl ScImmutableInt32 { + pub fn new(proxy: Proxy) -> ScImmutableInt32 { + ScImmutableInt32 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + int32_to_string(self.value()) + } + + pub fn value(&self) -> i32 { + int32_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable i32 in host container +pub struct ScMutableInt32 { + proxy: Proxy, +} + +impl ScMutableInt32 { + pub fn new(proxy: Proxy) -> ScMutableInt32 { + ScMutableInt32 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: i32) { + self.proxy.set(&int32_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + int32_to_string(self.value()) + } + + pub fn value(&self) -> i32 { + int32_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scint64.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scint64.rs new file mode 100644 index 0000000000..d9a98137e9 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scint64.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_INT64_LENGTH: usize = 8; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn int64_decode(dec: &mut WasmDecoder) -> i64 { + dec.vli_decode(64) +} + +pub fn int64_encode(enc: &mut WasmEncoder, value: i64) { + enc.vli_encode(value); +} + +pub fn int64_from_bytes(buf: &[u8]) -> i64 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_INT64_LENGTH { + panic("invalid Int64 length"); + } + i64::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn int64_to_bytes(value: i64) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn int64_to_string(value: i64) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableInt64 { + proxy: Proxy, +} + +impl ScImmutableInt64 { + pub fn new(proxy: Proxy) -> ScImmutableInt64 { + ScImmutableInt64 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + int64_to_string(self.value()) + } + + pub fn value(&self) -> i64 { + int64_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable i64 in host container +pub struct ScMutableInt64 { + proxy: Proxy, +} + +impl ScMutableInt64 { + pub fn new(proxy: Proxy) -> ScMutableInt64 { + ScMutableInt64 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: i64) { + self.proxy.set(&int64_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + int64_to_string(self.value()) + } + + pub fn value(&self) -> i64 { + int64_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scint8.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scint8.rs new file mode 100644 index 0000000000..7d6f716e1e --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scint8.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_INT8_LENGTH: usize = 1; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn int8_decode(dec: &mut WasmDecoder) -> i8 { + dec.byte() as i8 +} + +pub fn int8_encode(enc: &mut WasmEncoder, value: i8) { + enc.byte(value as u8); +} + +pub fn int8_from_bytes(buf: &[u8]) -> i8 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_INT8_LENGTH { + panic("invalid Int8 length"); + } + buf[0] as i8 +} + +pub fn int8_to_bytes(value: i8) -> Vec { + [value as u8].to_vec() +} + +pub fn int8_to_string(value: i8) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableInt8 { + proxy: Proxy, +} + +impl ScImmutableInt8 { + pub fn new(proxy: Proxy) -> ScImmutableInt8 { + ScImmutableInt8 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + int8_to_string(self.value()) + } + + pub fn value(&self) -> i8 { + int8_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable i8 in host container +pub struct ScMutableInt8 { + proxy: Proxy, +} + +impl ScMutableInt8 { + pub fn new(proxy: Proxy) -> ScMutableInt8 { + ScMutableInt8 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: i8) { + self.proxy.set(&int8_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + int8_to_string(self.value()) + } + + pub fn value(&self) -> i8 { + int8_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/screquestid.rs b/packages/wasmvm/wasmlib/src/wasmtypes/screquestid.rs new file mode 100644 index 0000000000..97f0953e36 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/screquestid.rs @@ -0,0 +1,123 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_REQUEST_ID_LENGTH: usize = 34; + +#[derive(PartialEq, Clone)] +pub struct ScRequestID { + id: [u8; SC_REQUEST_ID_LENGTH], +} + +impl ScRequestID { + pub fn new(buf: &[u8]) -> ScRequestID { + request_id_from_bytes(buf) + } + + pub fn to_bytes(&self) -> Vec { + request_id_to_bytes(self) + } + + pub fn to_string(&self) -> String { + request_id_to_string(self) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn request_id_decode(dec: &mut WasmDecoder) -> ScRequestID { + request_id_from_bytes_unchecked(&dec.fixed_bytes(SC_REQUEST_ID_LENGTH)) +} + +pub fn request_id_encode(enc: &mut WasmEncoder, value: &ScRequestID) { + enc.fixed_bytes(&value.to_bytes(), SC_REQUEST_ID_LENGTH); +} + +pub fn request_id_from_bytes(buf: &[u8]) -> ScRequestID { + if buf.len() == 0 { + return ScRequestID { id: [0; SC_REQUEST_ID_LENGTH] }; + } + if buf.len() != SC_REQUEST_ID_LENGTH { + panic("invalid RequestID length"); + } + // final uint16 output index must be > ledgerstate.MaxOutputCount + if buf[SC_REQUEST_ID_LENGTH - 2] > 127 || buf[SC_REQUEST_ID_LENGTH - 1] != 0 { + panic("invalid RequestID: output index > 127"); + } + ScRequestID { id: buf.try_into().expect("WTF?") } +} + +pub fn request_id_to_bytes(value: &ScRequestID) -> Vec { + value.id.to_vec() +} + +pub fn request_id_to_string(value: &ScRequestID) -> String { + // TODO standardize human readable string + base58_encode(&value.id) +} + +fn request_id_from_bytes_unchecked(buf: &[u8]) -> ScRequestID { + ScRequestID { id: buf.try_into().expect("invalid RequestID length") } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableRequestID { + proxy: Proxy, +} + +impl ScImmutableRequestID { + pub fn new(proxy: Proxy) -> ScImmutableRequestID { + ScImmutableRequestID { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + request_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScRequestID { + request_id_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScRequestID in host container +pub struct ScMutableRequestID { + proxy: Proxy, +} + +impl ScMutableRequestID { + pub fn new(proxy: Proxy) -> ScMutableRequestID { + ScMutableRequestID { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &ScRequestID) { + self.proxy.set(&request_id_to_bytes(&value)); + } + + pub fn to_string(&self) -> String { + request_id_to_string(&self.value()) + } + + pub fn value(&self) -> ScRequestID { + request_id_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scstring.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scstring.rs new file mode 100644 index 0000000000..f32494cd35 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scstring.rs @@ -0,0 +1,85 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn string_decode(dec: &mut WasmDecoder) -> String { + string_from_bytes(&dec.bytes()) +} + +pub fn string_encode(enc: &mut WasmEncoder, value: &str) { + enc.bytes(&string_to_bytes(value)); +} + +pub fn string_from_bytes(buf: &[u8]) -> String { + String::from_utf8_lossy(buf).to_string() +} + +pub fn string_to_bytes(value: &str) -> Vec { + value.as_bytes().to_vec() +} + +pub fn string_to_string(value: &str) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableString { + proxy: Proxy, +} + +impl ScImmutableString { + pub fn new(proxy: Proxy) -> ScImmutableString { + ScImmutableString { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + self.value() + } + + pub fn value(&self) -> String { + string_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable ScString in host container +pub struct ScMutableString { + proxy: Proxy, +} + +impl ScMutableString { + pub fn new(proxy: Proxy) -> ScMutableString { + ScMutableString { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: &str) { + self.proxy.set(&string_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + self.value() + } + + pub fn value(&self) -> String { + string_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scuint16.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scuint16.rs new file mode 100644 index 0000000000..18e2babc04 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scuint16.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_UINT16_LENGTH: usize = 2; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn uint16_decode(dec: &mut WasmDecoder) -> u16 { + dec.vlu_decode(16) as u16 +} + +pub fn uint16_encode(enc: &mut WasmEncoder, value: u16) { + enc.vlu_encode(value as u64); +} + +pub fn uint16_from_bytes(buf: &[u8]) -> u16 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_UINT16_LENGTH { + panic("invalid Uint16 length"); + } + u16::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn uint16_to_bytes(value: u16) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn uint16_to_string(value: u16) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableUint16 { + proxy: Proxy, +} + +impl ScImmutableUint16 { + pub fn new(proxy: Proxy) -> ScImmutableUint16 { + ScImmutableUint16 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + uint16_to_string(self.value()) + } + + pub fn value(&self) -> u16 { + uint16_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable u16 in host container +pub struct ScMutableUint16 { + proxy: Proxy, +} + +impl ScMutableUint16 { + pub fn new(proxy: Proxy) -> ScMutableUint16 { + ScMutableUint16 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: u16) { + self.proxy.set(&uint16_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + uint16_to_string(self.value()) + } + + pub fn value(&self) -> u16 { + uint16_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scuint32.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scuint32.rs new file mode 100644 index 0000000000..6cc52330d6 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scuint32.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_UINT32_LENGTH: usize = 4; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn uint32_decode(dec: &mut WasmDecoder) -> u32 { + dec.vlu_decode(32) as u32 +} + +pub fn uint32_encode(enc: &mut WasmEncoder, value: u32) { + enc.vlu_encode(value as u64); +} + +pub fn uint32_from_bytes(buf: &[u8]) -> u32 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_UINT32_LENGTH { + panic("invalid Uint32 length"); + } + u32::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn uint32_to_bytes(value: u32) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn uint32_to_string(value: u32) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableUint32 { + proxy: Proxy, +} + +impl ScImmutableUint32 { + pub fn new(proxy: Proxy) -> ScImmutableUint32 { + ScImmutableUint32 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + uint32_to_string(self.value()) + } + + pub fn value(&self) -> u32 { + uint32_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable u32 in host container +pub struct ScMutableUint32 { + proxy: Proxy, +} + +impl ScMutableUint32 { + pub fn new(proxy: Proxy) -> ScMutableUint32 { + ScMutableUint32 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: u32) { + self.proxy.set(&uint32_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + uint32_to_string(self.value()) + } + + pub fn value(&self) -> u32 { + uint32_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scuint64.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scuint64.rs new file mode 100644 index 0000000000..7f23b7eca7 --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scuint64.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_UINT64_LENGTH: usize = 8; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn uint64_decode(dec: &mut WasmDecoder) -> u64 { + dec.vlu_decode(64) +} + +pub fn uint64_encode(enc: &mut WasmEncoder, value: u64) { + enc.vlu_encode(value); +} + +pub fn uint64_from_bytes(buf: &[u8]) -> u64 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_UINT64_LENGTH { + panic("invalid Uint64 length"); + } + u64::from_le_bytes(buf.try_into().expect("WTF?")) +} + +pub fn uint64_to_bytes(value: u64) -> Vec { + value.to_le_bytes().to_vec() +} + +pub fn uint64_to_string(value: u64) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableUint64 { + proxy: Proxy, +} + +impl ScImmutableUint64 { + pub fn new(proxy: Proxy) -> ScImmutableUint64 { + ScImmutableUint64 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + uint64_to_string(self.value()) + } + + pub fn value(&self) -> u64 { + uint64_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable u64 in host container +pub struct ScMutableUint64 { + proxy: Proxy, +} + +impl ScMutableUint64 { + pub fn new(proxy: Proxy) -> ScMutableUint64 { + ScMutableUint64 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: u64) { + self.proxy.set(&uint64_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + uint64_to_string(self.value()) + } + + pub fn value(&self) -> u64 { + uint64_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scuint8.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scuint8.rs new file mode 100644 index 0000000000..ad8e371dbd --- /dev/null +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scuint8.rs @@ -0,0 +1,95 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +use std::convert::TryInto; + +use crate::*; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub const SC_UINT8_LENGTH: usize = 1; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub fn uint8_decode(dec: &mut WasmDecoder) -> u8 { + dec.byte() +} + +pub fn uint8_encode(enc: &mut WasmEncoder, value: u8) { + enc.byte(value); +} + +pub fn uint8_from_bytes(buf: &[u8]) -> u8 { + if buf.len() == 0 { + return 0; + } + if buf.len() != SC_UINT8_LENGTH { + panic("invalid Uint8 length"); + } + buf[0] +} + +pub fn uint8_to_bytes(value: u8) -> Vec { + [value].to_vec() +} + +pub fn uint8_to_string(value: u8) -> String { + value.to_string() +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +pub struct ScImmutableUint8 { + proxy: Proxy, +} + +impl ScImmutableUint8 { + pub fn new(proxy: Proxy) -> ScImmutableUint8 { + ScImmutableUint8 { proxy } + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn to_string(&self) -> String { + uint8_to_string(self.value()) + } + + pub fn value(&self) -> u8 { + uint8_from_bytes(&self.proxy.get()) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// value proxy for mutable u8 in host container +pub struct ScMutableUint8 { + proxy: Proxy, +} + +impl ScMutableUint8 { + pub fn new(proxy: Proxy) -> ScMutableUint8 { + ScMutableUint8 { proxy } + } + + pub fn delete(&self) { + self.proxy.delete(); + } + + pub fn exists(&self) -> bool { + self.proxy.exists() + } + + pub fn set_value(&self, value: u8) { + self.proxy.set(&uint8_to_bytes(value)); + } + + pub fn to_string(&self) -> String { + uint8_to_string(self.value()) + } + + pub fn value(&self) -> u8 { + uint8_from_bytes(&self.proxy.get()) + } +} diff --git a/packages/vm/wasmlib/ts/wasmclient/api_common/request_sender.ts b/packages/wasmvm/wasmlib/ts/wasmclient/api_common/request_sender.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/api_common/request_sender.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/api_common/request_sender.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/api_common/response_models.ts b/packages/wasmvm/wasmlib/ts/wasmclient/api_common/response_models.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/api_common/response_models.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/api_common/response_models.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/arguments.ts b/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts similarity index 79% rename from packages/vm/wasmlib/ts/wasmclient/arguments.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts index b181bde558..1a4484ee8d 100644 --- a/packages/vm/wasmlib/ts/wasmclient/arguments.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts @@ -1,30 +1,30 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import * as wasmclient from "./index" +import {Bytes, Int32, Item, Items, panic} from "." +import {Encoder} from "./encoder" import {Buffer} from "./buffer"; // The Arguments struct is used to gather all arguments for this smart // contract function call and encode it into this deterministic byte array -export class Arguments extends wasmclient.Encoder { - private args = new Map(); - +export class Arguments extends Encoder { + private args = new Map(); // get(key: string): wasmclient.Bytes { // const bytes = this.args.get(key); // return bytes ?? Buffer.alloc(0); // } - public set(key: string, val: wasmclient.Bytes): void { + public set(key: string, val: Bytes): void { this.args.set(key, val); } - public indexedKey(key: string, index: wasmclient.Int32): string { + public indexedKey(key: string, index: Int32): string { return key + "." + index.toString(); } public mandatory(key: string): void { if (!this.args.has(key)) { - wasmclient.panic("missing mandatory " + key) + panic("missing mandatory " + key) } } @@ -34,7 +34,7 @@ export class Arguments extends wasmclient.Encoder { // be 100% deterministic). Then emit the 4-byte argument count. // Next for each argument emit the 2-byte key length, the key prepended // with the minus sign, the 4-byte value length, and then the value bytes. - public encode(): wasmclient.Bytes { + public encode(): Bytes { const keys = new Array(); for (const key of this.args.keys()) { keys.push(key); @@ -58,12 +58,12 @@ export class Arguments extends wasmclient.Encoder { return buf; } - public encodeCall(): wasmclient.Items { - let items = new wasmclient.Items() + public encodeCall(): Items { + const items = new Items() for (const [key, val] of this.args) { const k = Buffer.from(key).toString("base64"); const v = val.toString("base64"); - items.Items.push(new wasmclient.Item(k, v)) + items.Items.push(new Item(k, v)) } return items; } diff --git a/packages/vm/wasmlib/ts/wasmclient/buffer/index.d.ts b/packages/wasmvm/wasmlib/ts/wasmclient/buffer/index.d.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/buffer/index.d.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/buffer/index.d.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/buffer/index.js b/packages/wasmvm/wasmlib/ts/wasmclient/buffer/index.js similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/buffer/index.js rename to packages/wasmvm/wasmlib/ts/wasmclient/buffer/index.js diff --git a/packages/vm/wasmlib/ts/wasmclient/buffer/readme.md b/packages/wasmvm/wasmlib/ts/wasmclient/buffer/readme.md similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/buffer/readme.md rename to packages/wasmvm/wasmlib/ts/wasmclient/buffer/readme.md diff --git a/packages/vm/wasmlib/ts/wasmclient/clientfunc.ts b/packages/wasmvm/wasmlib/ts/wasmclient/clientfunc.ts similarity index 92% rename from packages/vm/wasmlib/ts/wasmclient/clientfunc.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/clientfunc.ts index 06bb352dd9..c3fd9ed5dc 100644 --- a/packages/vm/wasmlib/ts/wasmclient/clientfunc.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/clientfunc.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmclient from "./index"; -import { IKeyPair } from "./crypto"; +import {IKeyPair} from "./crypto"; export class ClientFunc { protected svc: wasmclient.Service; @@ -20,6 +20,8 @@ export class ClientFunc { this.onLedger = onLedger; } + //TODO rename to protected postRequest to prevent need for override and hide it + // Sends a request to the smart contract service // You can wait for the request to complete by using the returned RequestID // as parameter to Service.waitRequest() diff --git a/packages/vm/wasmlib/ts/wasmclient/clientview.ts b/packages/wasmvm/wasmlib/ts/wasmclient/clientview.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/clientview.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/clientview.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/colors.ts b/packages/wasmvm/wasmlib/ts/wasmclient/colors.ts similarity index 74% rename from packages/vm/wasmlib/ts/wasmclient/colors.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/colors.ts index 475b229cb6..3d3e8d65f9 100644 --- a/packages/vm/wasmlib/ts/wasmclient/colors.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/colors.ts @@ -1,4 +1,7 @@ -import { Buffer } from "./buffer"; +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {Buffer} from "./buffer"; export class Colors { public static readonly IOTA_COLOR: string = "IOTA"; diff --git a/packages/vm/wasmlib/ts/wasmclient/configuration.ts b/packages/wasmvm/wasmlib/ts/wasmclient/configuration.ts similarity index 83% rename from packages/vm/wasmlib/ts/wasmclient/configuration.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/configuration.ts index 4f25142a2f..5e1cdd7775 100644 --- a/packages/vm/wasmlib/ts/wasmclient/configuration.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/configuration.ts @@ -1,4 +1,7 @@ -import { Buffer } from './buffer'; +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {Buffer} from './buffer'; export interface IConfiguration { seed: Buffer | null; @@ -15,7 +18,7 @@ export class Configuration implements IConfiguration { chainId: string = ''; constructor(configuration: IConfiguration) { - if(!configuration) throw new Error("Configuration not defined"); + if (!configuration) throw new Error("Configuration not defined"); this.seed = configuration.seed; this.waspWebSocketUrl = configuration.waspWebSocketUrl; diff --git a/packages/vm/wasmlib/ts/wasmclient/coreaccounts/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/coreaccounts/service.ts similarity index 99% rename from packages/vm/wasmlib/ts/wasmclient/coreaccounts/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/coreaccounts/service.ts index a3a39405b0..57a728ea96 100644 --- a/packages/vm/wasmlib/ts/wasmclient/coreaccounts/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/coreaccounts/service.ts @@ -157,7 +157,7 @@ export class TotalAssetsResults extends wasmclient.Results { export class CoreAccountsService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0x3c4b5e02, new Map()); + super(cl, 0x3c4b5e02); } public deposit(): DepositFunc { diff --git a/packages/vm/wasmlib/ts/wasmclient/coreblob/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/coreblob/service.ts similarity index 98% rename from packages/vm/wasmlib/ts/wasmclient/coreblob/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/coreblob/service.ts index 265fe35f9e..e49aea04be 100644 --- a/packages/vm/wasmlib/ts/wasmclient/coreblob/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/coreblob/service.ts @@ -120,7 +120,7 @@ export class ListBlobsResults extends wasmclient.Results { export class CoreBlobService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0xfd91bc63, new Map()); + super(cl, 0xfd91bc63); } public storeBlob(): StoreBlobFunc { diff --git a/packages/vm/wasmlib/ts/wasmclient/coreblocklog/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/coreblocklog/service.ts similarity index 89% rename from packages/vm/wasmlib/ts/wasmclient/coreblocklog/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/coreblocklog/service.ts index abe2db5dc9..d0a3985e67 100644 --- a/packages/vm/wasmlib/ts/wasmclient/coreblocklog/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/coreblocklog/service.ts @@ -36,8 +36,8 @@ export class ControlAddressesView extends wasmclient.ClientView { export class ControlAddressesResults extends wasmclient.Results { - blockIndex(): wasmclient.Int32 { - return this.toInt32(this.get(ResBlockIndex)); + blockIndex(): wasmclient.Uint32 { + return this.toUint32(this.get(ResBlockIndex)); } governingAddress(): wasmclient.Address { @@ -54,8 +54,8 @@ export class ControlAddressesResults extends wasmclient.Results { export class GetBlockInfoView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } public async call(): Promise { @@ -78,8 +78,8 @@ export class GetBlockInfoResults extends wasmclient.Results { export class GetEventsForBlockView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } public async call(): Promise { @@ -106,12 +106,12 @@ export class GetEventsForContractView extends wasmclient.ClientView { this.args.set(ArgContractHname, this.args.fromHname(v)); } - public fromBlock(v: wasmclient.Int32): void { - this.args.set(ArgFromBlock, this.args.fromInt32(v)); + public fromBlock(v: wasmclient.Uint32): void { + this.args.set(ArgFromBlock, this.args.fromUint32(v)); } - public toBlock(v: wasmclient.Int32): void { - this.args.set(ArgToBlock, this.args.fromInt32(v)); + public toBlock(v: wasmclient.Uint32): void { + this.args.set(ArgToBlock, this.args.fromUint32(v)); } public async call(): Promise { @@ -166,8 +166,8 @@ export class GetLatestBlockInfoView extends wasmclient.ClientView { export class GetLatestBlockInfoResults extends wasmclient.Results { - blockIndex(): wasmclient.Int32 { - return this.toInt32(this.get(ResBlockIndex)); + blockIndex(): wasmclient.Uint32 { + return this.toUint32(this.get(ResBlockIndex)); } blockInfo(): wasmclient.Bytes { @@ -180,8 +180,8 @@ export class GetLatestBlockInfoResults extends wasmclient.Results { export class GetRequestIDsForBlockView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } public async call(): Promise { @@ -218,12 +218,12 @@ export class GetRequestReceiptView extends wasmclient.ClientView { export class GetRequestReceiptResults extends wasmclient.Results { - blockIndex(): wasmclient.Int32 { - return this.toInt32(this.get(ResBlockIndex)); + blockIndex(): wasmclient.Uint32 { + return this.toUint32(this.get(ResBlockIndex)); } - requestIndex(): wasmclient.Int16 { - return this.toInt16(this.get(ResRequestIndex)); + requestIndex(): wasmclient.Uint16 { + return this.toUint16(this.get(ResRequestIndex)); } requestRecord(): wasmclient.Bytes { @@ -236,8 +236,8 @@ export class GetRequestReceiptResults extends wasmclient.Results { export class GetRequestReceiptsForBlockView extends wasmclient.ClientView { private args: wasmclient.Arguments = new wasmclient.Arguments(); - public blockIndex(v: wasmclient.Int32): void { - this.args.set(ArgBlockIndex, this.args.fromInt32(v)); + public blockIndex(v: wasmclient.Uint32): void { + this.args.set(ArgBlockIndex, this.args.fromUint32(v)); } public async call(): Promise { @@ -284,7 +284,7 @@ export class IsRequestProcessedResults extends wasmclient.Results { export class CoreBlockLogService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0xf538ef2b, new Map()); + super(cl, 0xf538ef2b); } public controlAddresses(): ControlAddressesView { diff --git a/packages/vm/wasmlib/ts/wasmclient/coregovernance/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/coregovernance/service.ts similarity index 99% rename from packages/vm/wasmlib/ts/wasmclient/coregovernance/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/coregovernance/service.ts index f30da2d644..6c1c87bb33 100644 --- a/packages/vm/wasmlib/ts/wasmclient/coregovernance/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/coregovernance/service.ts @@ -302,7 +302,7 @@ export class GetMaxBlobSizeResults extends wasmclient.Results { export class CoreGovernanceService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0x17cf909f, new Map()); + super(cl, 0x17cf909f); } public addAllowedStateControllerAddress(): AddAllowedStateControllerAddressFunc { diff --git a/packages/vm/wasmlib/ts/wasmclient/coreroot/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/coreroot/service.ts similarity index 99% rename from packages/vm/wasmlib/ts/wasmclient/coreroot/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/coreroot/service.ts index b00ab43f67..d38b2318f4 100644 --- a/packages/vm/wasmlib/ts/wasmclient/coreroot/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/coreroot/service.ts @@ -126,7 +126,7 @@ export class GetContractRecordsResults extends wasmclient.Results { export class CoreRootService extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { - super(cl, 0xcebf5908, new Map()); + super(cl, 0xcebf5908); } public deployContract(): DeployContractFunc { diff --git a/packages/vm/wasmlib/ts/wasmclient/crypto/base58.ts b/packages/wasmvm/wasmlib/ts/wasmclient/crypto/base58.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/crypto/base58.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/crypto/base58.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/crypto/ed25519.ts b/packages/wasmvm/wasmlib/ts/wasmclient/crypto/ed25519.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/crypto/ed25519.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/crypto/ed25519.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/crypto/hash.ts b/packages/wasmvm/wasmlib/ts/wasmclient/crypto/hash.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/crypto/hash.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/crypto/hash.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/crypto/index.ts b/packages/wasmvm/wasmlib/ts/wasmclient/crypto/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/crypto/index.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/crypto/index.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/crypto/seed.ts b/packages/wasmvm/wasmlib/ts/wasmclient/crypto/seed.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/crypto/seed.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/crypto/seed.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/decoder.ts b/packages/wasmvm/wasmlib/ts/wasmclient/decoder.ts similarity index 96% rename from packages/vm/wasmlib/ts/wasmclient/decoder.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/decoder.ts index c83f5a9e64..f721171517 100644 --- a/packages/vm/wasmlib/ts/wasmclient/decoder.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/decoder.ts @@ -1,5 +1,6 @@ -// The Results struct is used to gather all arguments for a smart -// contract function call and encode it into a deterministic byte array +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + import * as wasmclient from "./index"; import {Base58} from "./crypto"; import {Buffer} from "./buffer"; diff --git a/packages/vm/wasmlib/ts/wasmclient/encoder.ts b/packages/wasmvm/wasmlib/ts/wasmclient/encoder.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/encoder.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/encoder.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/event.ts b/packages/wasmvm/wasmlib/ts/wasmclient/event.ts similarity index 97% rename from packages/vm/wasmlib/ts/wasmclient/event.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/event.ts index f23c08220f..1ae52896b8 100644 --- a/packages/vm/wasmlib/ts/wasmclient/event.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/event.ts @@ -15,7 +15,7 @@ export class Event { } private next(): string { - return this.msg[this.index++]; + return this.msg[this.index++] ?? ""; } protected nextAddress(): wasmclient.Address { diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_helper.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_helper.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_helper.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_helper.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_models.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_models.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_models.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/faucet/faucet_models.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts similarity index 95% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts index 48aeb971e4..d6920cab4c 100644 --- a/packages/vm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/goshimmerclient.ts @@ -46,8 +46,9 @@ export class GoShimmerClient { const unspents = await this.unspentOutputs({ addresses: [address] }); const currentUnspent = unspents.unspentOutputs.find((x) => x.address.base58 == address); + if (!currentUnspent) throw new Error("current unspent not found"); - const balance = currentUnspent!.outputs + const balance = currentUnspent.outputs .filter( (o) => ["ExtendedLockedOutputType", "SigLockedColoredOutputType"].includes(o.output.type) && @@ -123,7 +124,7 @@ export class GoShimmerClient { public async postOnLedgerRequest( chainId: string, payload: IOnLedger, - transfer: bigint = 1n, + transfer = 1n, keyPair: IKeyPair ): Promise { if (transfer <= 0) { @@ -171,12 +172,14 @@ export class GoShimmerClient { ); } - public async depositIOTAToAccountInChain(keypair: IKeyPair, destinationAgentID: AgentID, amount: bigint) { + public async depositIOTAToAccountInChain(keypair: IKeyPair, destinationAgentID: AgentID, amount: bigint): Promise { const depositfunc = this.coreAccountsService.deposit(); depositfunc.agentID(destinationAgentID); + depositfunc.onLedgerRequest(true); depositfunc.transfer(Transfer.iotas(amount)); depositfunc.sign(keypair); - depositfunc.onLedgerRequest(true); - await depositfunc.post(); + const depositRequestID = await depositfunc.post(); + const success = depositRequestID.length > 0; + return success; } } diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/models/mana.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/mana.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/models/mana.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/mana.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/models/on_ledger.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/on_ledger.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/models/on_ledger.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/on_ledger.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts similarity index 98% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts index 479b745f3d..3250322afa 100644 --- a/packages/vm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/transaction.ts @@ -81,7 +81,7 @@ export class Transaction { * @param tx The tx to get the essence for. * @returns The essence of the transaction. */ - public static essence(tx: ITransaction, payload: Buffer = Buffer.alloc(0)): Buffer { + public static essence(tx: ITransaction): Buffer { const essenceBuffer = new SimpleBufferCursor(); essenceBuffer.writeInt8(tx.version); diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/models/unspent_outputs.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/unspent_outputs.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/models/unspent_outputs.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/models/unspent_outputs.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow.worker.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow.worker.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow.worker.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow.worker.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts similarity index 94% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts index 18dded42f8..9c0b050a7c 100644 --- a/packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/pow_worker_manager.ts @@ -29,7 +29,7 @@ export class PoWWorkerManager { const message: PowWorkerResponse = e.data; if (message.type == 'pow_response' && message.uuid == requestId) { - this.powWorker!.removeEventListener('message', responseHandler); + this.powWorker.removeEventListener('message', responseHandler); if (!message.error) { resolve(message.data); diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/proof_of_work.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/proof_of_work.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/proof_of_work.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/proof_of_work.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/worker-loader.d.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/worker-loader.d.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/worker-loader.d.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/pow_web_worker/worker-loader.d.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/utils/simple_buffer_cursor.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/utils/simple_buffer_cursor.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/utils/simple_buffer_cursor.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/utils/simple_buffer_cursor.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts similarity index 98% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts index fb7f51e719..4d0b9e30bc 100644 --- a/packages/vm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet.ts @@ -109,7 +109,6 @@ export class Wallet { if (!outputsByColor[destinationAddress][Colors.IOTA_COLOR_STRING]) { outputsByColor[destinationAddress][Colors.IOTA_COLOR_STRING] = 0n; } - const t = outputsByColor[destinationAddress][Colors.IOTA_COLOR_STRING]; outputsByColor[destinationAddress][Colors.IOTA_COLOR_STRING] += iotas; consumedFunds[Colors.IOTA_COLOR_STRING] = BigInt(consumedFunds[Colors.IOTA_COLOR_STRING] ?? 0n) - iotas; @@ -191,7 +190,7 @@ export class Wallet { builtInputs: string[] ): Array { const unlockBlocks: IUnlockBlock[] = []; - const txEssence = Transaction.essence(tx, Buffer.alloc(0)); + const txEssence = Transaction.essence(tx); const addressByOutputID: { [outputID: string]: string } = {}; for (const address in consumedOutputs) { diff --git a/packages/vm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet_models.ts b/packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet_models.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet_models.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/goshimmer/wallet/wallet_models.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/index.ts b/packages/wasmvm/wasmlib/ts/wasmclient/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/index.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/index.ts diff --git a/packages/vm/wasmlib/ts/wasmclient/package-lock.json b/packages/wasmvm/wasmlib/ts/wasmclient/package-lock.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/package-lock.json rename to packages/wasmvm/wasmlib/ts/wasmclient/package-lock.json diff --git a/packages/vm/wasmlib/ts/wasmclient/package.json b/packages/wasmvm/wasmlib/ts/wasmclient/package.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/package.json rename to packages/wasmvm/wasmlib/ts/wasmclient/package.json diff --git a/packages/vm/wasmlib/ts/wasmclient/results.ts b/packages/wasmvm/wasmlib/ts/wasmclient/results.ts similarity index 81% rename from packages/vm/wasmlib/ts/wasmclient/results.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/results.ts index 0472c92112..4bbb572b07 100644 --- a/packages/vm/wasmlib/ts/wasmclient/results.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/results.ts @@ -1,5 +1,6 @@ -// The Results struct is used to gather all arguments for a smart -// contract function call and encode it into a deterministic byte array +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + import * as wasmclient from "./index"; import {Buffer} from "./buffer"; @@ -13,13 +14,13 @@ export class Results extends wasmclient.Decoder { protected forEach(keyValue: (key: Buffer, val: Buffer) => void): void { this.res.forEach((val, key) => { - let keyBuf = this.keys.get(key); + const keyBuf = this.keys.get(key); if (keyBuf === undefined) { wasmclient.panic("missing key"); return; } keyValue(keyBuf, val); - }) + }); } protected get(key: string): Buffer | undefined { diff --git a/packages/vm/wasmlib/ts/wasmclient/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/service.ts similarity index 66% rename from packages/vm/wasmlib/ts/wasmclient/service.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/service.ts index efb029f008..a14bae2067 100644 --- a/packages/vm/wasmlib/ts/wasmclient/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/service.ts @@ -5,24 +5,23 @@ import * as wasmclient from "./index"; import {Hash, IKeyPair} from "./crypto"; import {IOnLedger} from "./goshimmer/models/on_ledger"; import {Colors} from "./colors"; -import {Buffer} from './buffer'; +import {Buffer} from "./buffer"; -export type EventHandlers = Map void>; +export interface IEventHandler { + callHandler(topic: string, params: string[]): void; +} export class Service { private serviceClient: wasmclient.ServiceClient; private webSocket: WebSocket | null = null; public keyPair: IKeyPair | null = null; - private eventHandlers: EventHandlers | null = null; + private eventHandlers: Array = []; public scHname: wasmclient.Hname; - private waspWebSocketUrl: string = ""; + private waspWebSocketUrl = ""; - constructor(client: wasmclient.ServiceClient, scHname: wasmclient.Hname, eventHandlers: EventHandlers) { + constructor(client: wasmclient.ServiceClient, scHname: wasmclient.Hname) { this.serviceClient = client; this.scHname = scHname; - if (eventHandlers.size != 0) { - this.configureWebSocketsEventHandlers(eventHandlers); - } } public async callView(viewName: string, args: wasmclient.Arguments, res: wasmclient.Results): Promise { @@ -62,18 +61,33 @@ export class Service { return transactionID; } + public register(handler: IEventHandler): void { + if (this.eventHandlers.length === 0) this.configureWebSocketsEventHandlers(); + + for (let i = 0; i < this.eventHandlers.length; i++) { + if (this.eventHandlers[i] === handler) { + return; + } + } + this.eventHandlers.push(handler); + } + + public unregister(handler: IEventHandler): void { + // remove handler + this.eventHandlers = this.eventHandlers.filter((h) => h !== handler); + if (this.eventHandlers.length === 0) this.webSocket?.close(); + } + // overrides default contract name public serviceContractName(contractName: string): void { - this.scHname = Hash.from(Buffer.from(contractName)).readUInt32LE(0) + this.scHname = Hash.from(Buffer.from(contractName)).readUInt32LE(0); } public async waitRequest(reqID: wasmclient.RequestID): Promise { await this.serviceClient.waspClient.waitRequest(this.serviceClient.configuration.chainId, reqID); } - private configureWebSocketsEventHandlers(eventHandlers: EventHandlers) { - this.eventHandlers = eventHandlers; - + private configureWebSocketsEventHandlers() { if ( this.serviceClient.configuration.waspWebSocketUrl.startsWith("wss://") || this.serviceClient.configuration.waspWebSocketUrl.startsWith("ws://") @@ -83,15 +97,27 @@ export class Service { this.waspWebSocketUrl = this.waspWebSocketUrl.replace("%chainId", this.serviceClient.configuration.chainId); - if (this.eventHandlers.size > 1) this.connectWebSocket(); + this.connectWebSocket(); } private connectWebSocket(): void { - // eslint-disable-next-line no-console - console.log(`Connecting to Websocket => ${this.waspWebSocketUrl}`); this.webSocket = new WebSocket(this.waspWebSocketUrl); + this.webSocket.addEventListener("open", () => this.handleOpenWebSocket()); + this.webSocket.addEventListener("close", () => this.handleCloseWebSocket()); + this.webSocket.addEventListener("error", (x) => this.handleErrorWebSocket(x)); this.webSocket.addEventListener("message", (x) => this.handleIncomingMessage(x)); - this.webSocket.addEventListener("close", () => setTimeout(this.connectWebSocket.bind(this), 1000)); + } + + private handleOpenWebSocket(): void { + console.log(`Connected to Websocket => ${this.waspWebSocketUrl}`); + } + + private handleCloseWebSocket(): void { + console.log(`Disconnected from Websocket => ${this.waspWebSocketUrl}`); + } + + private handleErrorWebSocket(event: Event): void { + console.error(`Web socket error => ${this.waspWebSocketUrl} => ${event}`); } private handleIncomingMessage(message: MessageEvent): void { @@ -102,10 +128,9 @@ export class Service { } const topics = msg[3].split("|"); const topic = topics[0]; - if (this.eventHandlers && this.eventHandlers.has(topic)) { - const eventHandler = this.eventHandlers.get(topic)!; - const eventHandlerMsg = topics.slice(1); - eventHandler(eventHandlerMsg); + const params = topics.slice(1); + for (let i = 0; i < this.eventHandlers.length; i++) { + this.eventHandlers[i].callHandler(topic, params); } } } diff --git a/packages/vm/wasmlib/ts/wasmclient/serviceclient.ts b/packages/wasmvm/wasmlib/ts/wasmclient/serviceclient.ts similarity index 86% rename from packages/vm/wasmlib/ts/wasmclient/serviceclient.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/serviceclient.ts index 66e93df086..01c27d586f 100644 --- a/packages/vm/wasmlib/ts/wasmclient/serviceclient.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/serviceclient.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import * as wasmclient from "./index"; -import { Configuration, IConfiguration } from "./configuration"; -import { CoreAccountsService } from "./coreaccounts/service"; +import {Configuration, IConfiguration} from "./configuration"; +import {CoreAccountsService} from "./coreaccounts/service"; export class ServiceClient { waspClient: wasmclient.WaspClient; @@ -12,8 +12,8 @@ export class ServiceClient { constructor(configuration: Configuration) { this.configuration = configuration; - this.waspClient = new wasmclient.WaspClient(configuration.waspApiUrl); const accountsService = new CoreAccountsService(this); + this.waspClient = new wasmclient.WaspClient(configuration.waspApiUrl, accountsService); this.goShimmerClient = new wasmclient.GoShimmerClient(configuration, accountsService); } diff --git a/packages/vm/wasmlib/ts/wasmclient/transfer.ts b/packages/wasmvm/wasmlib/ts/wasmclient/transfer.ts similarity index 98% rename from packages/vm/wasmlib/ts/wasmclient/transfer.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/transfer.ts index 267eb32e12..06a1697803 100644 --- a/packages/vm/wasmlib/ts/wasmclient/transfer.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/transfer.ts @@ -4,7 +4,7 @@ import * as wasmclient from "./index" import {Base58} from "./crypto"; import {Buffer} from "./buffer"; -import { Colors } from "./colors"; +import {Colors} from "./colors"; export class Transfer { private xfer = new Map(); diff --git a/packages/vm/wasmlib/ts/wasmclient/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmclient/tsconfig.json similarity index 96% rename from packages/vm/wasmlib/ts/wasmclient/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmclient/tsconfig.json index 6154e4f4be..4066cb02ba 100644 --- a/packages/vm/wasmlib/ts/wasmclient/tsconfig.json +++ b/packages/wasmvm/wasmlib/ts/wasmclient/tsconfig.json @@ -10,11 +10,11 @@ "baseUrl": ".", "paths": { "@/*": ["./*"] - }, + } }, "preferBuiltins": true, "include": ["./**/*.ts"], "exclude": [ "node_modules" - ], + ] } \ No newline at end of file diff --git a/packages/vm/wasmlib/ts/wasmclient/types.ts b/packages/wasmvm/wasmlib/ts/wasmclient/types.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmclient/types.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/types.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/wasmrequests/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/wasmrequests/service.ts new file mode 100644 index 0000000000..5d33ce1c64 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmclient/wasmrequests/service.ts @@ -0,0 +1,19 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmclient from "wasmclient" + + + +///////////////////////////// WasmRequestsService ///////////////////////////// + +export class WasmRequestsService extends wasmclient.Service { + + public constructor(cl: wasmclient.ServiceClient) { + super(cl, 0x98e19453); + } +} diff --git a/packages/vm/wasmlib/ts/wasmclient/waspclient.ts b/packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts similarity index 79% rename from packages/vm/wasmlib/ts/wasmclient/waspclient.ts rename to packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts index 0e34996400..2087149090 100644 --- a/packages/vm/wasmlib/ts/wasmclient/waspclient.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts @@ -6,6 +6,8 @@ import { Buffer } from "./buffer"; import { IResponse } from "./api_common/response_models"; import * as requestSender from "./api_common/request_sender"; import { Base58, ED25519, Hash, IKeyPair } from "./crypto"; +import {Colors} from "./colors"; +import {CoreAccountsService} from "./coreaccounts/service"; interface ICallViewResponse extends IResponse { Items: [{ Key: string; Value: string }]; @@ -31,10 +33,12 @@ export class Items { export class WaspClient { private waspAPI: string; + private coreAccountsService: CoreAccountsService; - constructor(waspAPI: string) { + constructor(waspAPI: string, coreAccountsService: CoreAccountsService) { if (waspAPI.startsWith("https://") || waspAPI.startsWith("http://")) this.waspAPI = waspAPI; else this.waspAPI = "http://" + waspAPI; + this.coreAccountsService = coreAccountsService; } public async callView(chainID: string, contractHName: string, entryPoint: string, args: Items, res: wasmclient.Results): Promise { @@ -89,4 +93,17 @@ export class WaspClient { return Base58.encode(requestID); } + + public async getIOTABalanceInChain(agentID: wasmclient.AgentID): Promise { + const balanceView = this.coreAccountsService.balance(); + balanceView.agentID(agentID); + const result = await balanceView.call(); + const balances = result.balances(); + const iotaBalance = balances.has(Colors.IOTA_COLOR_STRING) + ? balances.get(Colors.IOTA_COLOR_STRING) + : balances.has(Colors.IOTA_COLOR) + ? balances.get(Colors.IOTA_COLOR) + : 0n; + return iotaBalance ?? 0n; + } } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/assets.ts b/packages/wasmvm/wasmlib/ts/wasmlib/assets.ts new file mode 100644 index 0000000000..bea7c1445f --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/assets.ts @@ -0,0 +1,103 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./wasmtypes" +import {ScDict} from "./dict"; + +export class ScAssets { + assets: Map = new Map(); + + public constructor(buf: u8[]) { + if (buf.length != 0) { + const dec = new wasmtypes.WasmDecoder(buf); + const size = wasmtypes.uint32FromBytes(dec.fixedBytes(wasmtypes.ScUint32Length)); + for (let i: u32 = 0; i < size; i++) { + const color = wasmtypes.colorDecode(dec); + this.assets.set(ScDict.toKey(color.id), wasmtypes.uint64FromBytes(dec.fixedBytes(wasmtypes.ScUint64Length))); + } + } + } + + public balances(): ScBalances { + return new ScBalances(this); + } + + public toBytes(): u8[] { + const keys = this.assets.keys().sort(); + const enc = new wasmtypes.WasmEncoder(); + enc.fixedBytes(wasmtypes.uint32ToBytes(keys.length as u32), wasmtypes.ScUint32Length); + for (let i = 0; i < keys.length; i++) { + const mapKey = keys[i] + const colorId = ScDict.fromKey(mapKey); + enc.fixedBytes(colorId, wasmtypes.ScColorLength); + enc.fixedBytes(wasmtypes.uint64ToBytes(this.assets.get(mapKey)), wasmtypes.ScUint64Length); + } + return enc.buf() + } +} + +export class ScBalances { + assets: Map; + + constructor(assets: ScAssets) { + this.assets = assets.assets; + } + + public balance(color: wasmtypes.ScColor): u64 { + const mapKey = ScDict.toKey(color.id); + if (!this.assets.has(mapKey)) { + return 0; + } + return this.assets.get(mapKey); + } + + public colors(): wasmtypes.ScColor[] { + let colors: wasmtypes.ScColor[] = []; + const keys = this.assets.keys(); + for (let i = 0; i < keys.length; i++) { + const colorId = ScDict.fromKey(keys[i]); + colors.push(wasmtypes.colorFromBytes(colorId)); + } + return colors; + } +} + +export class ScTransfers extends ScAssets { + public constructor() { + super([]); + } + + public static fromBalances(balances: ScBalances): ScTransfers { + const transfer = new ScTransfers(); + const colors = balances.colors(); + for (let i = 0; i < colors.length; i++) { + const color = colors[i]; + transfer.set(color, balances.balance(color)); + } + return transfer; + } + + public static iotas(amount: u64): ScTransfers { + return ScTransfers.transfer(wasmtypes.IOTA, amount); + } + + public static transfer(color: wasmtypes.ScColor, amount: u64): ScTransfers { + const transfer = new ScTransfers(); + transfer.set(color, amount); + return transfer; + } + + public isEmpty(): bool { + const keys = this.assets.keys(); + for (let i = 0; i < keys.length; i++) { + if (this.assets.get(keys[i]) != 0) { + return false; + } + } + return true; + } + + public set(color: wasmtypes.ScColor, amount: u64): void { + this.assets.set(ScDict.toKey(color.id), amount); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/context.ts b/packages/wasmvm/wasmlib/ts/wasmlib/context.ts new file mode 100644 index 0000000000..2c5bcdeae7 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/context.ts @@ -0,0 +1,41 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// encapsulates standard host entities into a simple interface + +import * as wasmtypes from "./wasmtypes" +import {ScBalances, ScTransfers} from "./assets"; +import {ScFuncCallContext, ScViewCallContext} from "./contract"; +import {panic, ScSandboxFunc, ScSandboxView} from "./sandbox"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract interface with mutable access to state +export class ScFuncContext extends ScSandboxFunc implements ScViewCallContext, ScFuncCallContext { + canCallFunc(): void { + panic("canCallFunc"); + } + + canCallView(): void { + panic("canCallView"); + } + + // TODO deprecated + incoming(): ScBalances { + return super.incomingTransfer(); + } + + // TODO deprecated + transferToAddress(address: wasmtypes.ScAddress, transfer: ScTransfers): void { + super.send(address, transfer); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// smart contract view interface which has only immutable access to state +export class ScViewContext extends ScSandboxView implements ScViewCallContext { + canCallView(): void { + panic("canCallView"); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/contract.ts new file mode 100644 index 0000000000..d32213079a --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/contract.ts @@ -0,0 +1,134 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmrequests from "./wasmrequests" +import * as wasmtypes from "./wasmtypes" +import {ScAssets, ScTransfers} from "./assets"; +import {ScDict} from "./dict"; +import {sandbox} from "./host"; +import {FnCall, FnPost, panic, ScSandbox} from "./sandbox"; + +// base contract objects + +export interface ScFuncCallContext { + canCallFunc(): void; +} + +export interface ScViewCallContext { + canCallView(): void; +} + +export function newCallParamsProxy(v: ScView): wasmtypes.Proxy { + v.params = new ScDict([]); + return v.params.asProxy(); +} + +export function newCallResultsProxy(v: ScView): wasmtypes.Proxy { + const proxy = new ScDict([]).asProxy(); + v.resultsProxy = proxy; + return proxy +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScView { + private static nilParams: ScDict = new ScDict([]); + public static nilProxy: wasmtypes.Proxy = new wasmtypes.Proxy(ScView.nilParams); + + hContract: wasmtypes.ScHname; + hFunction: wasmtypes.ScHname; + params: ScDict; + resultsProxy: wasmtypes.Proxy | null; + + constructor(hContract: wasmtypes.ScHname, hFunction: wasmtypes.ScHname) { + this.hContract = hContract; + this.hFunction = hFunction; + this.params = ScView.nilParams; + this.resultsProxy = null; + } + + call(): void { + this.callWithTransfer(null); + } + + protected callWithTransfer(transfer: ScAssets | null): void { + //TODO new ScSandboxFunc().call(...) + if (transfer === null) { + transfer = new ScAssets([]); + } + const req = new wasmrequests.CallRequest(); + req.contract = this.hContract; + req.function = this.hFunction; + req.params = this.params.toBytes(); + req.transfer = transfer.toBytes(); + const res = sandbox(FnCall, req.bytes()); + const proxy = this.resultsProxy; + if (proxy != null) { + proxy.kvStore = new ScDict(res); + } + } + + ofContract(hContract: wasmtypes.ScHname): ScView { + this.hContract = hContract; + return this; + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScInitFunc extends ScView { + call(): void { + return panic("cannot call init"); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScFunc extends ScView { + delaySeconds: u32 = 0; + transfers: ScAssets | null = null; + + call(): void { + if (this.delaySeconds != 0) { + return panic("cannot delay a call"); + } + this.callWithTransfer(this.transfers); + } + + delay(seconds: u32): ScFunc { + this.delaySeconds = seconds; + return this; + } + + post(): void { + return this.postToChain(new ScSandbox().chainID()); + } + + postToChain(chainID: wasmtypes.ScChainID): void { + let transfer = this.transfers; + if (transfer === null) { + transfer = new ScAssets([]); + } + const req = new wasmrequests.PostRequest(); + req.chainID = chainID; + req.contract = this.hContract; + req.function = this.hFunction; + req.params = this.params.toBytes(); + req.transfer = transfer.toBytes(); + req.delay = this.delaySeconds; + const res = sandbox(FnPost, req.bytes()); + if (this.resultsProxy) { + //TODO set kvStore directly? + this.resultsProxy = new wasmtypes.Proxy(new ScDict(res)); + } + } + + transfer(transfers: ScTransfers): ScFunc { + this.transfers = transfers; + return this; + } + + transferIotas(amount: i64): ScFunc { + return this.transfer(ScTransfers.iotas(amount)); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/consts.ts similarity index 58% rename from packages/vm/wasmlib/ts/wasmlib/coreaccounts/consts.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/consts.ts index 967aa43c5f..4b60887c1e 100644 --- a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/consts.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "accounts"; export const ScDescription = "Core chain account ledger contract"; -export const HScName = new wasmlib.ScHname(0x3c4b5e02); +export const HScName = new wasmtypes.ScHname(0x3c4b5e02); export const ParamAgentID = "a"; export const ParamWithdrawAmount = "m"; @@ -27,10 +27,10 @@ export const ViewBalance = "balance"; export const ViewGetAccountNonce = "getAccountNonce"; export const ViewTotalAssets = "totalAssets"; -export const HFuncDeposit = new wasmlib.ScHname(0xbdc9102d); -export const HFuncHarvest = new wasmlib.ScHname(0x7b40efbd); -export const HFuncWithdraw = new wasmlib.ScHname(0x9dcc0f41); -export const HViewAccounts = new wasmlib.ScHname(0x3c4b5e02); -export const HViewBalance = new wasmlib.ScHname(0x84168cb4); -export const HViewGetAccountNonce = new wasmlib.ScHname(0x529d7df9); -export const HViewTotalAssets = new wasmlib.ScHname(0xfab0f8d2); +export const HFuncDeposit = new wasmtypes.ScHname(0xbdc9102d); +export const HFuncHarvest = new wasmtypes.ScHname(0x7b40efbd); +export const HFuncWithdraw = new wasmtypes.ScHname(0x9dcc0f41); +export const HViewAccounts = new wasmtypes.ScHname(0x3c4b5e02); +export const HViewBalance = new wasmtypes.ScHname(0x84168cb4); +export const HViewGetAccountNonce = new wasmtypes.ScHname(0x529d7df9); +export const HViewTotalAssets = new wasmtypes.ScHname(0xfab0f8d2); diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/contract.ts new file mode 100644 index 0000000000..d20a7290c4 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/contract.ts @@ -0,0 +1,89 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmlib from "wasmlib"; +import * as sc from "./index"; + +export class DepositCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDeposit); + params: sc.MutableDepositParams = new sc.MutableDepositParams(wasmlib.ScView.nilProxy); +} + +export class HarvestCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncHarvest); + params: sc.MutableHarvestParams = new sc.MutableHarvestParams(wasmlib.ScView.nilProxy); +} + +export class WithdrawCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWithdraw); +} + +export class AccountsCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewAccounts); + results: sc.ImmutableAccountsResults = new sc.ImmutableAccountsResults(wasmlib.ScView.nilProxy); +} + +export class BalanceCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewBalance); + params: sc.MutableBalanceParams = new sc.MutableBalanceParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableBalanceResults = new sc.ImmutableBalanceResults(wasmlib.ScView.nilProxy); +} + +export class GetAccountNonceCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetAccountNonce); + params: sc.MutableGetAccountNonceParams = new sc.MutableGetAccountNonceParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetAccountNonceResults = new sc.ImmutableGetAccountNonceResults(wasmlib.ScView.nilProxy); +} + +export class TotalAssetsCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTotalAssets); + results: sc.ImmutableTotalAssetsResults = new sc.ImmutableTotalAssetsResults(wasmlib.ScView.nilProxy); +} + +export class ScFuncs { + static deposit(_ctx: wasmlib.ScFuncCallContext): DepositCall { + const f = new DepositCall(); + f.params = new sc.MutableDepositParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static harvest(_ctx: wasmlib.ScFuncCallContext): HarvestCall { + const f = new HarvestCall(); + f.params = new sc.MutableHarvestParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static withdraw(_ctx: wasmlib.ScFuncCallContext): WithdrawCall { + return new WithdrawCall(); + } + + static accounts(_ctx: wasmlib.ScViewCallContext): AccountsCall { + const f = new AccountsCall(); + f.results = new sc.ImmutableAccountsResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static balance(_ctx: wasmlib.ScViewCallContext): BalanceCall { + const f = new BalanceCall(); + f.params = new sc.MutableBalanceParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableBalanceResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getAccountNonce(_ctx: wasmlib.ScViewCallContext): GetAccountNonceCall { + const f = new GetAccountNonceCall(); + f.params = new sc.MutableGetAccountNonceParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetAccountNonceResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static totalAssets(_ctx: wasmlib.ScViewCallContext): TotalAssetsCall { + const f = new TotalAssetsCall(); + f.results = new sc.ImmutableTotalAssetsResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreaccounts/index.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/index.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/params.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/params.ts new file mode 100644 index 0000000000..bbeeddeb8d --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/params.ts @@ -0,0 +1,65 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableDepositParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} + +export class MutableDepositParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} + +export class ImmutableHarvestParams extends wasmtypes.ScProxy { + withdrawAmount(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamWithdrawAmount)); + } + + withdrawColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamWithdrawColor)); + } +} + +export class MutableHarvestParams extends wasmtypes.ScProxy { + withdrawAmount(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamWithdrawAmount)); + } + + withdrawColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamWithdrawColor)); + } +} + +export class ImmutableBalanceParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} + +export class MutableBalanceParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} + +export class ImmutableGetAccountNonceParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} + +export class MutableGetAccountNonceParams extends wasmtypes.ScProxy { + agentID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamAgentID)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/results.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/results.ts new file mode 100644 index 0000000000..b3536d40cc --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/results.ts @@ -0,0 +1,93 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class MapAgentIDToImmutableBytes extends wasmtypes.ScProxy { + + getBytes(key: wasmtypes.ScAgentID): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } +} + +export class ImmutableAccountsResults extends wasmtypes.ScProxy { + agents(): sc.MapAgentIDToImmutableBytes { + return new sc.MapAgentIDToImmutableBytes(this.proxy); + } +} + +export class MapAgentIDToMutableBytes extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getBytes(key: wasmtypes.ScAgentID): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.key(wasmtypes.agentIDToBytes(key))); + } +} + +export class MutableAccountsResults extends wasmtypes.ScProxy { + agents(): sc.MapAgentIDToMutableBytes { + return new sc.MapAgentIDToMutableBytes(this.proxy); + } +} + +export class MapColorToImmutableInt64 extends wasmtypes.ScProxy { + + getInt64(key: wasmtypes.ScColor): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.key(wasmtypes.colorToBytes(key))); + } +} + +export class ImmutableBalanceResults extends wasmtypes.ScProxy { + balances(): sc.MapColorToImmutableInt64 { + return new sc.MapColorToImmutableInt64(this.proxy); + } +} + +export class MapColorToMutableInt64 extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getInt64(key: wasmtypes.ScColor): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.key(wasmtypes.colorToBytes(key))); + } +} + +export class MutableBalanceResults extends wasmtypes.ScProxy { + balances(): sc.MapColorToMutableInt64 { + return new sc.MapColorToMutableInt64(this.proxy); + } +} + +export class ImmutableGetAccountNonceResults extends wasmtypes.ScProxy { + accountNonce(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultAccountNonce)); + } +} + +export class MutableGetAccountNonceResults extends wasmtypes.ScProxy { + accountNonce(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultAccountNonce)); + } +} + +export class ImmutableTotalAssetsResults extends wasmtypes.ScProxy { + balances(): sc.MapColorToImmutableInt64 { + return new sc.MapColorToImmutableInt64(this.proxy); + } +} + +export class MutableTotalAssetsResults extends wasmtypes.ScProxy { + balances(): sc.MapColorToMutableInt64 { + return new sc.MapColorToMutableInt64(this.proxy); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreaccounts/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreaccounts/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/coreaccounts/tsconfig.json diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/consts.ts similarity index 63% rename from packages/vm/wasmlib/ts/wasmlib/coreblob/consts.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblob/consts.ts index 9293fa2b4f..d75a05d05d 100644 --- a/packages/vm/wasmlib/ts/wasmlib/coreblob/consts.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "blob"; export const ScDescription = "Core blob contract"; -export const HScName = new wasmlib.ScHname(0xfd91bc63); +export const HScName = new wasmtypes.ScHname(0xfd91bc63); export const ParamBlobs = "this"; export const ParamField = "field"; @@ -24,7 +24,7 @@ export const ViewGetBlobField = "getBlobField"; export const ViewGetBlobInfo = "getBlobInfo"; export const ViewListBlobs = "listBlobs"; -export const HFuncStoreBlob = new wasmlib.ScHname(0xddd4c281); -export const HViewGetBlobField = new wasmlib.ScHname(0x1f448130); -export const HViewGetBlobInfo = new wasmlib.ScHname(0xfde4ab46); -export const HViewListBlobs = new wasmlib.ScHname(0x62ca7990); +export const HFuncStoreBlob = new wasmtypes.ScHname(0xddd4c281); +export const HViewGetBlobField = new wasmtypes.ScHname(0x1f448130); +export const HViewGetBlobInfo = new wasmtypes.ScHname(0xfde4ab46); +export const HViewListBlobs = new wasmtypes.ScHname(0x62ca7990); diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/contract.ts new file mode 100644 index 0000000000..b45e67809c --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/contract.ts @@ -0,0 +1,61 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmlib from "wasmlib"; +import * as sc from "./index"; + +export class StoreBlobCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncStoreBlob); + params: sc.MutableStoreBlobParams = new sc.MutableStoreBlobParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableStoreBlobResults = new sc.ImmutableStoreBlobResults(wasmlib.ScView.nilProxy); +} + +export class GetBlobFieldCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlobField); + params: sc.MutableGetBlobFieldParams = new sc.MutableGetBlobFieldParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetBlobFieldResults = new sc.ImmutableGetBlobFieldResults(wasmlib.ScView.nilProxy); +} + +export class GetBlobInfoCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlobInfo); + params: sc.MutableGetBlobInfoParams = new sc.MutableGetBlobInfoParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetBlobInfoResults = new sc.ImmutableGetBlobInfoResults(wasmlib.ScView.nilProxy); +} + +export class ListBlobsCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewListBlobs); + results: sc.ImmutableListBlobsResults = new sc.ImmutableListBlobsResults(wasmlib.ScView.nilProxy); +} + +export class ScFuncs { + static storeBlob(_ctx: wasmlib.ScFuncCallContext): StoreBlobCall { + const f = new StoreBlobCall(); + f.params = new sc.MutableStoreBlobParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableStoreBlobResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getBlobField(_ctx: wasmlib.ScViewCallContext): GetBlobFieldCall { + const f = new GetBlobFieldCall(); + f.params = new sc.MutableGetBlobFieldParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetBlobFieldResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getBlobInfo(_ctx: wasmlib.ScViewCallContext): GetBlobInfoCall { + const f = new GetBlobInfoCall(); + f.params = new sc.MutableGetBlobInfoParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetBlobInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static listBlobs(_ctx: wasmlib.ScViewCallContext): ListBlobsCall { + const f = new ListBlobsCall(); + f.results = new sc.ImmutableListBlobsResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreblob/index.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblob/index.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/params.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/params.ts new file mode 100644 index 0000000000..f11008f14d --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/params.ts @@ -0,0 +1,71 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class MapStringToImmutableBytes extends wasmtypes.ScProxy { + + getBytes(key: string): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.key(wasmtypes.stringToBytes(key))); + } +} + +export class ImmutableStoreBlobParams extends wasmtypes.ScProxy { + blobs(): sc.MapStringToImmutableBytes { + return new sc.MapStringToImmutableBytes(this.proxy); + } +} + +export class MapStringToMutableBytes extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getBytes(key: string): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.key(wasmtypes.stringToBytes(key))); + } +} + +export class MutableStoreBlobParams extends wasmtypes.ScProxy { + blobs(): sc.MapStringToMutableBytes { + return new sc.MapStringToMutableBytes(this.proxy); + } +} + +export class ImmutableGetBlobFieldParams extends wasmtypes.ScProxy { + field(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamField)); + } + + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamHash)); + } +} + +export class MutableGetBlobFieldParams extends wasmtypes.ScProxy { + field(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamField)); + } + + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamHash)); + } +} + +export class ImmutableGetBlobInfoParams extends wasmtypes.ScProxy { + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamHash)); + } +} + +export class MutableGetBlobInfoParams extends wasmtypes.ScProxy { + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamHash)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/results.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/results.ts new file mode 100644 index 0000000000..03d0a98cf9 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/results.ts @@ -0,0 +1,93 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableStoreBlobResults extends wasmtypes.ScProxy { + hash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ResultHash)); + } +} + +export class MutableStoreBlobResults extends wasmtypes.ScProxy { + hash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ResultHash)); + } +} + +export class ImmutableGetBlobFieldResults extends wasmtypes.ScProxy { + bytes(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultBytes)); + } +} + +export class MutableGetBlobFieldResults extends wasmtypes.ScProxy { + bytes(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultBytes)); + } +} + +export class MapStringToImmutableInt32 extends wasmtypes.ScProxy { + + getInt32(key: string): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.key(wasmtypes.stringToBytes(key))); + } +} + +export class ImmutableGetBlobInfoResults extends wasmtypes.ScProxy { + blobSizes(): sc.MapStringToImmutableInt32 { + return new sc.MapStringToImmutableInt32(this.proxy); + } +} + +export class MapStringToMutableInt32 extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getInt32(key: string): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.key(wasmtypes.stringToBytes(key))); + } +} + +export class MutableGetBlobInfoResults extends wasmtypes.ScProxy { + blobSizes(): sc.MapStringToMutableInt32 { + return new sc.MapStringToMutableInt32(this.proxy); + } +} + +export class MapHashToImmutableInt32 extends wasmtypes.ScProxy { + + getInt32(key: wasmtypes.ScHash): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.key(wasmtypes.hashToBytes(key))); + } +} + +export class ImmutableListBlobsResults extends wasmtypes.ScProxy { + blobSizes(): sc.MapHashToImmutableInt32 { + return new sc.MapHashToImmutableInt32(this.proxy); + } +} + +export class MapHashToMutableInt32 extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getInt32(key: wasmtypes.ScHash): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.key(wasmtypes.hashToBytes(key))); + } +} + +export class MutableListBlobsResults extends wasmtypes.ScProxy { + blobSizes(): sc.MapHashToMutableInt32 { + return new sc.MapHashToMutableInt32(this.proxy); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblob/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/coreblob/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreblob/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblob/tsconfig.json diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/consts.ts similarity index 63% rename from packages/vm/wasmlib/ts/wasmlib/coreblocklog/consts.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/consts.ts index 8525d71f43..11f90ad0e6 100644 --- a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/consts.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "blocklog"; export const ScDescription = "Core block log contract"; -export const HScName = new wasmlib.ScHname(0xf538ef2b); +export const HScName = new wasmtypes.ScHname(0xf538ef2b); export const ParamBlockIndex = "n"; export const ParamContractHname = "h"; @@ -38,13 +38,13 @@ export const ViewGetRequestReceipt = "getRequestReceipt"; export const ViewGetRequestReceiptsForBlock = "getRequestReceiptsForBlock"; export const ViewIsRequestProcessed = "isRequestProcessed"; -export const HViewControlAddresses = new wasmlib.ScHname(0x796bd223); -export const HViewGetBlockInfo = new wasmlib.ScHname(0xbe89f9b3); -export const HViewGetEventsForBlock = new wasmlib.ScHname(0x36232798); -export const HViewGetEventsForContract = new wasmlib.ScHname(0x682a1922); -export const HViewGetEventsForRequest = new wasmlib.ScHname(0x4f8d68e4); -export const HViewGetLatestBlockInfo = new wasmlib.ScHname(0x084a1760); -export const HViewGetRequestIDsForBlock = new wasmlib.ScHname(0x5a20327a); -export const HViewGetRequestReceipt = new wasmlib.ScHname(0xb7f9534f); -export const HViewGetRequestReceiptsForBlock = new wasmlib.ScHname(0x77e3beef); -export const HViewIsRequestProcessed = new wasmlib.ScHname(0xd57d50a9); +export const HViewControlAddresses = new wasmtypes.ScHname(0x796bd223); +export const HViewGetBlockInfo = new wasmtypes.ScHname(0xbe89f9b3); +export const HViewGetEventsForBlock = new wasmtypes.ScHname(0x36232798); +export const HViewGetEventsForContract = new wasmtypes.ScHname(0x682a1922); +export const HViewGetEventsForRequest = new wasmtypes.ScHname(0x4f8d68e4); +export const HViewGetLatestBlockInfo = new wasmtypes.ScHname(0x084a1760); +export const HViewGetRequestIDsForBlock = new wasmtypes.ScHname(0x5a20327a); +export const HViewGetRequestReceipt = new wasmtypes.ScHname(0xb7f9534f); +export const HViewGetRequestReceiptsForBlock = new wasmtypes.ScHname(0x77e3beef); +export const HViewIsRequestProcessed = new wasmtypes.ScHname(0xd57d50a9); diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/contract.ts new file mode 100644 index 0000000000..b83fee345e --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/contract.ts @@ -0,0 +1,137 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmlib from "wasmlib"; +import * as sc from "./index"; + +export class ControlAddressesCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewControlAddresses); + results: sc.ImmutableControlAddressesResults = new sc.ImmutableControlAddressesResults(wasmlib.ScView.nilProxy); +} + +export class GetBlockInfoCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetBlockInfo); + params: sc.MutableGetBlockInfoParams = new sc.MutableGetBlockInfoParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetBlockInfoResults = new sc.ImmutableGetBlockInfoResults(wasmlib.ScView.nilProxy); +} + +export class GetEventsForBlockCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForBlock); + params: sc.MutableGetEventsForBlockParams = new sc.MutableGetEventsForBlockParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetEventsForBlockResults = new sc.ImmutableGetEventsForBlockResults(wasmlib.ScView.nilProxy); +} + +export class GetEventsForContractCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForContract); + params: sc.MutableGetEventsForContractParams = new sc.MutableGetEventsForContractParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetEventsForContractResults = new sc.ImmutableGetEventsForContractResults(wasmlib.ScView.nilProxy); +} + +export class GetEventsForRequestCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetEventsForRequest); + params: sc.MutableGetEventsForRequestParams = new sc.MutableGetEventsForRequestParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetEventsForRequestResults = new sc.ImmutableGetEventsForRequestResults(wasmlib.ScView.nilProxy); +} + +export class GetLatestBlockInfoCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetLatestBlockInfo); + results: sc.ImmutableGetLatestBlockInfoResults = new sc.ImmutableGetLatestBlockInfoResults(wasmlib.ScView.nilProxy); +} + +export class GetRequestIDsForBlockCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestIDsForBlock); + params: sc.MutableGetRequestIDsForBlockParams = new sc.MutableGetRequestIDsForBlockParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetRequestIDsForBlockResults = new sc.ImmutableGetRequestIDsForBlockResults(wasmlib.ScView.nilProxy); +} + +export class GetRequestReceiptCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestReceipt); + params: sc.MutableGetRequestReceiptParams = new sc.MutableGetRequestReceiptParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetRequestReceiptResults = new sc.ImmutableGetRequestReceiptResults(wasmlib.ScView.nilProxy); +} + +export class GetRequestReceiptsForBlockCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetRequestReceiptsForBlock); + params: sc.MutableGetRequestReceiptsForBlockParams = new sc.MutableGetRequestReceiptsForBlockParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetRequestReceiptsForBlockResults = new sc.ImmutableGetRequestReceiptsForBlockResults(wasmlib.ScView.nilProxy); +} + +export class IsRequestProcessedCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewIsRequestProcessed); + params: sc.MutableIsRequestProcessedParams = new sc.MutableIsRequestProcessedParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableIsRequestProcessedResults = new sc.ImmutableIsRequestProcessedResults(wasmlib.ScView.nilProxy); +} + +export class ScFuncs { + static controlAddresses(_ctx: wasmlib.ScViewCallContext): ControlAddressesCall { + const f = new ControlAddressesCall(); + f.results = new sc.ImmutableControlAddressesResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getBlockInfo(_ctx: wasmlib.ScViewCallContext): GetBlockInfoCall { + const f = new GetBlockInfoCall(); + f.params = new sc.MutableGetBlockInfoParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetBlockInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getEventsForBlock(_ctx: wasmlib.ScViewCallContext): GetEventsForBlockCall { + const f = new GetEventsForBlockCall(); + f.params = new sc.MutableGetEventsForBlockParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetEventsForBlockResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getEventsForContract(_ctx: wasmlib.ScViewCallContext): GetEventsForContractCall { + const f = new GetEventsForContractCall(); + f.params = new sc.MutableGetEventsForContractParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetEventsForContractResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getEventsForRequest(_ctx: wasmlib.ScViewCallContext): GetEventsForRequestCall { + const f = new GetEventsForRequestCall(); + f.params = new sc.MutableGetEventsForRequestParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetEventsForRequestResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getLatestBlockInfo(_ctx: wasmlib.ScViewCallContext): GetLatestBlockInfoCall { + const f = new GetLatestBlockInfoCall(); + f.results = new sc.ImmutableGetLatestBlockInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getRequestIDsForBlock(_ctx: wasmlib.ScViewCallContext): GetRequestIDsForBlockCall { + const f = new GetRequestIDsForBlockCall(); + f.params = new sc.MutableGetRequestIDsForBlockParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetRequestIDsForBlockResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getRequestReceipt(_ctx: wasmlib.ScViewCallContext): GetRequestReceiptCall { + const f = new GetRequestReceiptCall(); + f.params = new sc.MutableGetRequestReceiptParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetRequestReceiptResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getRequestReceiptsForBlock(_ctx: wasmlib.ScViewCallContext): GetRequestReceiptsForBlockCall { + const f = new GetRequestReceiptsForBlockCall(); + f.params = new sc.MutableGetRequestReceiptsForBlockParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetRequestReceiptsForBlockResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static isRequestProcessed(_ctx: wasmlib.ScViewCallContext): IsRequestProcessedCall { + const f = new IsRequestProcessedCall(); + f.params = new sc.MutableIsRequestProcessedParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableIsRequestProcessedResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreblocklog/index.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/index.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/params.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/params.ts new file mode 100644 index 0000000000..c0336bd2b0 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/params.ts @@ -0,0 +1,121 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableGetBlockInfoParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class MutableGetBlockInfoParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class ImmutableGetEventsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class MutableGetEventsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class ImmutableGetEventsForContractParams extends wasmtypes.ScProxy { + contractHname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamContractHname)); + } + + fromBlock(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamFromBlock)); + } + + toBlock(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamToBlock)); + } +} + +export class MutableGetEventsForContractParams extends wasmtypes.ScProxy { + contractHname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamContractHname)); + } + + fromBlock(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamFromBlock)); + } + + toBlock(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamToBlock)); + } +} + +export class ImmutableGetEventsForRequestParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScImmutableRequestID { + return new wasmtypes.ScImmutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} + +export class MutableGetEventsForRequestParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} + +export class ImmutableGetRequestIDsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class MutableGetRequestIDsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class ImmutableGetRequestReceiptParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScImmutableRequestID { + return new wasmtypes.ScImmutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} + +export class MutableGetRequestReceiptParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} + +export class ImmutableGetRequestReceiptsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class MutableGetRequestReceiptsForBlockParams extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ParamBlockIndex)); + } +} + +export class ImmutableIsRequestProcessedParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScImmutableRequestID { + return new wasmtypes.ScImmutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} + +export class MutableIsRequestProcessedParams extends wasmtypes.ScProxy { + requestID(): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.root(sc.ParamRequestID)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/results.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/results.ts new file mode 100644 index 0000000000..0edb64b735 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/results.ts @@ -0,0 +1,229 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableControlAddressesResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + governingAddress(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ResultGoverningAddress)); + } + + stateControllerAddress(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ResultStateControllerAddress)); + } +} + +export class MutableControlAddressesResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + governingAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ResultGoverningAddress)); + } + + stateControllerAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ResultStateControllerAddress)); + } +} + +export class ImmutableGetBlockInfoResults extends wasmtypes.ScProxy { + blockInfo(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultBlockInfo)); + } +} + +export class MutableGetBlockInfoResults extends wasmtypes.ScProxy { + blockInfo(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultBlockInfo)); + } +} + +export class ArrayOfImmutableBytes extends wasmtypes.ScProxy { + + length(): u32 { + return this.proxy.length(); + } + + getBytes(index: u32): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.index(index)); + } +} + +export class ImmutableGetEventsForBlockResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfImmutableBytes { + return new sc.ArrayOfImmutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class ArrayOfMutableBytes extends wasmtypes.ScProxy { + + appendBytes(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.append()); + } + + clear(): void { + this.proxy.clearArray(); + } + + length(): u32 { + return this.proxy.length(); + } + + getBytes(index: u32): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.index(index)); + } +} + +export class MutableGetEventsForBlockResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfMutableBytes { + return new sc.ArrayOfMutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class ImmutableGetEventsForContractResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfImmutableBytes { + return new sc.ArrayOfImmutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class MutableGetEventsForContractResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfMutableBytes { + return new sc.ArrayOfMutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class ImmutableGetEventsForRequestResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfImmutableBytes { + return new sc.ArrayOfImmutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class MutableGetEventsForRequestResults extends wasmtypes.ScProxy { + event(): sc.ArrayOfMutableBytes { + return new sc.ArrayOfMutableBytes(this.proxy.root(sc.ResultEvent)); + } +} + +export class ImmutableGetLatestBlockInfoResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + blockInfo(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultBlockInfo)); + } +} + +export class MutableGetLatestBlockInfoResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + blockInfo(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultBlockInfo)); + } +} + +export class ArrayOfImmutableRequestID extends wasmtypes.ScProxy { + + length(): u32 { + return this.proxy.length(); + } + + getRequestID(index: u32): wasmtypes.ScImmutableRequestID { + return new wasmtypes.ScImmutableRequestID(this.proxy.index(index)); + } +} + +export class ImmutableGetRequestIDsForBlockResults extends wasmtypes.ScProxy { + requestID(): sc.ArrayOfImmutableRequestID { + return new sc.ArrayOfImmutableRequestID(this.proxy.root(sc.ResultRequestID)); + } +} + +export class ArrayOfMutableRequestID extends wasmtypes.ScProxy { + + appendRequestID(): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.append()); + } + + clear(): void { + this.proxy.clearArray(); + } + + length(): u32 { + return this.proxy.length(); + } + + getRequestID(index: u32): wasmtypes.ScMutableRequestID { + return new wasmtypes.ScMutableRequestID(this.proxy.index(index)); + } +} + +export class MutableGetRequestIDsForBlockResults extends wasmtypes.ScProxy { + requestID(): sc.ArrayOfMutableRequestID { + return new sc.ArrayOfMutableRequestID(this.proxy.root(sc.ResultRequestID)); + } +} + +export class ImmutableGetRequestReceiptResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScImmutableUint32 { + return new wasmtypes.ScImmutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + requestIndex(): wasmtypes.ScImmutableUint16 { + return new wasmtypes.ScImmutableUint16(this.proxy.root(sc.ResultRequestIndex)); + } + + requestRecord(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultRequestRecord)); + } +} + +export class MutableGetRequestReceiptResults extends wasmtypes.ScProxy { + blockIndex(): wasmtypes.ScMutableUint32 { + return new wasmtypes.ScMutableUint32(this.proxy.root(sc.ResultBlockIndex)); + } + + requestIndex(): wasmtypes.ScMutableUint16 { + return new wasmtypes.ScMutableUint16(this.proxy.root(sc.ResultRequestIndex)); + } + + requestRecord(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultRequestRecord)); + } +} + +export class ImmutableGetRequestReceiptsForBlockResults extends wasmtypes.ScProxy { + requestRecord(): sc.ArrayOfImmutableBytes { + return new sc.ArrayOfImmutableBytes(this.proxy.root(sc.ResultRequestRecord)); + } +} + +export class MutableGetRequestReceiptsForBlockResults extends wasmtypes.ScProxy { + requestRecord(): sc.ArrayOfMutableBytes { + return new sc.ArrayOfMutableBytes(this.proxy.root(sc.ResultRequestRecord)); + } +} + +export class ImmutableIsRequestProcessedResults extends wasmtypes.ScProxy { + requestProcessed(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultRequestProcessed)); + } +} + +export class MutableIsRequestProcessedResults extends wasmtypes.ScProxy { + requestProcessed(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultRequestProcessed)); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreblocklog/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreblocklog/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/coreblocklog/tsconfig.json diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/consts.ts similarity index 87% rename from packages/vm/wasmlib/ts/wasmlib/coregovernance/consts.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/consts.ts index bc538fbb2b..56ca393177 100644 --- a/packages/vm/wasmlib/ts/wasmlib/coregovernance/consts.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "governance"; export const ScDescription = "Core governance contract"; -export const HScName = new wasmlib.ScHname(0x17cf909f); +export const HScName = new wasmtypes.ScHname(0x17cf909f); export const ParamChainOwner = "oi"; export const ParamFeeColor = "fc"; @@ -47,15 +47,15 @@ export const ViewGetChainInfo = "getChainInfo"; export const ViewGetFeeInfo = "getFeeInfo"; export const ViewGetMaxBlobSize = "getMaxBlobSize"; -export const HFuncAddAllowedStateControllerAddress = new wasmlib.ScHname(0x9469d567); -export const HFuncClaimChainOwnership = new wasmlib.ScHname(0x03ff0fc0); -export const HFuncDelegateChainOwnership = new wasmlib.ScHname(0x93ecb6ad); -export const HFuncRemoveAllowedStateControllerAddress = new wasmlib.ScHname(0x31f69447); -export const HFuncRotateStateController = new wasmlib.ScHname(0x244d1038); -export const HFuncSetChainInfo = new wasmlib.ScHname(0x702f5d2b); -export const HFuncSetContractFee = new wasmlib.ScHname(0x8421a42b); -export const HFuncSetDefaultFee = new wasmlib.ScHname(0x3310ecd0); -export const HViewGetAllowedStateControllerAddresses = new wasmlib.ScHname(0xf3505183); -export const HViewGetChainInfo = new wasmlib.ScHname(0x434477e2); -export const HViewGetFeeInfo = new wasmlib.ScHname(0x9fe54b48); -export const HViewGetMaxBlobSize = new wasmlib.ScHname(0xe1db3d28); +export const HFuncAddAllowedStateControllerAddress = new wasmtypes.ScHname(0x9469d567); +export const HFuncClaimChainOwnership = new wasmtypes.ScHname(0x03ff0fc0); +export const HFuncDelegateChainOwnership = new wasmtypes.ScHname(0x93ecb6ad); +export const HFuncRemoveAllowedStateControllerAddress = new wasmtypes.ScHname(0x31f69447); +export const HFuncRotateStateController = new wasmtypes.ScHname(0x244d1038); +export const HFuncSetChainInfo = new wasmtypes.ScHname(0x702f5d2b); +export const HFuncSetContractFee = new wasmtypes.ScHname(0x8421a42b); +export const HFuncSetDefaultFee = new wasmtypes.ScHname(0x3310ecd0); +export const HViewGetAllowedStateControllerAddresses = new wasmtypes.ScHname(0xf3505183); +export const HViewGetChainInfo = new wasmtypes.ScHname(0x434477e2); +export const HViewGetFeeInfo = new wasmtypes.ScHname(0x9fe54b48); +export const HViewGetMaxBlobSize = new wasmtypes.ScHname(0xe1db3d28); diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/contract.ts new file mode 100644 index 0000000000..50b40dd3f6 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/contract.ts @@ -0,0 +1,142 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmlib from "wasmlib"; +import * as sc from "./index"; + +export class AddAllowedStateControllerAddressCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncAddAllowedStateControllerAddress); + params: sc.MutableAddAllowedStateControllerAddressParams = new sc.MutableAddAllowedStateControllerAddressParams(wasmlib.ScView.nilProxy); +} + +export class ClaimChainOwnershipCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncClaimChainOwnership); +} + +export class DelegateChainOwnershipCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDelegateChainOwnership); + params: sc.MutableDelegateChainOwnershipParams = new sc.MutableDelegateChainOwnershipParams(wasmlib.ScView.nilProxy); +} + +export class RemoveAllowedStateControllerAddressCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRemoveAllowedStateControllerAddress); + params: sc.MutableRemoveAllowedStateControllerAddressParams = new sc.MutableRemoveAllowedStateControllerAddressParams(wasmlib.ScView.nilProxy); +} + +export class RotateStateControllerCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRotateStateController); + params: sc.MutableRotateStateControllerParams = new sc.MutableRotateStateControllerParams(wasmlib.ScView.nilProxy); +} + +export class SetChainInfoCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetChainInfo); + params: sc.MutableSetChainInfoParams = new sc.MutableSetChainInfoParams(wasmlib.ScView.nilProxy); +} + +export class SetContractFeeCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetContractFee); + params: sc.MutableSetContractFeeParams = new sc.MutableSetContractFeeParams(wasmlib.ScView.nilProxy); +} + +export class SetDefaultFeeCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetDefaultFee); + params: sc.MutableSetDefaultFeeParams = new sc.MutableSetDefaultFeeParams(wasmlib.ScView.nilProxy); +} + +export class GetAllowedStateControllerAddressesCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetAllowedStateControllerAddresses); + results: sc.ImmutableGetAllowedStateControllerAddressesResults = new sc.ImmutableGetAllowedStateControllerAddressesResults(wasmlib.ScView.nilProxy); +} + +export class GetChainInfoCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetChainInfo); + results: sc.ImmutableGetChainInfoResults = new sc.ImmutableGetChainInfoResults(wasmlib.ScView.nilProxy); +} + +export class GetFeeInfoCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetFeeInfo); + params: sc.MutableGetFeeInfoParams = new sc.MutableGetFeeInfoParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableGetFeeInfoResults = new sc.ImmutableGetFeeInfoResults(wasmlib.ScView.nilProxy); +} + +export class GetMaxBlobSizeCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetMaxBlobSize); + results: sc.ImmutableGetMaxBlobSizeResults = new sc.ImmutableGetMaxBlobSizeResults(wasmlib.ScView.nilProxy); +} + +export class ScFuncs { + static addAllowedStateControllerAddress(_ctx: wasmlib.ScFuncCallContext): AddAllowedStateControllerAddressCall { + const f = new AddAllowedStateControllerAddressCall(); + f.params = new sc.MutableAddAllowedStateControllerAddressParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static claimChainOwnership(_ctx: wasmlib.ScFuncCallContext): ClaimChainOwnershipCall { + return new ClaimChainOwnershipCall(); + } + + static delegateChainOwnership(_ctx: wasmlib.ScFuncCallContext): DelegateChainOwnershipCall { + const f = new DelegateChainOwnershipCall(); + f.params = new sc.MutableDelegateChainOwnershipParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static removeAllowedStateControllerAddress(_ctx: wasmlib.ScFuncCallContext): RemoveAllowedStateControllerAddressCall { + const f = new RemoveAllowedStateControllerAddressCall(); + f.params = new sc.MutableRemoveAllowedStateControllerAddressParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static rotateStateController(_ctx: wasmlib.ScFuncCallContext): RotateStateControllerCall { + const f = new RotateStateControllerCall(); + f.params = new sc.MutableRotateStateControllerParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setChainInfo(_ctx: wasmlib.ScFuncCallContext): SetChainInfoCall { + const f = new SetChainInfoCall(); + f.params = new sc.MutableSetChainInfoParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setContractFee(_ctx: wasmlib.ScFuncCallContext): SetContractFeeCall { + const f = new SetContractFeeCall(); + f.params = new sc.MutableSetContractFeeParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static setDefaultFee(_ctx: wasmlib.ScFuncCallContext): SetDefaultFeeCall { + const f = new SetDefaultFeeCall(); + f.params = new sc.MutableSetDefaultFeeParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static getAllowedStateControllerAddresses(_ctx: wasmlib.ScViewCallContext): GetAllowedStateControllerAddressesCall { + const f = new GetAllowedStateControllerAddressesCall(); + f.results = new sc.ImmutableGetAllowedStateControllerAddressesResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getChainInfo(_ctx: wasmlib.ScViewCallContext): GetChainInfoCall { + const f = new GetChainInfoCall(); + f.results = new sc.ImmutableGetChainInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getFeeInfo(_ctx: wasmlib.ScViewCallContext): GetFeeInfoCall { + const f = new GetFeeInfoCall(); + f.params = new sc.MutableGetFeeInfoParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableGetFeeInfoResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getMaxBlobSize(_ctx: wasmlib.ScViewCallContext): GetMaxBlobSizeCall { + const f = new GetMaxBlobSizeCall(); + f.results = new sc.ImmutableGetMaxBlobSizeResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coregovernance/index.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/index.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/params.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/params.ts new file mode 100644 index 0000000000..f33cda22c9 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/params.ts @@ -0,0 +1,177 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableAddAllowedStateControllerAddressParams extends wasmtypes.ScProxy { + chainOwner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamChainOwner)); + } + + feeColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ParamFeeColor)); + } + + stateControllerAddress(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class MutableAddAllowedStateControllerAddressParams extends wasmtypes.ScProxy { + chainOwner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamChainOwner)); + } + + feeColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ParamFeeColor)); + } + + stateControllerAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class ImmutableDelegateChainOwnershipParams extends wasmtypes.ScProxy { + chainOwner(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamChainOwner)); + } +} + +export class MutableDelegateChainOwnershipParams extends wasmtypes.ScProxy { + chainOwner(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamChainOwner)); + } +} + +export class ImmutableRemoveAllowedStateControllerAddressParams extends wasmtypes.ScProxy { + stateControllerAddress(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class MutableRemoveAllowedStateControllerAddressParams extends wasmtypes.ScProxy { + stateControllerAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class ImmutableRotateStateControllerParams extends wasmtypes.ScProxy { + stateControllerAddress(): wasmtypes.ScImmutableAddress { + return new wasmtypes.ScImmutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class MutableRotateStateControllerParams extends wasmtypes.ScProxy { + stateControllerAddress(): wasmtypes.ScMutableAddress { + return new wasmtypes.ScMutableAddress(this.proxy.root(sc.ParamStateControllerAddress)); + } +} + +export class ImmutableSetChainInfoParams extends wasmtypes.ScProxy { + maxBlobSize(): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.root(sc.ParamMaxBlobSize)); + } + + maxEventSize(): wasmtypes.ScImmutableInt16 { + return new wasmtypes.ScImmutableInt16(this.proxy.root(sc.ParamMaxEventSize)); + } + + maxEventsPerReq(): wasmtypes.ScImmutableInt16 { + return new wasmtypes.ScImmutableInt16(this.proxy.root(sc.ParamMaxEventsPerReq)); + } + + ownerFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class MutableSetChainInfoParams extends wasmtypes.ScProxy { + maxBlobSize(): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.root(sc.ParamMaxBlobSize)); + } + + maxEventSize(): wasmtypes.ScMutableInt16 { + return new wasmtypes.ScMutableInt16(this.proxy.root(sc.ParamMaxEventSize)); + } + + maxEventsPerReq(): wasmtypes.ScMutableInt16 { + return new wasmtypes.ScMutableInt16(this.proxy.root(sc.ParamMaxEventsPerReq)); + } + + ownerFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class ImmutableSetContractFeeParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); + } + + ownerFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class MutableSetContractFeeParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); + } + + ownerFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class ImmutableSetDefaultFeeParams extends wasmtypes.ScProxy { + ownerFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class MutableSetDefaultFeeParams extends wasmtypes.ScProxy { + ownerFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamOwnerFee)); + } + + validatorFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ParamValidatorFee)); + } +} + +export class ImmutableGetFeeInfoParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); + } +} + +export class MutableGetFeeInfoParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/results.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/results.ts new file mode 100644 index 0000000000..b12c2a0a45 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/results.ts @@ -0,0 +1,167 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ArrayOfImmutableBytes extends wasmtypes.ScProxy { + + length(): u32 { + return this.proxy.length(); + } + + getBytes(index: u32): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.index(index)); + } +} + +export class ImmutableGetAllowedStateControllerAddressesResults extends wasmtypes.ScProxy { + allowedStateControllerAddresses(): sc.ArrayOfImmutableBytes { + return new sc.ArrayOfImmutableBytes(this.proxy.root(sc.ResultAllowedStateControllerAddresses)); + } +} + +export class ArrayOfMutableBytes extends wasmtypes.ScProxy { + + appendBytes(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.append()); + } + + clear(): void { + this.proxy.clearArray(); + } + + length(): u32 { + return this.proxy.length(); + } + + getBytes(index: u32): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.index(index)); + } +} + +export class MutableGetAllowedStateControllerAddressesResults extends wasmtypes.ScProxy { + allowedStateControllerAddresses(): sc.ArrayOfMutableBytes { + return new sc.ArrayOfMutableBytes(this.proxy.root(sc.ResultAllowedStateControllerAddresses)); + } +} + +export class ImmutableGetChainInfoResults extends wasmtypes.ScProxy { + chainID(): wasmtypes.ScImmutableChainID { + return new wasmtypes.ScImmutableChainID(this.proxy.root(sc.ResultChainID)); + } + + chainOwnerID(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); + } + + defaultOwnerFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultDefaultOwnerFee)); + } + + defaultValidatorFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultDefaultValidatorFee)); + } + + description(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ResultDescription)); + } + + feeColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ResultFeeColor)); + } + + maxBlobSize(): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.root(sc.ResultMaxBlobSize)); + } + + maxEventSize(): wasmtypes.ScImmutableInt16 { + return new wasmtypes.ScImmutableInt16(this.proxy.root(sc.ResultMaxEventSize)); + } + + maxEventsPerReq(): wasmtypes.ScImmutableInt16 { + return new wasmtypes.ScImmutableInt16(this.proxy.root(sc.ResultMaxEventsPerReq)); + } +} + +export class MutableGetChainInfoResults extends wasmtypes.ScProxy { + chainID(): wasmtypes.ScMutableChainID { + return new wasmtypes.ScMutableChainID(this.proxy.root(sc.ResultChainID)); + } + + chainOwnerID(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ResultChainOwnerID)); + } + + defaultOwnerFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultDefaultOwnerFee)); + } + + defaultValidatorFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultDefaultValidatorFee)); + } + + description(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ResultDescription)); + } + + feeColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ResultFeeColor)); + } + + maxBlobSize(): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.root(sc.ResultMaxBlobSize)); + } + + maxEventSize(): wasmtypes.ScMutableInt16 { + return new wasmtypes.ScMutableInt16(this.proxy.root(sc.ResultMaxEventSize)); + } + + maxEventsPerReq(): wasmtypes.ScMutableInt16 { + return new wasmtypes.ScMutableInt16(this.proxy.root(sc.ResultMaxEventsPerReq)); + } +} + +export class ImmutableGetFeeInfoResults extends wasmtypes.ScProxy { + feeColor(): wasmtypes.ScImmutableColor { + return new wasmtypes.ScImmutableColor(this.proxy.root(sc.ResultFeeColor)); + } + + ownerFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultOwnerFee)); + } + + validatorFee(): wasmtypes.ScImmutableInt64 { + return new wasmtypes.ScImmutableInt64(this.proxy.root(sc.ResultValidatorFee)); + } +} + +export class MutableGetFeeInfoResults extends wasmtypes.ScProxy { + feeColor(): wasmtypes.ScMutableColor { + return new wasmtypes.ScMutableColor(this.proxy.root(sc.ResultFeeColor)); + } + + ownerFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultOwnerFee)); + } + + validatorFee(): wasmtypes.ScMutableInt64 { + return new wasmtypes.ScMutableInt64(this.proxy.root(sc.ResultValidatorFee)); + } +} + +export class ImmutableGetMaxBlobSizeResults extends wasmtypes.ScProxy { + maxBlobSize(): wasmtypes.ScImmutableInt32 { + return new wasmtypes.ScImmutableInt32(this.proxy.root(sc.ResultMaxBlobSize)); + } +} + +export class MutableGetMaxBlobSizeResults extends wasmtypes.ScProxy { + maxBlobSize(): wasmtypes.ScMutableInt32 { + return new wasmtypes.ScMutableInt32(this.proxy.root(sc.ResultMaxBlobSize)); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coregovernance/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coregovernance/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/coregovernance/tsconfig.json diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/consts.ts similarity index 64% rename from packages/vm/wasmlib/ts/wasmlib/coreroot/consts.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreroot/consts.ts index 8d5626b329..079f2dbd9d 100644 --- a/packages/vm/wasmlib/ts/wasmlib/coreroot/consts.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/consts.ts @@ -5,11 +5,11 @@ // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead -import * as wasmlib from "wasmlib"; +import * as wasmtypes from "wasmlib/wasmtypes"; export const ScName = "root"; export const ScDescription = "Core root contract"; -export const HScName = new wasmlib.ScHname(0xcebf5908); +export const HScName = new wasmtypes.ScHname(0xcebf5908); export const ParamDeployer = "dp"; export const ParamDescription = "ds"; @@ -27,8 +27,8 @@ export const FuncRevokeDeployPermission = "revokeDeployPermission"; export const ViewFindContract = "findContract"; export const ViewGetContractRecords = "getContractRecords"; -export const HFuncDeployContract = new wasmlib.ScHname(0x28232c27); -export const HFuncGrantDeployPermission = new wasmlib.ScHname(0xf440263a); -export const HFuncRevokeDeployPermission = new wasmlib.ScHname(0x850744f1); -export const HViewFindContract = new wasmlib.ScHname(0xc145ca00); -export const HViewGetContractRecords = new wasmlib.ScHname(0x078b3ef3); +export const HFuncDeployContract = new wasmtypes.ScHname(0x28232c27); +export const HFuncGrantDeployPermission = new wasmtypes.ScHname(0xf440263a); +export const HFuncRevokeDeployPermission = new wasmtypes.ScHname(0x850744f1); +export const HViewFindContract = new wasmtypes.ScHname(0xc145ca00); +export const HViewGetContractRecords = new wasmtypes.ScHname(0x078b3ef3); diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/contract.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/contract.ts new file mode 100644 index 0000000000..43ef9bbe84 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/contract.ts @@ -0,0 +1,68 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmlib from "wasmlib"; +import * as sc from "./index"; + +export class DeployContractCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDeployContract); + params: sc.MutableDeployContractParams = new sc.MutableDeployContractParams(wasmlib.ScView.nilProxy); +} + +export class GrantDeployPermissionCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncGrantDeployPermission); + params: sc.MutableGrantDeployPermissionParams = new sc.MutableGrantDeployPermissionParams(wasmlib.ScView.nilProxy); +} + +export class RevokeDeployPermissionCall { + func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRevokeDeployPermission); + params: sc.MutableRevokeDeployPermissionParams = new sc.MutableRevokeDeployPermissionParams(wasmlib.ScView.nilProxy); +} + +export class FindContractCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewFindContract); + params: sc.MutableFindContractParams = new sc.MutableFindContractParams(wasmlib.ScView.nilProxy); + results: sc.ImmutableFindContractResults = new sc.ImmutableFindContractResults(wasmlib.ScView.nilProxy); +} + +export class GetContractRecordsCall { + func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetContractRecords); + results: sc.ImmutableGetContractRecordsResults = new sc.ImmutableGetContractRecordsResults(wasmlib.ScView.nilProxy); +} + +export class ScFuncs { + static deployContract(_ctx: wasmlib.ScFuncCallContext): DeployContractCall { + const f = new DeployContractCall(); + f.params = new sc.MutableDeployContractParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static grantDeployPermission(_ctx: wasmlib.ScFuncCallContext): GrantDeployPermissionCall { + const f = new GrantDeployPermissionCall(); + f.params = new sc.MutableGrantDeployPermissionParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static revokeDeployPermission(_ctx: wasmlib.ScFuncCallContext): RevokeDeployPermissionCall { + const f = new RevokeDeployPermissionCall(); + f.params = new sc.MutableRevokeDeployPermissionParams(wasmlib.newCallParamsProxy(f.func)); + return f; + } + + static findContract(_ctx: wasmlib.ScViewCallContext): FindContractCall { + const f = new FindContractCall(); + f.params = new sc.MutableFindContractParams(wasmlib.newCallParamsProxy(f.func)); + f.results = new sc.ImmutableFindContractResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } + + static getContractRecords(_ctx: wasmlib.ScViewCallContext): GetContractRecordsCall { + const f = new GetContractRecordsCall(); + f.results = new sc.ImmutableGetContractRecordsResults(wasmlib.newCallResultsProxy(f.func)); + return f; + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/index.ts similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreroot/index.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/coreroot/index.ts diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/params.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/params.ts new file mode 100644 index 0000000000..3e8dfa71d3 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/params.ts @@ -0,0 +1,73 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableDeployContractParams extends wasmtypes.ScProxy { + description(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamDescription)); + } + + name(): wasmtypes.ScImmutableString { + return new wasmtypes.ScImmutableString(this.proxy.root(sc.ParamName)); + } + + programHash(): wasmtypes.ScImmutableHash { + return new wasmtypes.ScImmutableHash(this.proxy.root(sc.ParamProgramHash)); + } +} + +export class MutableDeployContractParams extends wasmtypes.ScProxy { + description(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamDescription)); + } + + name(): wasmtypes.ScMutableString { + return new wasmtypes.ScMutableString(this.proxy.root(sc.ParamName)); + } + + programHash(): wasmtypes.ScMutableHash { + return new wasmtypes.ScMutableHash(this.proxy.root(sc.ParamProgramHash)); + } +} + +export class ImmutableGrantDeployPermissionParams extends wasmtypes.ScProxy { + deployer(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamDeployer)); + } +} + +export class MutableGrantDeployPermissionParams extends wasmtypes.ScProxy { + deployer(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamDeployer)); + } +} + +export class ImmutableRevokeDeployPermissionParams extends wasmtypes.ScProxy { + deployer(): wasmtypes.ScImmutableAgentID { + return new wasmtypes.ScImmutableAgentID(this.proxy.root(sc.ParamDeployer)); + } +} + +export class MutableRevokeDeployPermissionParams extends wasmtypes.ScProxy { + deployer(): wasmtypes.ScMutableAgentID { + return new wasmtypes.ScMutableAgentID(this.proxy.root(sc.ParamDeployer)); + } +} + +export class ImmutableFindContractParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScImmutableHname { + return new wasmtypes.ScImmutableHname(this.proxy.root(sc.ParamHname)); + } +} + +export class MutableFindContractParams extends wasmtypes.ScProxy { + hname(): wasmtypes.ScMutableHname { + return new wasmtypes.ScMutableHname(this.proxy.root(sc.ParamHname)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/results.ts b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/results.ts new file mode 100644 index 0000000000..0d006dbaeb --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/results.ts @@ -0,0 +1,59 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; +import * as sc from "./index"; + +export class ImmutableFindContractResults extends wasmtypes.ScProxy { + contractFound(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultContractFound)); + } + + contractRecData(): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.root(sc.ResultContractRecData)); + } +} + +export class MutableFindContractResults extends wasmtypes.ScProxy { + contractFound(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultContractFound)); + } + + contractRecData(): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.root(sc.ResultContractRecData)); + } +} + +export class MapHnameToImmutableBytes extends wasmtypes.ScProxy { + + getBytes(key: wasmtypes.ScHname): wasmtypes.ScImmutableBytes { + return new wasmtypes.ScImmutableBytes(this.proxy.key(wasmtypes.hnameToBytes(key))); + } +} + +export class ImmutableGetContractRecordsResults extends wasmtypes.ScProxy { + contractRegistry(): sc.MapHnameToImmutableBytes { + return new sc.MapHnameToImmutableBytes(this.proxy.root(sc.ResultContractRegistry)); + } +} + +export class MapHnameToMutableBytes extends wasmtypes.ScProxy { + + clear(): void { + this.proxy.clearMap(); + } + + getBytes(key: wasmtypes.ScHname): wasmtypes.ScMutableBytes { + return new wasmtypes.ScMutableBytes(this.proxy.key(wasmtypes.hnameToBytes(key))); + } +} + +export class MutableGetContractRecordsResults extends wasmtypes.ScProxy { + contractRegistry(): sc.MapHnameToMutableBytes { + return new sc.MapHnameToMutableBytes(this.proxy.root(sc.ResultContractRegistry)); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/coreroot/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/coreroot/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/coreroot/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/coreroot/tsconfig.json diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/dict.ts b/packages/wasmvm/wasmlib/ts/wasmlib/dict.ts new file mode 100644 index 0000000000..095aa37368 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/dict.ts @@ -0,0 +1,158 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./wasmtypes" +import {log} from "./sandbox"; + +// returns a hex string representing the byte buffer +function hex(buf: u8[]): string { + const hexa = "0123456789abcdef"; + let res = ""; + for (let i = 0; i < buf.length; i++) { + const b = buf[i]; + res += hexa.charAt(b >> 4) + hexa.charAt(b & 0x0f); + } + return res; +} + +function keya(key: u8[]): string { + for (let i = 0; i < key.length; i++) { + if (key[i] == 0x23) { + return wasmtypes.stringFromBytes(key.slice(0, i + 1)) + hex(key.slice(i + 1)); + } + if (key[i] < 0x20 || key[i] > 0x7e) { + return hex(key); + } + } + return wasmtypes.stringFromBytes(key); +} + +function vala(val: u8[]): string { + return hex(val); +} + +export class ScDict implements wasmtypes.IKvStore { + dict: Map = new Map(); + + static toKey(buf: u8[]): string { + let key = ""; + for (let i = 0; i < buf.length; i++) { + key += String.fromCharCode((buf[i] >> 4) + 0x40, (buf[i] & 0x0f) + 0x40); + } + return key; + } + + static fromKey(key: string): u8[] { + let buf: u8[] = new Array(key.length / 2); + for (let i = 0; i < key.length; i += 2) { + const b1 = key.charCodeAt(i) as u8; + const b2 = key.charCodeAt(i + 1) as u8; + buf[i / 2] = (((b1 - 0x40) << 4) | (b2 - 0x40)); + } + return buf; + } + + public constructor(buf: u8[]) { + if (buf.length != 0) { + const dec = new wasmtypes.WasmDecoder(buf); + const size = wasmtypes.uint32FromBytes(dec.fixedBytes(wasmtypes.ScUint32Length)); + for (let i: u32 = 0; i < size; i++) { + const keyBuf = dec.fixedBytes(wasmtypes.ScUint16Length); + const keyLen = wasmtypes.uint16FromBytes(keyBuf); + const key = dec.fixedBytes(keyLen as u32); + const valBuf = dec.fixedBytes(wasmtypes.ScUint32Length); + const valLen = wasmtypes.uint32FromBytes(valBuf); + const val = dec.fixedBytes(valLen); + this.set(key, val); + } + } + } + + public asProxy(): wasmtypes.Proxy { + return new wasmtypes.Proxy(this); + } + + delete(key: u8[]): void { + // this.dump("delete"); + // log("dict.delete(" + keya(key) + ")"); + this.dict.delete(ScDict.toKey(key)); + // this.dump("Delete") + } + + protected dump(which: string): void { + const keys = this.dict.keys() + for (let i = 0; i < keys.length; i++) { + log("dict." + which + "." + i.toString() + "." + keya(ScDict.fromKey(keys[i])) + " = " + vala(this.dict.get(keys[i]))); + } + } + + exists(key: u8[]): bool { + const mapKey = ScDict.toKey(key); + const ret = this.dict.has(mapKey); + // this.dump("exists"); + // log("dict.exists(" + keya(key) + ") = " + ret.toString()); + return ret; + } + + get(key: u8[]): u8[] { + // this.dump("get") + const mapKey = ScDict.toKey(key); + if (!this.dict.has(mapKey)) { + // log("dict.get(" + keya(key) + ") = null"); + return []; + } + const value = this.dict.get(mapKey); + // log("dict.get(" + keya(key) + ") = " + vala(value)); + return value; + } + + public immutable(): ScImmutableDict { + return new ScImmutableDict(this); + } + + set(key: u8[], value: u8[]): void { + // this.dump("set") + // log("dict.set(" + keya(key) + ", " + vala(value) + ")"); + this.dict.set(ScDict.toKey(key), value); + // this.dump("Set") + } + + public toBytes(): u8[] { + if (this.dict.size == 0) { + return [0, 0, 0, 0]; + } + const keys = this.dict.keys().sort(); + const enc = new wasmtypes.WasmEncoder(); + enc.fixedBytes(wasmtypes.uint32ToBytes(keys.length as u32), wasmtypes.ScUint32Length); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + const key = ScDict.fromKey(k); + let val = this.dict.get(k); + enc.fixedBytes(wasmtypes.uint16ToBytes(key.length as u16), wasmtypes.ScUint16Length); + enc.fixedBytes(key, key.length as u32); + enc.fixedBytes(wasmtypes.uint32ToBytes(val.length as u32), wasmtypes.ScUint32Length); + enc.fixedBytes(val, val.length as u32); + } + return enc.buf(); + } +} + +export class ScImmutableDict { + dict: Map; + + public constructor(dict: ScDict) { + this.dict = dict.dict; + } + + exists(key: u8[]): bool { + return this.dict.has(ScDict.toKey(key)); + } + + get(key: u8[]): u8[] { + const mapKey = ScDict.toKey(key); + if (!this.dict.has(mapKey)) { + return []; + } + return this.dict.get(mapKey); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/events.ts b/packages/wasmvm/wasmlib/ts/wasmlib/events.ts new file mode 100644 index 0000000000..fce092e5cf --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/events.ts @@ -0,0 +1,25 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./wasmtypes" +import {ScFuncContext} from "./context"; + +export class EventEncoder { + event: string; + + constructor(eventName: string) { + this.event = eventName; + let timestamp = new ScFuncContext().timestamp(); + // convert nanoseconds to seconds + this.encode(wasmtypes.uint64ToString(timestamp / 1_000_000_000)); + } + + emit(): void { + new ScFuncContext().event(this.event); + } + + encode(value: string): void { + //TODO encode potential vertical bars that are present in the value string + this.event += "|" + value; + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/exports.ts b/packages/wasmvm/wasmlib/ts/wasmlib/exports.ts new file mode 100644 index 0000000000..6f12a7b96b --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/exports.ts @@ -0,0 +1,61 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// Provide host with details about funcs and views in this smart contract + +import {ScFuncContext, ScViewContext} from "./context"; +import {exportName} from "./host"; + +// Note that we do not use the Wasm export symbol table on purpose +// because Wasm does not allow us to determine whether the symbols +// are meant as view or func, or meant as extra public callbacks +// generated by the compilation of the the Wasm code. +// There are only 2 symbols the ISCP host will actually look for +// in the export table: +// on_load (which must be defined by the SC code) and +// on_call (which is defined here as part of WasmLib) + +export type ScFuncContextFunc = (f: ScFuncContext) => void; +export type ScViewContextFunc = (v: ScViewContext) => void; + +export class ScExportMap { + names: string[]; + funcs: ScFuncContextFunc[]; + views: ScViewContextFunc[]; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// context for onLoad function to be able to tell host which +// funcs and views are available as entry points to the SC +export class ScExports { + // constructs the symbol export context for the onLoad function + static export(exportMap: ScExportMap): void { + exportName(-1, "WASM::TYPESCRIPT"); + + for (let i = 0; i < exportMap.funcs.length; i++) { + exportName(i as i32, exportMap.names[i]); + } + + let offset = exportMap.funcs.length; + for (let i = 0; i < exportMap.views.length; i++) { + exportName((i as i32) | 0x8000, exportMap.names[offset + i]); + } + } + + // general entrypoint for the host to call any SC function + // the host will pass the index of one of the entry points + // that was provided by onLoad during SC initialization + static call(index: i32, exportMap: ScExportMap): void { + if ((index & 0x8000) == 0) { + // mutable full function, invoke with a func context + let func = exportMap.funcs[index]; + func(new ScFuncContext()); + return; + } + // immutable view function, invoke with a view context + let view = exportMap.views[index & 0x7fff]; + view(new ScViewContext()); + } +} + diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/host.ts b/packages/wasmvm/wasmlib/ts/wasmlib/host.ts new file mode 100644 index 0000000000..c201d39d74 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/host.ts @@ -0,0 +1,74 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./wasmtypes" + +// interface WasmLib to the VM host + +// These 2 external functions are funneling the entire WasmLib functionality +// to their counterparts on the host. + +@external("WasmLib", "hostStateGet") +export declare function hostStateGet(keyRef: usize, keyLen: i32, valRef: usize, valLen: i32): i32; + +@external("WasmLib", "hostStateSet") +export declare function hostStateSet(keyRef: usize, keyLen: i32, valRef: usize, valLen: i32): void; + +export function exportName(index: i32, name: string): void { + const buf = wasmtypes.stringToBytes(name); + hostStateSet(0, index, buf.dataStart, buf.length as i32); +} + +export function sandbox(funcNr: i32, params: u8[] | null): u8[] { + if (params === null) { + params = []; + } + // call sandbox function, result value will be cached by host + // always negative funcNr as keyLen indicates sandbox call + // this removes the need for a separate hostSandbox function + let size = hostStateGet(0, funcNr, params.dataStart, params.length as i32); + + // zero length, no need to retrieve cached value + if (size == 0) { + return []; + } + + // retrieve cached value from host + let result: u8[] = new Array(size); + hostStateGet(0, 0, result.dataStart, size); + return result; +} + +export function stateDelete(key: u8[]): void { + hostStateSet(key.dataStart, key.length as i32, 0, -1); +} + +export function stateExists(key: u8[]): bool { + return hostStateGet(key.dataStart, key.length as i32, 0, -1) >= 0; +} + +export function stateGet(key: u8[]): u8[] | null { + // variable sized result expected, + // query size first by passing zero length buffer + // value will be cached by host + let size = hostStateGet(key.dataStart, key.length as i32, 0, 0); + + // -1 means non-existent + if (size < 0) { + return null; + } + + // zero length, no need to retrieve cached value + if (size == 0) { + return []; + } + + // retrieve cached value from host + let result: u8[] = new Array(size); + hostStateGet(0, 0, result.dataStart, size); + return result; +} + +export function stateSet(key: u8[], value: u8[]): void { + hostStateSet(key.dataStart, key.length as i32, value.dataStart, value.length as i32); +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/index.ts new file mode 100644 index 0000000000..97e96f0e2b --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/index.ts @@ -0,0 +1,16 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +export * from "./assets" +export * from "./context" +export * from "./contract" +export * from "./dict" +export * from "./events" +export * from "./exports" +export * from "./host" +export * from "./sandbox" +export * from "./sandboxutils" +export * from "./state" + +export * from "./wasmrequests" +export * from "./wasmtypes" diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/package-lock.json b/packages/wasmvm/wasmlib/ts/wasmlib/package-lock.json new file mode 100644 index 0000000000..b50dee9169 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/package-lock.json @@ -0,0 +1,134 @@ +{ + "name": "wasmlib", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "wasmlib", + "version": "1.0.0", + "dependencies": { + "@assemblyscript/loader": "^0.19.22" + }, + "devDependencies": { + "assemblyscript": "^0.19.22" + } + }, + "node_modules/@assemblyscript/loader": { + "version": "0.19.22", + "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.19.22.tgz", + "integrity": "sha512-ksrMVpPOatD7ZzXCw+c/g3zId5rm8MMnQe7P32dH/qtDrgT9SbQjJYEngRP0YhRF0qrBCga2PtpID7arqphGyg==" + }, + "node_modules/assemblyscript": { + "version": "0.19.22", + "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.22.tgz", + "integrity": "sha512-+Rclbx0+BI3qAe9fjc8XGbSUDaayTtjINnD19I4MmfpT2R43c9YTQERP36676shkPxb1fisDFZeSTL65Da8Q2g==", + "dev": true, + "dependencies": { + "binaryen": "102.0.0-nightly.20211028", + "long": "^5.2.0", + "source-map-support": "^0.5.20" + }, + "bin": { + "asc": "bin/asc", + "asinit": "bin/asinit" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/assemblyscript" + } + }, + "node_modules/binaryen": { + "version": "102.0.0-nightly.20211028", + "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz", + "integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==", + "dev": true, + "bin": { + "wasm-opt": "bin/wasm-opt" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/long": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.0.tgz", + "integrity": "sha512-9RTUNjK60eJbx3uz+TEGF7fUr29ZDxR5QzXcyDpeSfeH28S9ycINflOgOlppit5U+4kNTe83KQnMEerw7GmE8w==", + "dev": true + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + } + }, + "dependencies": { + "@assemblyscript/loader": { + "version": "0.19.22", + "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.19.22.tgz", + "integrity": "sha512-ksrMVpPOatD7ZzXCw+c/g3zId5rm8MMnQe7P32dH/qtDrgT9SbQjJYEngRP0YhRF0qrBCga2PtpID7arqphGyg==" + }, + "assemblyscript": { + "version": "0.19.22", + "resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.22.tgz", + "integrity": "sha512-+Rclbx0+BI3qAe9fjc8XGbSUDaayTtjINnD19I4MmfpT2R43c9YTQERP36676shkPxb1fisDFZeSTL65Da8Q2g==", + "dev": true, + "requires": { + "binaryen": "102.0.0-nightly.20211028", + "long": "^5.2.0", + "source-map-support": "^0.5.20" + } + }, + "binaryen": { + "version": "102.0.0-nightly.20211028", + "resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz", + "integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==", + "dev": true + }, + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "long": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.0.tgz", + "integrity": "sha512-9RTUNjK60eJbx3uz+TEGF7fUr29ZDxR5QzXcyDpeSfeH28S9ycINflOgOlppit5U+4kNTe83KQnMEerw7GmE8w==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + } + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/package.json b/packages/wasmvm/wasmlib/ts/wasmlib/package.json similarity index 71% rename from packages/vm/wasmlib/ts/wasmlib/package.json rename to packages/wasmvm/wasmlib/ts/wasmlib/package.json index b3d0b9c01d..aee97e6323 100644 --- a/packages/vm/wasmlib/ts/wasmlib/package.json +++ b/packages/wasmvm/wasmlib/ts/wasmlib/package.json @@ -4,9 +4,9 @@ "version": "1.0.0", "author": "Eric Hop", "dependencies": { - "@assemblyscript/loader": "^0.19.18" + "@assemblyscript/loader": "^0.19.22" }, "devDependencies": { - "assemblyscript": "^0.19.18" + "assemblyscript": "^0.19.22" } } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts b/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts new file mode 100644 index 0000000000..d014a69534 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts @@ -0,0 +1,290 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmrequests from "./wasmrequests" +import * as wasmtypes from "./wasmtypes" +import {ScAssets, ScBalances, ScTransfers} from "./assets"; +import {ScDict, ScImmutableDict} from "./dict"; +import {sandbox} from "./host"; +import {ScSandboxUtils} from "./sandboxutils"; +import {ScImmutableState, ScState} from "./state"; + +// @formatter:off +export const FnAccountID : i32 = -1; +export const FnBalance : i32 = -2; +export const FnBalances : i32 = -3; +export const FnBlockContext : i32 = -4; +export const FnCall : i32 = -5; +export const FnCaller : i32 = -6; +export const FnChainID : i32 = -7; +export const FnChainOwnerID : i32 = -8; +export const FnContract : i32 = -9; +export const FnContractCreator : i32 = -10; +export const FnDeployContract : i32 = -11; +export const FnEntropy : i32 = -12; +export const FnEvent : i32 = -13; +export const FnIncomingTransfer : i32 = -14; +export const FnLog : i32 = -15; +export const FnMinted : i32 = -16; +export const FnPanic : i32 = -17; +export const FnParams : i32 = -18; +export const FnPost : i32 = -19; +export const FnRequest : i32 = -20; +export const FnRequestID : i32 = -21; +export const FnResults : i32 = -22; +export const FnSend : i32 = -23; +export const FnStateAnchor : i32 = -24; +export const FnTimestamp : i32 = -25; +export const FnTrace : i32 = -26; +export const FnUtilsBase58Decode : i32 = -27; +export const FnUtilsBase58Encode : i32 = -28; +export const FnUtilsBlsAddress : i32 = -29; +export const FnUtilsBlsAggregate : i32 = -30; +export const FnUtilsBlsValid : i32 = -31; +export const FnUtilsEd25519Address : i32 = -32; +export const FnUtilsEd25519Valid : i32 = -33; +export const FnUtilsHashBlake2b : i32 = -34; +export const FnUtilsHashName : i32 = -35; +export const FnUtilsHashSha3 : i32 = -36; +// @formatter:on + +// Direct logging of text to host log +export function log(text: string): void { + sandbox(FnLog, wasmtypes.stringToBytes(text)); +} + +// Direct logging of error to host log, followed by panicking out of the Wasm code +export function panic(text: string): void { + sandbox(FnPanic, wasmtypes.stringToBytes(text)); +} + +// Direct conditional logging of debug-level informational text to host log +export function trace(text: string): void { + sandbox(FnTrace, wasmtypes.stringToBytes(text)); +} + +export function paramsProxy(): wasmtypes.Proxy { + return new ScDict(sandbox(FnParams, null)).asProxy(); +} + +export class ScSandbox { + // retrieve the agent id of this contract account + public accountID(): wasmtypes.ScAgentID { + return wasmtypes.agentIDFromBytes(sandbox(FnAccountID, null)); + } + + public balance(color: wasmtypes.ScColor): u64 { + return wasmtypes.uint64FromBytes(sandbox(FnBalance, color.toBytes())); + } + + // access the current balances for all assets + public balances(): ScBalances { + return new ScAssets(sandbox(FnBalances, null)).balances(); + } + + // calls a smart contract function + protected callWithTransfer(hContract: wasmtypes.ScHname, hFunction: wasmtypes.ScHname, params: ScDict | null, transfer: ScTransfers | null): ScImmutableDict { + if (params === null) { + params = new ScDict([]); + } + if (transfer === null) { + transfer = new ScTransfers(); + } + const req = new wasmrequests.CallRequest(); + req.contract = hContract; + req.function = hFunction; + req.params = params.toBytes(); + req.transfer = transfer.toBytes(); + const res = sandbox(FnCall, req.bytes()); + return new ScDict(res).immutable(); + } + + // retrieve the chain id of the chain this contract lives on + public chainID(): wasmtypes.ScChainID { + return wasmtypes.chainIDFromBytes(sandbox(FnChainID, null)); + } + + // retrieve the agent id of the owner of the chain this contract lives on + public chainOwnerID(): wasmtypes.ScAgentID { + return wasmtypes.agentIDFromBytes(sandbox(FnChainOwnerID, null)); + } + + // retrieve the hname of this contract + public contract(): wasmtypes.ScHname { + return wasmtypes.hnameFromBytes(sandbox(FnContract, null)); + } + + // retrieve the agent id of the creator of this contract + public contractCreator(): wasmtypes.ScAgentID { + return wasmtypes.agentIDFromBytes(sandbox(FnContractCreator, null)); + } + + // logs informational text message + public log(text: string): void { + sandbox(FnLog, wasmtypes.stringToBytes(text)); + } + + // logs error text message and then panics + public panic(text: string): void { + sandbox(FnPanic, wasmtypes.stringToBytes(text)); + } + + // retrieve parameters passed to the smart contract function that was called + public params(): ScImmutableDict { + return new ScDict(sandbox(FnParams, null)).immutable(); + } + + // panics if condition is not satisfied + public require(cond: bool, msg: string): void { + if (!cond) { + this.panic(msg); + } + } + + public results(results: ScDict): void { + sandbox(FnResults, results.toBytes()); + } + + // deterministic time stamp fixed at the moment of calling the smart contract + public timestamp(): u64 { + return wasmtypes.uint64FromBytes(sandbox(FnTimestamp, null)); + } + + // logs debugging trace text message + public trace(text: string): void { + sandbox(FnTrace, wasmtypes.stringToBytes(text)); + } + + // access diverse utility functions + public utility(): ScSandboxUtils { + return new ScSandboxUtils(); + } +} + +export class ScSandboxView extends ScSandbox { + // calls a smart contract view + public call(hContract: wasmtypes.ScHname, hFunction: wasmtypes.ScHname, params: ScDict | null): ScImmutableDict { + return this.callWithTransfer(hContract, hFunction, params, null); + } + + public rawState(): ScImmutableState { + return new ScImmutableState(); + } +} + +export class ScSandboxFunc extends ScSandbox { + private static entropy: u8[] = []; + private static offset: u32 = 0; + + //public blockContext(construct func(sandbox: ScSandbox) interface{}, onClose func(interface{})): interface{} { + // panic("implement me") + //} + + // calls a smart contract function + public call(hContract: wasmtypes.ScHname, hFunction: wasmtypes.ScHname, params: ScDict | null, transfer: ScTransfers | null): ScImmutableDict { + return this.callWithTransfer(hContract, hFunction, params, transfer); + } + + // retrieve the agent id of the caller of the smart contract + public caller(): wasmtypes.ScAgentID { + return wasmtypes.agentIDFromBytes(sandbox(FnCaller, null)); + } + + // deploys a smart contract + public deployContract(programHash: wasmtypes.ScHash, name: string, description: string, initParams: ScDict | null): void { + if (initParams === null) { + initParams = new ScDict([]); + } + const req = new wasmrequests.DeployRequest(); + req.progHash = programHash; + req.name = name; + req.description = description; + req.params = initParams.toBytes(); + sandbox(FnDeployContract, req.bytes()); + } + + // returns random entropy data for current request. + public entropy(): wasmtypes.ScHash { + return wasmtypes.hashFromBytes(sandbox(FnEntropy, null)); + } + + // signals an event on the node that external entities can subscribe to + public event(msg: string): void { + sandbox(FnEvent, wasmtypes.stringToBytes(msg)); + } + + // access the incoming balances for all assets + public incomingTransfer(): ScBalances { + const buf = sandbox(FnIncomingTransfer, null); + return new ScAssets(buf).balances(); + } + + // retrieve the assets that were minted in this transaction + public minted(): ScBalances { + return new ScAssets(sandbox(FnMinted, null)).balances(); + } + + // (delayed) posts a smart contract function request + public post(chainID: wasmtypes.ScChainID, hContract: wasmtypes.ScHname, hFunction: wasmtypes.ScHname, params: ScDict, transfer: ScTransfers, delay: u32): void { + const req = new wasmrequests.PostRequest(); + req.chainID = chainID; + req.contract = hContract; + req.function = hFunction; + req.params = params.toBytes(); + req.transfer = transfer.toBytes(); + req.delay = delay; + sandbox(FnPost, req.bytes()); + } + + // generates a random value from 0 to max (exclusive: max) using a deterministic RNG + public random(max: u64): u64 { + if (max == 0) { + this.panic("random: max parameter should be non-zero"); + } + + // note that entropy gets reset for every request + if (ScSandboxFunc.entropy.length == 0) { + // first time in this: request, initialize with current request entropy + ScSandboxFunc.entropy = this.entropy().toBytes(); + ScSandboxFunc.offset = 0; + } + if (ScSandboxFunc.offset == 32) { + // ran out of entropy: data, hash entropy for next pseudo-random entropy + ScSandboxFunc.entropy = this.utility().hashBlake2b(ScSandboxFunc.entropy).toBytes(); + ScSandboxFunc.offset = 0; + } + let rnd = wasmtypes.uint64FromBytes(ScSandboxFunc.entropy.slice(ScSandboxFunc.offset, ScSandboxFunc.offset + 8)) % max; + ScSandboxFunc.offset += 8; + return rnd; + } + + public rawState(): ScState { + return new ScState(); + } + + //public request(): ScRequest { + // panic("implement me") + //} + + // retrieve the request id of this transaction + public requestID(): wasmtypes.ScRequestID { + return wasmtypes.requestIDFromBytes(sandbox(FnRequestID, null)); + } + + // transfer assets to the specified Tangle ledger address + public send(address: wasmtypes.ScAddress, transfer: ScTransfers): void { + // we need some assets to send + if (transfer.isEmpty()) { + return; + } + + const req = new wasmrequests.SendRequest(); + req.address = address; + req.transfer = transfer.toBytes(); + sandbox(FnSend, req.bytes()); + } + + //public stateAnchor(): interface{} { + // panic("implement me") + //} +} \ No newline at end of file diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/sandboxutils.ts b/packages/wasmvm/wasmlib/ts/wasmlib/sandboxutils.ts new file mode 100644 index 0000000000..038f7ae009 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/sandboxutils.ts @@ -0,0 +1,66 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as util from "./sandbox"; +import * as wasmtypes from "./wasmtypes" +import {sandbox} from "./host"; + +export class ScSandboxUtils { + // decodes the specified base58-encoded string value to its original bytes + public base58Decode(value: string): u8[] { + return sandbox(util.FnUtilsBase58Decode, wasmtypes.stringToBytes(value)); + } + + // encodes the specified bytes to a base-58-encoded string + public base58Encode(bytes: u8[]): string { + return wasmtypes.bytesToString(sandbox(util.FnUtilsBase58Encode, bytes)); + } + + public blsAddressFromPubKey(pubKey: u8[]): wasmtypes.ScAddress { + return wasmtypes.addressFromBytes(sandbox(util.FnUtilsBlsAddress, pubKey)); + } + + public blsAggregateSignatures(pubKeys: u8[][], sigs: u8[][]): u8[][] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint32Encode(enc, pubKeys.length as u32); + for (let i = 0; i < pubKeys.length; i++) { + enc.bytes(pubKeys[i]); + } + wasmtypes.uint32Encode(enc, sigs.length as u32); + for (let i = 0; i < sigs.length; i++) { + enc.bytes(sigs[i]); + } + const result = sandbox(util.FnUtilsBlsAggregate, enc.buf()); + const decode = new wasmtypes.WasmDecoder(result); + return [decode.bytes(), decode.bytes()]; + } + + public blsValidSignature(data: u8[], pubKey: u8[], signature: u8[]): bool { + const enc = new wasmtypes.WasmEncoder().bytes(data).bytes(pubKey).bytes(signature); + return wasmtypes.boolFromBytes(sandbox(util.FnUtilsBlsValid, enc.buf())); + } + + public ed25519AddressFromPubKey(pubKey: u8[]): wasmtypes.ScAddress { + return wasmtypes.addressFromBytes(sandbox(util.FnUtilsEd25519Address, pubKey)); + } + + public ed25519ValidSignature(data: u8[], pubKey: u8[], signature: u8[]): bool { + const enc = new wasmtypes.WasmEncoder().bytes(data).bytes(pubKey).bytes(signature); + return wasmtypes.boolFromBytes(sandbox(util.FnUtilsEd25519Valid, enc.buf())); + } + + // hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash + public hashBlake2b(value: u8[]): wasmtypes.ScHash { + return wasmtypes.hashFromBytes(sandbox(util.FnUtilsHashBlake2b, value)); + } + + // hashes the specified value bytes using sha3 hashing and returns the resulting 32-byte hash + public hashSha3(value: u8[]): wasmtypes.ScHash { + return wasmtypes.hashFromBytes(sandbox(util.FnUtilsHashSha3, value)); + } + + // hashes the specified value bytes using blake2b hashing and returns the resulting 32-byte hash + public hname(value: string): wasmtypes.ScHname { + return wasmtypes.hnameFromBytes(sandbox(util.FnUtilsHashName, wasmtypes.stringToBytes(value))); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/state.ts b/packages/wasmvm/wasmlib/ts/wasmlib/state.ts new file mode 100644 index 0000000000..121619fa3b --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/state.ts @@ -0,0 +1,44 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./wasmtypes" +import {IKvStore} from "./wasmtypes" +import {stateDelete, stateExists, stateGet, stateSet} from "./host"; + +export class ScImmutableState { + exists(key: u8[]): bool { + return stateExists(key); + } + + get(key: u8[]): u8[] { + const val = stateGet(key); + return val === null ? [] : val; + } +} + +export class ScState implements IKvStore { + public static proxy(): wasmtypes.Proxy { + return new wasmtypes.Proxy(new ScState()); + } + + delete(key: u8[]): void { + stateDelete(key); + } + + exists(key: u8[]): bool { + return stateExists(key); + } + + get(key: u8[]): u8[] { + const val = stateGet(key); + return val === null ? [] : val; + } + + public immutable(): ScImmutableState { + return this; + } + + set(key: u8[], value: u8[]): void { + stateSet(key, value); + } +} diff --git a/packages/vm/wasmlib/ts/wasmlib/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/tsconfig.json similarity index 100% rename from packages/vm/wasmlib/ts/wasmlib/tsconfig.json rename to packages/wasmvm/wasmlib/ts/wasmlib/tsconfig.json diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/consts.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/consts.ts new file mode 100644 index 0000000000..2533b5bc75 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/consts.ts @@ -0,0 +1,12 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; + +export const ScName = "requests"; +export const ScDescription = "WasmLib request structures"; +export const HScName = new wasmtypes.ScHname(0x98e19453); diff --git a/contracts/wasm/helloworld/ts/helloworld/keys.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/contract.ts similarity index 60% rename from contracts/wasm/helloworld/ts/helloworld/keys.ts rename to packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/contract.ts index 7fb73b33ec..227f20d89d 100644 --- a/contracts/wasm/helloworld/ts/helloworld/keys.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/contract.ts @@ -8,12 +8,5 @@ import * as wasmlib from "wasmlib"; import * as sc from "./index"; - -export const IdxResultHelloWorld = 0; - - -export let keyMap: string[] = [ - sc.ResultHelloWorld, -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); +export class ScFuncs { +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/index.ts new file mode 100644 index 0000000000..d057bb4090 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/index.ts @@ -0,0 +1,10 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +export * from "./consts"; +export * from "./contract"; +export * from "./structs"; diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts new file mode 100644 index 0000000000..e34ebc677a --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts @@ -0,0 +1,290 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +// (Re-)generated by schema tool +// >>>> DO NOT CHANGE THIS FILE! <<<< +// Change the json schema instead + +import * as wasmtypes from "wasmlib/wasmtypes"; + +export class CallRequest { + contract : wasmtypes.ScHname = new wasmtypes.ScHname(0); + function : wasmtypes.ScHname = new wasmtypes.ScHname(0); + params : u8[] = []; + transfer : u8[] = []; + + static fromBytes(buf: u8[]): CallRequest { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new CallRequest(); + data.contract = wasmtypes.hnameDecode(dec); + data.function = wasmtypes.hnameDecode(dec); + data.params = wasmtypes.bytesDecode(dec); + data.transfer = wasmtypes.bytesDecode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.hnameEncode(enc, this.contract); + wasmtypes.hnameEncode(enc, this.function); + wasmtypes.bytesEncode(enc, this.params); + wasmtypes.bytesEncode(enc, this.transfer); + return enc.buf(); + } +} + +export class ImmutableCallRequest extends wasmtypes.ScProxy { + + exists(): bool { + return this.proxy.exists(); + } + + value(): CallRequest { + return CallRequest.fromBytes(this.proxy.get()); + } +} + +export class MutableCallRequest extends wasmtypes.ScProxy { + + delete(): void { + this.proxy.delete(); + } + + exists(): bool { + return this.proxy.exists(); + } + + setValue(value: CallRequest): void { + this.proxy.set(value.bytes()); + } + + value(): CallRequest { + return CallRequest.fromBytes(this.proxy.get()); + } +} + +export class DeployRequest { + description : string = ""; + name : string = ""; + params : u8[] = []; + progHash : wasmtypes.ScHash = new wasmtypes.ScHash(); + + static fromBytes(buf: u8[]): DeployRequest { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new DeployRequest(); + data.description = wasmtypes.stringDecode(dec); + data.name = wasmtypes.stringDecode(dec); + data.params = wasmtypes.bytesDecode(dec); + data.progHash = wasmtypes.hashDecode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.stringEncode(enc, this.description); + wasmtypes.stringEncode(enc, this.name); + wasmtypes.bytesEncode(enc, this.params); + wasmtypes.hashEncode(enc, this.progHash); + return enc.buf(); + } +} + +export class ImmutableDeployRequest extends wasmtypes.ScProxy { + + exists(): bool { + return this.proxy.exists(); + } + + value(): DeployRequest { + return DeployRequest.fromBytes(this.proxy.get()); + } +} + +export class MutableDeployRequest extends wasmtypes.ScProxy { + + delete(): void { + this.proxy.delete(); + } + + exists(): bool { + return this.proxy.exists(); + } + + setValue(value: DeployRequest): void { + this.proxy.set(value.bytes()); + } + + value(): DeployRequest { + return DeployRequest.fromBytes(this.proxy.get()); + } +} + +export class PostRequest { + chainID : wasmtypes.ScChainID = new wasmtypes.ScChainID(); + contract : wasmtypes.ScHname = new wasmtypes.ScHname(0); + delay : u32 = 0; + function : wasmtypes.ScHname = new wasmtypes.ScHname(0); + params : u8[] = []; + transfer : u8[] = []; + + static fromBytes(buf: u8[]): PostRequest { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new PostRequest(); + data.chainID = wasmtypes.chainIDDecode(dec); + data.contract = wasmtypes.hnameDecode(dec); + data.delay = wasmtypes.uint32Decode(dec); + data.function = wasmtypes.hnameDecode(dec); + data.params = wasmtypes.bytesDecode(dec); + data.transfer = wasmtypes.bytesDecode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.chainIDEncode(enc, this.chainID); + wasmtypes.hnameEncode(enc, this.contract); + wasmtypes.uint32Encode(enc, this.delay); + wasmtypes.hnameEncode(enc, this.function); + wasmtypes.bytesEncode(enc, this.params); + wasmtypes.bytesEncode(enc, this.transfer); + return enc.buf(); + } +} + +export class ImmutablePostRequest extends wasmtypes.ScProxy { + + exists(): bool { + return this.proxy.exists(); + } + + value(): PostRequest { + return PostRequest.fromBytes(this.proxy.get()); + } +} + +export class MutablePostRequest extends wasmtypes.ScProxy { + + delete(): void { + this.proxy.delete(); + } + + exists(): bool { + return this.proxy.exists(); + } + + setValue(value: PostRequest): void { + this.proxy.set(value.bytes()); + } + + value(): PostRequest { + return PostRequest.fromBytes(this.proxy.get()); + } +} + +export class SendRequest { + address : wasmtypes.ScAddress = new wasmtypes.ScAddress(); + transfer : u8[] = []; + + static fromBytes(buf: u8[]): SendRequest { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new SendRequest(); + data.address = wasmtypes.addressDecode(dec); + data.transfer = wasmtypes.bytesDecode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.addressEncode(enc, this.address); + wasmtypes.bytesEncode(enc, this.transfer); + return enc.buf(); + } +} + +export class ImmutableSendRequest extends wasmtypes.ScProxy { + + exists(): bool { + return this.proxy.exists(); + } + + value(): SendRequest { + return SendRequest.fromBytes(this.proxy.get()); + } +} + +export class MutableSendRequest extends wasmtypes.ScProxy { + + delete(): void { + this.proxy.delete(); + } + + exists(): bool { + return this.proxy.exists(); + } + + setValue(value: SendRequest): void { + this.proxy.set(value.bytes()); + } + + value(): SendRequest { + return SendRequest.fromBytes(this.proxy.get()); + } +} + +export class TransferRequest { + agentID : wasmtypes.ScAgentID = wasmtypes.agentIDFromBytes([]); + create : bool = false; + transfer : u8[] = []; + + static fromBytes(buf: u8[]): TransferRequest { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new TransferRequest(); + data.agentID = wasmtypes.agentIDDecode(dec); + data.create = wasmtypes.boolDecode(dec); + data.transfer = wasmtypes.bytesDecode(dec); + dec.close(); + return data; + } + + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); + wasmtypes.agentIDEncode(enc, this.agentID); + wasmtypes.boolEncode(enc, this.create); + wasmtypes.bytesEncode(enc, this.transfer); + return enc.buf(); + } +} + +export class ImmutableTransferRequest extends wasmtypes.ScProxy { + + exists(): bool { + return this.proxy.exists(); + } + + value(): TransferRequest { + return TransferRequest.fromBytes(this.proxy.get()); + } +} + +export class MutableTransferRequest extends wasmtypes.ScProxy { + + delete(): void { + this.proxy.delete(); + } + + exists(): bool { + return this.proxy.exists(); + } + + setValue(value: TransferRequest): void { + this.proxy.set(value.bytes()); + } + + value(): TransferRequest { + return TransferRequest.fromBytes(this.proxy.get()); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/tsconfig.json new file mode 100644 index 0000000000..6fb4265c72 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "assemblyscript/std/assembly.json", + "include": ["./*.ts"] +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts new file mode 100644 index 0000000000..b3df713fe0 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts @@ -0,0 +1,218 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {sandbox} from "../host"; +import {FnUtilsBase58Encode, panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// WasmDecoder decodes separate entities from a byte buffer +export class WasmDecoder { + buf: u8[]; + + constructor(buf: u8[]) { + if (buf.length == 0) { + panic("empty decode buffer"); + } + this.buf = buf; + } + + // decodes the next byte from the byte buffer + byte(): u8 { + if (this.buf.length == 0) { + panic("insufficient bytes"); + } + const value = this.buf[0]; + this.buf = this.buf.slice(1); + return value; + } + + // decodes the next variable sized slice of bytes from the byte buffer + bytes(): u8[] { + const length = this.vluDecode(32) as u32; + return this.fixedBytes(length); + } + + // finalizes decoding by panicking if any bytes remain in the byte buffer + close(): void { + if (this.buf.length != 0) { + panic("extra bytes"); + } + } + + // decodes the next fixed size slice of bytes from the byte buffer + fixedBytes(size: u32): u8[] { + if ((this.buf.length as u32) < size) { + panic("insufficient fixed bytes"); + } + let value = this.buf.slice(0, size); + this.buf = this.buf.slice(size); + return value; + } + + // peeks at the next byte in the byte buffer + peek(): u8 { + if (this.buf.length == 0) { + panic("insufficient peek bytes"); + } + return this.buf[0]; + } + + // Variable Length Integer decoder, uses modified LEB128 + vliDecode(bits: i32): i64 { + let b = this.byte(); + const sign = b & 0x40; + + // first group of 6 bits + let value = (b & 0x3f) as i64; + let s = 6; + + // while continuation bit is set + for (; (b & 0x80) != 0; s += 7) { + if (s >= bits) { + panic("integer representation too long"); + } + + // next group of 7 bits + b = this.byte(); + value |= ((b & 0x7f) as i64) << s; + } + + if (sign == 0) { + // positive, sign bits are already zero + return value; + } + + // negative, extend sign bits + return value | ((-1 as i64) << s); + } + + // Variable Length Unsigned decoder, uses ULEB128 + vluDecode(bits: i32): u64 { + // first group of 7 bits + let b = this.byte(); + let value = (b & 0x7f) as u64; + let s = 7; + + // while continuation bit is set + for (; (b & 0x80) != 0; s += 7) { + if (s >= bits) { + panic("integer representation too long"); + } + + // next group of 7 bits + b = this.byte(); + value |= ((b & 0x7f) as u64) << s; + } + + return value; + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// WasmEncoder encodes separate entities into a byte buffer +export class WasmEncoder { + data: u8[]; + + // constructs an encoder + constructor() { + this.data = []; + } + + // retrieves the encoded byte buffer + buf(): u8[] { + return this.data; + } + + // encodes a single byte into the byte buffer + byte(value: u8): wasmtypes.WasmEncoder { + this.data.push(value); + return this; + } + + // encodes a variable sized slice of bytes into the byte buffer + bytes(value: u8[]): wasmtypes.WasmEncoder { + const length = value.length; + this.vluEncode(length as u64); + return this.fixedBytes(value, length as u32); + } + + // encodes a fixed size slice of bytes into the byte buffer + fixedBytes(value: u8[], length: u32): wasmtypes.WasmEncoder { + if ((value.length as u32) != length) { + panic("invalid fixed bytes length"); + } + this.data = this.data.concat(value); + return this; + } + + // Variable Length Integer encoder, uses modified LEB128 + vliEncode(value: i64): wasmtypes.WasmEncoder { + // bit 7 is always continuation bit + + // first group: 6 bits of data plus sign bit + // bit 6 encodes 0 as positive and 1 as negative + let b = (value as u8) & 0x3f; + value >>= 6; + + let finalValue: i64 = 0; + if (value < 0) { + // 1st byte encodes 1 as negative in bit 6 + b |= 0x40; + // negative value, start with all high bits set to 1 + finalValue = -1; + } + + // keep shifting until all bits are done + while (value != finalValue) { + // emit with continuation bit + this.data.push(b | 0x80); + + // next group of 7 data bits + b = (value as u8) & 0x7f; + value >>= 7; + } + + // emit without continuation bit to signal end + this.data.push(b); + return this; + } + + // Variable Length Unsigned encoder, uses ULEB128 + vluEncode(value: u64): wasmtypes.WasmEncoder { + // bit 7 is always continuation bit + + // first group of 7 data bits + let b = (value as u8) & 0x7f; + value >>= 7; + + // keep shifting until all bits are done + while (value != 0) { + // emit with continuation bit + this.data.push(b | 0x80); + + // next group of 7 data bits + b = (value as u8) & 0x7f; + value >>= 7; + } + + // emit without continuation bit to signal end + this.data.push(b); + return this; + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// wrapper for simplified use by hashtypes +export function base58Encode(buf: u8[]): string { + return wasmtypes.stringFromBytes(sandbox(FnUtilsBase58Encode, buf)); +} + +export function zeroes(count: u32): u8[] { + let buf: u8[] = new Array(count); + buf.fill(0); + return buf; +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/index.ts new file mode 100644 index 0000000000..0efea2b74e --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/index.ts @@ -0,0 +1,24 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +export * from "./codec" +export * from "./proxy" + +export * from "./scaddress" +export * from "./scagentid" +export * from "./scbool" +export * from "./scbytes" +export * from "./scchainid" +export * from "./sccolor" +export * from "./schash" +export * from "./schname" +export * from "./scint8" +export * from "./scint16" +export * from "./scint32" +export * from "./scint64" +export * from "./screquestid" +export * from "./scstring" +export * from "./scuint8" +export * from "./scuint16" +export * from "./scuint32" +export * from "./scuint64" diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/package.json b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/package.json new file mode 100644 index 0000000000..6261945296 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/package.json @@ -0,0 +1,12 @@ +{ + "name": "wasmtypes", + "description": "WasmTypes, interface library for ISCP Wasm VM", + "version": "1.0.0", + "author": "Eric Hop", + "dependencies": { + "@assemblyscript/loader": "^0.19.22" + }, + "devDependencies": { + "assemblyscript": "^0.19.22" + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts new file mode 100644 index 0000000000..cb40039708 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts @@ -0,0 +1,150 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index" + +export interface IKvStore { + delete(key: u8[]): void; + + exists(key: u8[]): bool; + + get(key: u8[]): u8[]; + + set(key: u8[], value: u8[]): void; +} + +export class ScProxy { + protected proxy: Proxy; + + public constructor(proxy: Proxy) { + this.proxy = proxy; + } +} + +export class Proxy { + _key: u8[] = []; + kvStore: IKvStore; + + constructor(kvStore: IKvStore) { + this.kvStore = kvStore; + } + + // alternative constructor + protected proxy(kvStore: IKvStore, key: u8[]): Proxy { + const res = new Proxy(kvStore); + res._key = key; + return res; + } + + // Append returns a Proxy for a newly appended null element + // Note that this will essentially return the element at Length() + public append(): Proxy { + const length = this.length(); + this.expand(length + 1); + return this.element(length); + } + + // ClearArray clears an array by deleting all elements + // TODO Note that this does not delete recursive container elements + public clearArray(): void { + for (let length = this.length(); length != 0; length--) { + this.element(length - 1).delete(); + } + + // clear the length counter + this.delete(); + } + + // ClearMap clears a map by deleting all elements + // TODO Note that this does not delete recursive container elements + public clearMap(): void { + // TODO clear prefix + + // clear the length counter + this.delete(); + } + + delete(): void { + //log(this.id.toString() + ".delete(" + keya(this._key) + ")"); + this.kvStore.delete(this._key); + } + + protected element(index: u32): Proxy { + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint32Encode(enc, index); + // 0x23 is '#' + return this.sub(0x23, enc.buf()); + } + + exists(): bool { + //log(this.id.toString() + ".exists(" + keya(this._key) + ")"); + return this.kvStore.exists(this._key); + } + + //TODO have a Grow function that grows an array? + protected expand(length: u32): void { + // update the length counter + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint32Encode(enc, length); + this.set(enc.buf()); + } + + get(): u8[] { + const buf = this.kvStore.get(this._key); + //log(this.id.toString() + ".get(" + keya(this._key) + ") = " + vala(buf)); + return buf; + } + + // Index gets a Proxy for an element of an Array by its index + public index(index: u32): Proxy { + const size = this.length(); + if (index >= size) { + if (index == size) { + panic("invalid index: use append"); + } + panic("invalid index"); + } + return this.element(index); + } + + // Key gets a Proxy for an element of a Map by its key + public key(key: u8[]): Proxy { + // 0x2e is '.' + return this.sub(0x2e, key); + } + + // Length returns the number of elements in an Array + // Never try to access an index >= Length() + public length(): u32 { + // get the length counter + let buf = this.get(); + if (buf.length == 0) { + return 0; + } + const dec = new wasmtypes.WasmDecoder(buf) + return wasmtypes.uint32Decode(dec); + } + + // Root returns a Proxy for an element of a root container (Params/Results/State). + // The key is always a string. + public root(key: string): Proxy { + return this.proxy(this.kvStore, wasmtypes.stringToBytes(key)); + } + + set(value: u8[]): void { + //log(this.id.toString() + ".set(" + keya(this._key) + ") = " + vala(value)); + this.kvStore.set(this._key, value); + } + + // sub returns a proxy for an element of a container. + // The separator is significant, it prevents potential clashes with other elements. + // Different separators can be used to indicate different sub-containers + protected sub(sep: u8, key: u8[]): Proxy { + if (this._key.length == 0) { + // this must be a root proxy + return this.proxy(this.kvStore, key.slice(0)); + } + return this.proxy(this.kvStore, this._key.concat([sep]).concat(key)); + } +} \ No newline at end of file diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts new file mode 100644 index 0000000000..aa79518419 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts @@ -0,0 +1,108 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index" + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScAddressAlias : u8 = 2; +export const ScAddressEd25519: u8 = 0; +export const ScAddressNFT : u8 = 1; + +export const ScAddressLength = 33; + +export class ScAddress { + id: u8[] = wasmtypes.zeroes(ScAddressLength); + + asAgentID(): wasmtypes.ScAgentID { + // agentID for address has Hname zero + return new wasmtypes.ScAgentID(this, new wasmtypes.ScHname(0)); + } + + public equals(other: ScAddress): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return addressToBytes(this); + } + + // human-readable string representation + public toString(): string { + return addressToString(this); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function addressDecode(dec: wasmtypes.WasmDecoder): ScAddress { + return addressFromBytesUnchecked(dec.fixedBytes(ScAddressLength)) +} + +export function addressEncode(enc: wasmtypes.WasmEncoder, value: ScAddress): void { + enc.fixedBytes(value.toBytes(), ScAddressLength) +} + +export function addressFromBytes(buf: u8[]): ScAddress { + if (buf.length == 0) { + return new ScAddress(); + } + if (buf.length != ScAddressLength) { + panic("invalid Address length"); + } + if (buf[0] > ScAddressAlias) { + panic("invalid Address: address type > 2"); + } + return addressFromBytesUnchecked(buf); +} + +export function addressToBytes(value: ScAddress): u8[] { + return value.id; +} + +export function addressToString(value: ScAddress): string { + // TODO standardize human readable string + return wasmtypes.base58Encode(value.id); +} + +function addressFromBytesUnchecked(buf: u8[]): ScAddress { + let o = new ScAddress(); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableAddress { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return addressToString(this.value()); + } + + value(): ScAddress { + return addressFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableAddress extends ScImmutableAddress { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScAddress): void { + this.proxy.set(addressToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts new file mode 100644 index 0000000000..3d86126e97 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts @@ -0,0 +1,117 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index" + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScAgentIDLength = 37; + +export class ScAgentID { + _address: wasmtypes.ScAddress; + _hname: wasmtypes.ScHname; + + constructor(address: wasmtypes.ScAddress, hname: wasmtypes.ScHname) { + this._address = address; + this._hname = hname; + } + + public equals(other: ScAgentID): bool { + return this._address.equals(other._address) && + this._hname.equals(other._hname); + } + + public address(): wasmtypes.ScAddress { + return this._address; + } + + public hname(): wasmtypes.ScHname { + return this._hname; + } + + public isAddress(): bool { + return this._hname.equals(new wasmtypes.ScHname(0)); + } + + // convert to byte array representation + public toBytes(): u8[] { + return agentIDToBytes(this) + } + + // human-readable string representation + public toString(): string { + return agentIDToString(this) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function agentIDDecode(dec: wasmtypes.WasmDecoder): ScAgentID { + return new ScAgentID(wasmtypes.addressDecode(dec), wasmtypes.hnameDecode(dec)) +} + +export function agentIDEncode(enc: wasmtypes.WasmEncoder, value: ScAgentID): void { + wasmtypes.addressEncode(enc, value._address); + wasmtypes.hnameEncode(enc, value._hname); +} + +export function agentIDFromBytes(buf: u8[]): ScAgentID { + if (buf.length == 0) { + return new ScAgentID(wasmtypes.addressFromBytes(buf), wasmtypes.hnameFromBytes(buf)); + } + if (buf.length != ScAgentIDLength) { + panic("invalid AgentID length"); + } + if (buf[0] > wasmtypes.ScAddressAlias) { + panic("invalid AgentID address type"); + } + return new wasmtypes.ScAgentID( + wasmtypes.addressFromBytes(buf.slice(0, wasmtypes.ScAddressLength)), + wasmtypes.hnameFromBytes(buf.slice(wasmtypes.ScAddressLength))); +} + +export function agentIDToBytes(value: ScAgentID): u8[] { + const enc = new wasmtypes.WasmEncoder(); + agentIDEncode(enc, value); + return enc.buf(); +} + +export function agentIDToString(value: ScAgentID): string { + // TODO standardize human readable string + return value._address.toString() + "::" + value._hname.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableAgentID { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return agentIDToString(this.value()); + } + + value(): ScAgentID { + return agentIDFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableAgentID extends ScImmutableAgentID { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScAgentID): void { + this.proxy.set(agentIDToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts new file mode 100644 index 0000000000..3af9f5c8a4 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts @@ -0,0 +1,77 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScBoolLength = 1; +export const ScBoolFalse = 0x00 +export const ScBoolTrue = 0xff + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function boolDecode(dec: wasmtypes.WasmDecoder): bool { + return dec.byte() != ScBoolFalse; +} + +export function boolEncode(enc: wasmtypes.WasmEncoder, value: bool): void { + enc.byte((value ? ScBoolTrue : ScBoolFalse) as u8); +} + +export function boolFromBytes(buf: u8[]): bool { + if (buf.length == 0) { + return false; + } + if (buf.length != ScBoolLength) { + panic("invalid Bool length"); + } + if (buf[0] == ScBoolFalse) { + return false; + } + if (buf[0] != ScBoolTrue) { + panic("invalid Bool value"); + } + return true; +} + +export function boolToBytes(value: bool): u8[] { + return [(value ? ScBoolTrue : ScBoolFalse) as u8]; +} + +export function boolToString(value: bool): string { + return value ? "1" : "0"; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableBool { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return boolToString(this.value()); + } + + value(): bool { + return boolFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableBool extends ScImmutableBool { + delete(): void { + this.proxy.delete(); + } + + setValue(value: bool): void { + this.proxy.set(boolToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts new file mode 100644 index 0000000000..702fd9dced --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts @@ -0,0 +1,70 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./index"; + +export function bytesCompare(lhs: u8[], rhs: u8[]): i32 { + const size = (lhs.length < rhs.length) ? lhs.length : rhs.length; + for (let i = 0; i < size; i++) { + if (lhs[i] != rhs[i]) { + return (lhs[i] > rhs[i]) ? 1 : -1 + } + } + return (lhs.length > size) ? 1 : (rhs.length > size) ? -1 : 0; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function bytesDecode(dec: wasmtypes.WasmDecoder): u8[] { + return dec.bytes(); +} + +export function bytesEncode(enc: wasmtypes.WasmEncoder, value: u8[]): void { + enc.bytes(value); +} + +export function bytesFromBytes(buf: u8[]): u8[] { + return buf; +} + +export function bytesToBytes(buf: u8[]): u8[] { + return buf; +} + +export function bytesToString(value: u8[]): string { + return wasmtypes.base58Encode(value); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableBytes { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return bytesToString(this.value()); + } + + value(): u8[] { + return bytesFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableBytes extends ScImmutableBytes { + delete(): void { + this.proxy.delete(); + } + + setValue(value: u8[]): void { + this.proxy.set(bytesToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts new file mode 100644 index 0000000000..ddae982fd6 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts @@ -0,0 +1,105 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScChainIDLength = 33; + +export class ScChainID { + id: u8[] = wasmtypes.zeroes(ScChainIDLength); + + public address(): wasmtypes.ScAddress { + return wasmtypes.addressFromBytes(this.id); + } + + public equals(other: ScChainID): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return chainIDToBytes(this); + } + + // human-readable string representation + public toString(): string { + return chainIDToString(this) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function chainIDDecode(dec: wasmtypes.WasmDecoder): ScChainID { + return chainIDFromBytesUnchecked(dec.fixedBytes(ScChainIDLength)); +} + +export function chainIDEncode(enc: wasmtypes.WasmEncoder, value: ScChainID): void { + enc.fixedBytes(value.toBytes(), ScChainIDLength); +} + +export function chainIDFromBytes(buf: u8[]): ScChainID { + if (buf.length == 0) { + const chainID = new ScChainID(); + chainID.id[0] = wasmtypes.ScAddressAlias; + return chainID; + } + if (buf.length != ScChainIDLength) { + panic("invalid ChainID length"); + } + if (buf[0] != wasmtypes.ScAddressAlias) { + panic("invalid ChainID: not an alias address"); + } + return chainIDFromBytesUnchecked(buf); +} + +export function chainIDToBytes(value: ScChainID): u8[] { + return value.id; +} + +export function chainIDToString(value: ScChainID): string { + // TODO standardize human readable string + return wasmtypes.base58Encode(value.id); +} + +function chainIDFromBytesUnchecked(buf: u8[]): ScChainID { + let o = new ScChainID(); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableChainID { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return chainIDToString(this.value()); + } + + value(): ScChainID { + return chainIDFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableChainID extends ScImmutableChainID { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScChainID): void { + this.proxy.set(chainIDToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts new file mode 100644 index 0000000000..c95852517c --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts @@ -0,0 +1,105 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScColorLength = 32; + +export class ScColor { + id: u8[] = wasmtypes.zeroes(ScColorLength); + + constructor(fill: u8) { + this.id.fill(fill); + } + + public equals(other: ScColor): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return colorToBytes(this); + } + + // human-readable string representation + public toString(): string { + // TODO standardize human readable string + return colorToString(this); + } +} + +// predefined colors +export const IOTA: ScColor = new ScColor(0x00); +export const MINT: ScColor = new ScColor(0xff); + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function colorDecode(dec: wasmtypes.WasmDecoder): ScColor { + return colorFromBytesUnchecked(dec.fixedBytes(ScColorLength)); +} + +export function colorEncode(enc: wasmtypes.WasmEncoder, value: ScColor): void { + enc.fixedBytes(value.toBytes(), ScColorLength); +} + +export function colorFromBytes(buf: u8[]): ScColor { + if (buf.length == 0) { + return new ScColor(0); + } + if (buf.length != ScColorLength) { + panic("invalid Color length"); + } + return colorFromBytesUnchecked(buf); +} + +export function colorToBytes(value: ScColor): u8[] { + return value.id; +} + +export function colorToString(value: ScColor): string { + // TODO standardize human readable string + return wasmtypes.base58Encode(value.id); +} + +function colorFromBytesUnchecked(buf: u8[]): ScColor { + let o = new ScColor(0); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableColor { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return colorToString(this.value()); + } + + value(): ScColor { + return colorFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableColor extends ScImmutableColor { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScColor): void { + this.proxy.set(colorToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts new file mode 100644 index 0000000000..dbf8826ded --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts @@ -0,0 +1,96 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScHashLength = 32; + +export class ScHash { + id: u8[] = wasmtypes.zeroes(ScHashLength); + + public equals(other: ScHash): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return hashToBytes(this); + } + + // human-readable string representation + public toString(): string { + return hashToString(this); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function hashDecode(dec: wasmtypes.WasmDecoder): ScHash { + return hashFromBytesUnchecked(dec.fixedBytes(ScHashLength)); +} + +export function hashEncode(enc: wasmtypes.WasmEncoder, value: ScHash): void { + enc.fixedBytes(value.toBytes(), ScHashLength); +} + +export function hashFromBytes(buf: u8[]): ScHash { + if (buf.length == 0) { + return new ScHash(); + } + if (buf.length != ScHashLength) { + panic("invalid Hash length"); + } + return hashFromBytesUnchecked(buf); +} + +export function hashToBytes(value: ScHash): u8[] { + return value.id; +} + +export function hashToString(value: ScHash): string { + // TODO standardize human readable string + return wasmtypes.base58Encode(value.id); +} + +function hashFromBytesUnchecked(buf: u8[]): ScHash { + let o = new ScHash(); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableHash { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return hashToString(this.value()); + } + + value(): ScHash { + return hashFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableHash extends ScImmutableHash { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScHash): void { + this.proxy.set(hashToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts new file mode 100644 index 0000000000..f3aa8c4b3c --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts @@ -0,0 +1,100 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScHnameLength = 4; + +export class ScHname { + id: u8[]; + + constructor(id: u32) { + this.id = wasmtypes.uint32ToBytes(id); + } + + public equals(other: ScHname): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return hnameToBytes(this); + } + + // human-readable string representation + public toString(): string { + return hnameToString(this) + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function hnameDecode(dec: wasmtypes.WasmDecoder): ScHname { + return hnameFromBytesUnchecked(dec.fixedBytes(ScHnameLength)); +} + +export function hnameEncode(enc: wasmtypes.WasmEncoder, value: ScHname): void { + enc.fixedBytes(value.toBytes(), ScHnameLength); +} + +export function hnameFromBytes(buf: u8[]): ScHname { + if (buf.length == 0) { + return new ScHname(0); + } + if (buf.length != ScHnameLength) { + panic("invalid Hname length"); + } + return hnameFromBytesUnchecked(buf); +} + +export function hnameToBytes(value: ScHname): u8[] { + return value.id; +} + +export function hnameToString(value: ScHname): string { + const res = wasmtypes.uint32FromBytes(value.id).toString(16); + return "0000000".slice(0, 8 - res.length) + res; +} + +function hnameFromBytesUnchecked(buf: u8[]): ScHname { + let o = new ScHname(0); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableHname { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return hnameToString(this.value()); + } + + value(): ScHname { + return hnameFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableHname extends ScImmutableHname { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScHname): void { + this.proxy.set(hnameToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts new file mode 100644 index 0000000000..d7ed73ba9b --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts @@ -0,0 +1,73 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScInt16Length = 2; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function int16Decode(dec: wasmtypes.WasmDecoder): i16 { + return dec.vliDecode(16) as i16; +} + +export function int16Encode(enc: wasmtypes.WasmEncoder, value: i16): void { + enc.vliEncode(value as i64); +} + +export function int16FromBytes(buf: u8[]): i16 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScInt16Length) { + panic("invalid Int16 length"); + } + let ret: i16 = buf[1]; + return (ret << 8) | buf[0]; +} + +export function int16ToBytes(value: i16): u8[] { + return [ + value as u8, + (value >> 8) as u8, + ]; +} + +export function int16ToString(value: i16): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableInt16 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return int16ToString(this.value()); + } + + value(): i16 { + return int16FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableInt16 extends ScImmutableInt16 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: i16): void { + this.proxy.set(int16ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts new file mode 100644 index 0000000000..3dd567c865 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts @@ -0,0 +1,77 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScInt32Length = 4; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function int32Decode(dec: wasmtypes.WasmDecoder): i32 { + return dec.vliDecode(32) as i32; +} + +export function int32Encode(enc: wasmtypes.WasmEncoder, value: i32): void { + enc.vliEncode(value as i64); +} + +export function int32FromBytes(buf: u8[]): i32 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScInt32Length) { + panic("invalid Int32 length"); + } + let ret: i32 = buf[3]; + ret = (ret << 8) | buf[2]; + ret = (ret << 8) | buf[1]; + return (ret << 8) | buf[0]; +} + +export function int32ToBytes(value: i32): u8[] { + return [ + value as u8, + (value >> 8) as u8, + (value >> 16) as u8, + (value >> 24) as u8, + ]; +} + +export function int32ToString(value: i32): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableInt32 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return int32ToString(this.value()); + } + + value(): i32 { + return int32FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableInt32 extends ScImmutableInt32 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: i32): void { + this.proxy.set(int32ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts new file mode 100644 index 0000000000..9b5ffa70e5 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts @@ -0,0 +1,85 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScInt64Length = 8; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function int64Decode(dec: wasmtypes.WasmDecoder): i64 { + return dec.vliDecode(64); +} + +export function int64Encode(enc: wasmtypes.WasmEncoder, value: i64): void { + enc.vliEncode(value); +} + +export function int64FromBytes(buf: u8[]): i64 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScInt64Length) { + panic("invalid Int64 length"); + } + let ret: i64 = buf[7]; + ret = (ret << 8) | buf[6]; + ret = (ret << 8) | buf[5]; + ret = (ret << 8) | buf[4]; + ret = (ret << 8) | buf[3]; + ret = (ret << 8) | buf[2]; + ret = (ret << 8) | buf[1]; + return (ret << 8) | buf[0]; +} + +export function int64ToBytes(value: i64): u8[] { + return [ + value as u8, + (value >> 8) as u8, + (value >> 16) as u8, + (value >> 24) as u8, + (value >> 32) as u8, + (value >> 40) as u8, + (value >> 48) as u8, + (value >> 56) as u8, + ]; +} + +export function int64ToString(value: i64): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableInt64 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return int64ToString(this.value()); + } + + value(): i64 { + return int64FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableInt64 extends ScImmutableInt64 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: i64): void { + this.proxy.set(int64ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts new file mode 100644 index 0000000000..07705b1bab --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts @@ -0,0 +1,69 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScInt8Length = 1; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function int8Decode(dec: wasmtypes.WasmDecoder): i8 { + return dec.byte() as i8; +} + +export function int8Encode(enc: wasmtypes.WasmEncoder, value: i8): void { + enc.byte(value as u8); +} + +export function int8FromBytes(buf: u8[]): i8 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScInt8Length) { + panic("invalid Int8 length"); + } + return buf[0] as i8; +} + +export function int8ToBytes(value: i8): u8[] { + return [value as u8]; +} + +export function int8ToString(value: i8): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableInt8 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return int8ToString(this.value()); + } + + value(): i8 { + return int8FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableInt8 extends ScImmutableInt8 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: i8): void { + this.proxy.set(int8ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts new file mode 100644 index 0000000000..6f7f726b96 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts @@ -0,0 +1,100 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export const ScRequestIDLength = 34; + +export class ScRequestID { + id: u8[] = wasmtypes.zeroes(ScRequestIDLength); + + public equals(other: ScRequestID): bool { + return wasmtypes.bytesCompare(this.id, other.id) == 0; + } + + // convert to byte array representation + public toBytes(): u8[] { + return requestIDToBytes(this); + } + + // human-readable string representation + public toString(): string { + return requestIDToString(this); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function requestIDDecode(dec: wasmtypes.WasmDecoder): ScRequestID { + return requestIDFromBytesUnchecked(dec.fixedBytes(ScRequestIDLength)); +} + +export function requestIDEncode(enc: wasmtypes.WasmEncoder, value: ScRequestID): void { + enc.fixedBytes(value.toBytes(), ScRequestIDLength); +} + +export function requestIDFromBytes(buf: u8[]): ScRequestID { + if (buf.length == 0) { + return new ScRequestID(); + } + if (buf.length != ScRequestIDLength) { + panic("invalid RequestID length"); + } + // final uint16 output index must be > ledgerstate.MaxOutputCount + if (buf[ScRequestIDLength - 2] > 127 || buf[ScRequestIDLength - 1] != 0) { + panic("invalid RequestID: output index > 127"); + } + return requestIDFromBytesUnchecked(buf); +} + +export function requestIDToBytes(value: ScRequestID): u8[] { + return value.id; +} + +export function requestIDToString(value: ScRequestID): string { + // TODO standardize human readable string + return wasmtypes.base58Encode(value.id); +} + +function requestIDFromBytesUnchecked(buf: u8[]): ScRequestID { + let o = new ScRequestID(); + o.id = buf.slice(0); + return o; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableRequestID { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return requestIDToString(this.value()); + } + + value(): ScRequestID { + return requestIDFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableRequestID extends ScImmutableRequestID { + delete(): void { + this.proxy.delete(); + } + + setValue(value: ScRequestID): void { + this.proxy.set(requestIDToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts new file mode 100644 index 0000000000..9d95bc7d87 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts @@ -0,0 +1,66 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import * as wasmtypes from "./index"; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function stringDecode(dec: wasmtypes.WasmDecoder): string { + return stringFromBytes(dec.bytes()); +} + +export function stringEncode(enc: wasmtypes.WasmEncoder, value: string): void { + enc.bytes(stringToBytes(value)); +} + +export function stringFromBytes(buf: u8[]): string { + return String.UTF8.decodeUnsafe(buf.dataStart, buf.length); +} + +export function stringToBytes(value: string): u8[] { + let arrayBuffer = String.UTF8.encode(value); + let u8Array = Uint8Array.wrap(arrayBuffer) + let ret: u8[] = new Array(u8Array.length); + for (let i = 0; i < ret.length; i++) { + ret[i] = u8Array[i]; + } + return ret; +} + +export function stringToString(value: string): string { + return value; +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableString { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return this.value(); + } + + value(): string { + return stringFromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableString extends ScImmutableString { + delete(): void { + this.proxy.delete(); + } + + setValue(value: string): void { + this.proxy.set(stringToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts new file mode 100644 index 0000000000..737ab37a1a --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts @@ -0,0 +1,73 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScUint16Length = 2; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function uint16Decode(dec: wasmtypes.WasmDecoder): u16 { + return dec.vluDecode(16) as u16; +} + +export function uint16Encode(enc: wasmtypes.WasmEncoder, value: u16): void { + enc.vluEncode(value as u64); +} + +export function uint16FromBytes(buf: u8[]): u16 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScUint16Length) { + panic("invalid Uint16 length"); + } + let ret: u16 = buf[1]; + return (ret << 8) | buf[0]; +} + +export function uint16ToBytes(value: u16): u8[] { + return [ + value as u8, + (value >> 8) as u8, + ]; +} + +export function uint16ToString(value: u16): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableUint16 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return uint16ToString(this.value()); + } + + value(): u16 { + return uint16FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableUint16 extends ScImmutableUint16 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: u16): void { + this.proxy.set(uint16ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts new file mode 100644 index 0000000000..c2210014b3 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts @@ -0,0 +1,77 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScUint32Length = 4; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function uint32Decode(dec: wasmtypes.WasmDecoder): u32 { + return dec.vluDecode(32) as u32; +} + +export function uint32Encode(enc: wasmtypes.WasmEncoder, value: u32): void { + enc.vluEncode(value as u64); +} + +export function uint32FromBytes(buf: u8[]): u32 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScUint32Length) { + panic("invalid Uint32 length"); + } + let ret: u32 = buf[3]; + ret = (ret << 8) | buf[2]; + ret = (ret << 8) | buf[1]; + return (ret << 8) | buf[0]; +} + +export function uint32ToBytes(value: u32): u8[] { + return [ + value as u8, + (value >> 8) as u8, + (value >> 16) as u8, + (value >> 24) as u8, + ]; +} + +export function uint32ToString(value: u32): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableUint32 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return uint32ToString(this.value()); + } + + value(): u32 { + return uint32FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableUint32 extends ScImmutableUint32 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: u32): void { + this.proxy.set(uint32ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts new file mode 100644 index 0000000000..c1483b857b --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts @@ -0,0 +1,85 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScUint64Length = 8; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function uint64Decode(dec: wasmtypes.WasmDecoder): u64 { + return dec.vluDecode(64); +} + +export function uint64Encode(enc: wasmtypes.WasmEncoder, value: u64): void { + enc.vluEncode(value); +} + +export function uint64FromBytes(buf: u8[]): u64 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScUint64Length) { + panic("invalid Uint64 length"); + } + let ret: u64 = buf[7]; + ret = (ret << 8) | buf[6]; + ret = (ret << 8) | buf[5]; + ret = (ret << 8) | buf[4]; + ret = (ret << 8) | buf[3]; + ret = (ret << 8) | buf[2]; + ret = (ret << 8) | buf[1]; + return (ret << 8) | buf[0]; +} + +export function uint64ToBytes(value: u64): u8[] { + return [ + value as u8, + (value >> 8) as u8, + (value >> 16) as u8, + (value >> 24) as u8, + (value >> 32) as u8, + (value >> 40) as u8, + (value >> 48) as u8, + (value >> 56) as u8, + ]; +} + +export function uint64ToString(value: u64): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableUint64 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return uint64ToString(this.value()); + } + + value(): u64 { + return uint64FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableUint64 extends ScImmutableUint64 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: u64): void { + this.proxy.set(uint64ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts new file mode 100644 index 0000000000..5384360601 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts @@ -0,0 +1,69 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +import {panic} from "../sandbox"; +import * as wasmtypes from "./index"; + +export const ScUint8Length = 1; + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export function uint8Decode(dec: wasmtypes.WasmDecoder): u8 { + return dec.byte(); +} + +export function uint8Encode(enc: wasmtypes.WasmEncoder, value: u8): void { + enc.byte(value); +} + +export function uint8FromBytes(buf: u8[]): u8 { + if (buf.length == 0) { + return 0; + } + if (buf.length != ScUint8Length) { + panic("invalid Uint8 length"); + } + return buf[0]; +} + +export function uint8ToBytes(value: u8): u8[] { + return [value]; +} + +export function uint8ToString(value: u8): string { + return value.toString(); +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScImmutableUint8 { + proxy: wasmtypes.Proxy; + + constructor(proxy: wasmtypes.Proxy) { + this.proxy = proxy; + } + + exists(): bool { + return this.proxy.exists(); + } + + toString(): string { + return uint8ToString(this.value()); + } + + value(): u8 { + return uint8FromBytes(this.proxy.get()); + } +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +export class ScMutableUint8 extends ScImmutableUint8 { + delete(): void { + this.proxy.delete(); + } + + setValue(value: u8): void { + this.proxy.set(uint8ToBytes(value)); + } +} diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/tsconfig.json new file mode 100644 index 0000000000..b51e156a90 --- /dev/null +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "assemblyscript/std/assembly.json", + "include": [ + "./*.ts" + ] +} \ No newline at end of file diff --git a/packages/vm/wasmsolo/soloagent.go b/packages/wasmvm/wasmsolo/soloagent.go similarity index 52% rename from packages/vm/wasmsolo/soloagent.go rename to packages/wasmvm/wasmsolo/soloagent.go index a535009f3e..f8e1731801 100644 --- a/packages/vm/wasmsolo/soloagent.go +++ b/packages/wasmvm/wasmsolo/soloagent.go @@ -5,17 +5,17 @@ package wasmsolo import ( "github.com/iotaledger/goshimmer/packages/ledgerstate" - "github.com/iotaledger/hive.go/crypto/ed25519" + cryptolib "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/iscp/colored" "github.com/iotaledger/wasp/packages/solo" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" "github.com/stretchr/testify/require" ) type SoloAgent struct { Env *solo.Solo - Pair *ed25519.KeyPair + Pair *cryptolib.KeyPair address ledgerstate.Address hname iscp.Hname } @@ -26,29 +26,29 @@ func NewSoloAgent(env *solo.Solo) *SoloAgent { return agent } -func (a *SoloAgent) ScAddress() wasmlib.ScAddress { - return wasmlib.NewScAddressFromBytes(a.address.Bytes()) +func (a *SoloAgent) ScAddress() wasmtypes.ScAddress { + return wasmtypes.AddressFromBytes(a.address.Bytes()) } -func (a *SoloAgent) ScAgentID() wasmlib.ScAgentID { - return wasmlib.NewScAgentID(a.ScAddress(), wasmlib.ScHname(a.hname)) +func (a *SoloAgent) ScAgentID() wasmtypes.ScAgentID { + return wasmtypes.NewScAgentID(a.ScAddress(), wasmtypes.ScHname(a.hname)) } -func (a *SoloAgent) Balance(color ...wasmlib.ScColor) int64 { +func (a *SoloAgent) Balance(color ...wasmtypes.ScColor) uint64 { switch len(color) { case 0: - return int64(a.Env.GetAddressBalance(a.address, colored.IOTA)) + return a.Env.GetAddressBalance(a.address, colored.IOTA) case 1: col, err := colored.ColorFromBytes(color[0].Bytes()) require.NoError(a.Env.T, err) - return int64(a.Env.GetAddressBalance(a.address, col)) + return a.Env.GetAddressBalance(a.address, col) default: require.Fail(a.Env.T, "too many color arguments") return 0 } } -func (a *SoloAgent) Mint(amount int64) (wasmlib.ScColor, error) { - color, err := a.Env.MintTokens(a.Pair, uint64(amount)) - return wasmlib.NewScColorFromBytes(color.Bytes()), err +func (a *SoloAgent) Mint(amount uint64) (wasmtypes.ScColor, error) { + color, err := a.Env.MintTokens(a.Pair, amount) + return wasmtypes.ColorFromBytes(color.Bytes()), err } diff --git a/packages/vm/wasmsolo/solocontext.go b/packages/wasmvm/wasmsolo/solocontext.go similarity index 67% rename from packages/vm/wasmsolo/solocontext.go rename to packages/wasmvm/wasmsolo/solocontext.go index 479ce39b22..8dd84dfd4e 100644 --- a/packages/vm/wasmsolo/solocontext.go +++ b/packages/wasmvm/wasmsolo/solocontext.go @@ -10,52 +10,75 @@ import ( "github.com/iotaledger/goshimmer/packages/ledgerstate" "github.com/iotaledger/goshimmer/packages/ledgerstate/utxoutil" - "github.com/iotaledger/hive.go/crypto/ed25519" + cryptolib "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/iscp/colored" "github.com/iotaledger/wasp/packages/iscp/coreutil" "github.com/iotaledger/wasp/packages/solo" "github.com/iotaledger/wasp/packages/util" - "github.com/iotaledger/wasp/packages/vm/wasmhost" - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/vm/wasmproc" + "github.com/iotaledger/wasp/packages/wasmvm/wasmhost" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" "github.com/stretchr/testify/require" ) -const ( - SoloDebug = false - SoloHostTracing = false - SoloStackTracing = false +const ( // TODO set back to false + SoloDebug = true + SoloHostTracing = true + SoloStackTracing = true ) var ( - GoDebug = flag.Bool("godebug", false, "debug go smart contract code") - GoWasm = flag.Bool("gowasm", false, "prefer go wasm smart contract code") - GoWasmEdge = flag.Bool("gowasmedge", false, "use WasmEdge instead of WasmTime") - TsWasm = flag.Bool("tswasm", false, "prefer typescript wasm smart contract code") + // GoWasm / RsWasm / TsWasm are used to specify the Wasm language mode, + // By default, SoloContext will try to run the Go SC code directly (no Wasm) + // The 3 flags can be used to cause Wasm code to be loaded and run instead. + // They are checked in sequence and the first one set determines the Wasm language used. + GoWasm = flag.Bool("gowasm", false, "use Go Wasm smart contract code") + RsWasm = flag.Bool("rswasm", false, "use Rust Wasm smart contract code") + TsWasm = flag.Bool("tswasm", false, "use TypeScript Wasm smart contract code") + + // UseWasmEdge flag is kept here in case we decide to use WasmEdge again. Some tests + // refer to this flag, so we keep it here instead of having to comment out a bunch + // of code. To actually enable WasmEdge you need to uncomment the relevant lines in + // NewSoloContextForChain(), and remove the go:build directives from wasmedge.go, so + // that the linker can actually pull in the WasmEdge runtime. + UseWasmEdge = flag.Bool("wasmedge", false, "use WasmEdge instead of WasmTime") +) + +const ( + L2FundsContract = 1_000_000 + L2FundsCreator = 2_000_000 + L2FundsOriginator = 3_000_000 + + WasmDustDeposit = 1000 ) type SoloContext struct { Chain *solo.Chain - Convertor SoloConvertor + Convertor wasmhost.WasmConvertor creator *SoloAgent + Dust uint64 Err error + Gas uint64 + GasFee uint64 Hprog hashing.HashValue - keyPair *ed25519.KeyPair isRequest bool + IsWasm bool + keyPair *cryptolib.KeyPair mint uint64 offLedger bool scName string Tx *ledgerstate.Transaction - wc *wasmproc.WasmContext wasmHostOld wasmlib.ScHost + wc *wasmhost.WasmContext } var ( //_ iscp.Gas = &SoloContext{} - _ wasmlib.ScFuncCallContext = &SoloContext{} - _ wasmlib.ScViewCallContext = &SoloContext{} + _ wasmlib.ScFuncCallContext = &SoloContext{} + _ wasmlib.ScViewCallContext = &SoloContext{} + SoloSeed = cryptolib.NewSeed([]byte("SoloSeedSoloSeedSoloSeedSoloSeed")) ) func (ctx *SoloContext) Burn(i int64) { @@ -71,6 +94,16 @@ func (ctx *SoloContext) SetBudget(i int64) { // ignore gas for now } +//nolint:unused,deadcode +func contains(s []*iscp.AgentID, e *iscp.AgentID) bool { + for _, a := range s { + if a.Equals(e) { + return true + } + } + return false +} + // NewSoloContext can be used to create a SoloContext associated with a smart contract // with minimal information and will verify successful creation before returning ctx. // It will start a default chain "chain1" before initializing the smart contract. @@ -79,7 +112,7 @@ func (ctx *SoloContext) SetBudget(i int64) { // the contract's init() function can be specified. // Unless you want to use a different chain than the default "chain1" this will be your // function of choice to set up a smart contract for your tests -func NewSoloContext(t *testing.T, scName string, onLoad func(), init ...*wasmlib.ScInitFunc) *SoloContext { +func NewSoloContext(t *testing.T, scName string, onLoad wasmhost.ScOnloadFunc, init ...*wasmlib.ScInitFunc) *SoloContext { ctx := NewSoloContextForChain(t, nil, nil, scName, onLoad, init...) require.NoError(t, ctx.Err) return ctx @@ -93,15 +126,15 @@ func NewSoloContext(t *testing.T, scName string, onLoad func(), init ...*wasmlib // Optionally, an init.Func that has been initialized with the parameters to pass to // the contract's init() function can be specified. // You can check for any error that occurred by checking the ctx.Err member. -func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, scName string, onLoad func(), - init ...*wasmlib.ScInitFunc) *SoloContext { +func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, scName string, + onLoad wasmhost.ScOnloadFunc, init ...*wasmlib.ScInitFunc) *SoloContext { ctx := soloContext(t, chain, scName, creator) - var keyPair *ed25519.KeyPair + var keyPair *cryptolib.KeyPair if creator != nil { keyPair = creator.Pair } - ctx.upload(keyPair) + ctx.uploadWasm(keyPair) if ctx.Err != nil { return ctx } @@ -110,18 +143,18 @@ func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, if len(init) != 0 { params = init[0].Params() } - if *GoDebug { - wasmproc.GoWasmVM = func() wasmhost.WasmVM { + if !ctx.IsWasm { + wasmhost.GoWasmVM = func() wasmhost.WasmVM { return wasmhost.NewWasmGoVM(ctx.scName, onLoad) } } - //if *GoWasmEdge && wasmproc.GoWasmVM == nil { + //if ctx.IsWasm && *UseWasmEdge && wasmproc.GoWasmVM == nil { // wasmproc.GoWasmVM = wasmhost.NewWasmEdgeVM //} ctx.Err = ctx.Chain.DeployContract(keyPair, ctx.scName, ctx.Hprog, params...) - if *GoDebug { + if !ctx.IsWasm { // just in case deploy failed we don't want to leave this around - wasmproc.GoWasmVM = nil + wasmhost.GoWasmVM = nil } if ctx.Err != nil { return ctx @@ -138,13 +171,13 @@ func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, // Optionally, an init.Func that has been initialized with the parameters to pass to // the contract's init() function can be specified. // You can check for any error that occurred by checking the ctx.Err member. -func NewSoloContextForNative(t *testing.T, chain *solo.Chain, creator *SoloAgent, scName string, onLoad func(), +func NewSoloContextForNative(t *testing.T, chain *solo.Chain, creator *SoloAgent, scName string, onLoad wasmhost.ScOnloadFunc, proc *coreutil.ContractProcessor, init ...*wasmlib.ScInitFunc) *SoloContext { ctx := soloContext(t, chain, scName, creator) ctx.Chain.Env.WithNativeContract(proc) ctx.Hprog = proc.Contract.ProgramHash - var keyPair *ed25519.KeyPair + var keyPair *cryptolib.KeyPair if creator != nil { keyPair = creator.Pair } @@ -161,7 +194,7 @@ func NewSoloContextForNative(t *testing.T, chain *solo.Chain, creator *SoloAgent } func soloContext(t *testing.T, chain *solo.Chain, scName string, creator *SoloAgent) *SoloContext { - ctx := &SoloContext{scName: scName, Chain: chain, creator: creator} + ctx := &SoloContext{scName: scName, Chain: chain, creator: creator, Dust: WasmDustDeposit} if chain == nil { ctx.Chain = StartChain(t, "chain1") } @@ -175,14 +208,13 @@ func StartChain(t *testing.T, chainName string, env ...*solo.Solo) *solo.Chain { wasmhost.DisableWasmTimeout = true } wasmhost.HostTracing = SoloHostTracing - // wasmhost.HostTracingAll = SoloHostTracing var soloEnv *solo.Solo if len(env) != 0 { soloEnv = env[0] } if soloEnv == nil { - soloEnv = solo.New(t, SoloDebug, SoloStackTracing) + soloEnv = solo.New(t, SoloDebug, SoloStackTracing, SoloSeed) } return soloEnv.NewChain(nil, chainName) } @@ -197,7 +229,7 @@ func (ctx *SoloContext) Account() *SoloAgent { } } -func (ctx *SoloContext) AccountID() wasmlib.ScAgentID { +func (ctx *SoloContext) AccountID() wasmtypes.ScAgentID { return ctx.Account().ScAgentID() } @@ -209,31 +241,31 @@ func (ctx *SoloContext) AdvanceClockBy(step time.Duration) { // Balance returns the account balance of the specified agent on the chain associated with ctx. // The optional color parameter can be used to retrieve the balance for the specific color. // When color is omitted, wasmlib.IOTA is assumed. -func (ctx *SoloContext) Balance(agent *SoloAgent, color ...wasmlib.ScColor) int64 { +func (ctx *SoloContext) Balance(agent *SoloAgent, color ...wasmtypes.ScColor) uint64 { account := iscp.NewAgentID(agent.address, agent.hname) balances := ctx.Chain.GetAccountBalance(account) switch len(color) { case 0: - return int64(balances.Get(colored.IOTA)) + return balances.Get(colored.IOTA) case 1: col, err := colored.ColorFromBytes(color[0].Bytes()) require.NoError(ctx.Chain.Env.T, err) - return int64(balances.Get(col)) + return balances.Get(col) default: require.Fail(ctx.Chain.Env.T, "too many color arguments") return 0 } } -func (ctx *SoloContext) ChainID() wasmlib.ScChainID { +func (ctx *SoloContext) ChainID() wasmtypes.ScChainID { return ctx.Convertor.ScChainID(ctx.Chain.ChainID) } -func (ctx *SoloContext) ChainOwnerID() wasmlib.ScAgentID { +func (ctx *SoloContext) ChainOwnerID() wasmtypes.ScAgentID { return ctx.Convertor.ScAgentID(ctx.Chain.OriginatorAgentID) } -func (ctx *SoloContext) ContractCreator() wasmlib.ScAgentID { +func (ctx *SoloContext) ContractCreator() wasmtypes.ScAgentID { return ctx.Creator().ScAgentID() } @@ -255,18 +287,35 @@ func (ctx *SoloContext) EnqueueRequest() { ctx.isRequest = true } +func (ctx *SoloContext) existFile(path, ext string) string { + fileName := ctx.scName + ext + + // first check for new file in path + pathName := path + fileName + exists, _ := util.ExistsFilePath(pathName) + if exists { + return pathName + } + + // check for file in current folder + exists, _ = util.ExistsFilePath(fileName) + if exists { + return fileName + } + + // file not found + return "" +} + func (ctx *SoloContext) Host() wasmlib.ScHost { return nil } // init further initializes the SoloContext. -func (ctx *SoloContext) init(onLoad func()) *SoloContext { - ctx.wc = wasmproc.NewWasmContext("-solo", nil) - ctx.wc.Init(nil) - ctx.wc.TrackObject(wasmproc.NewNullObject(&ctx.wc.KvStoreHost)) - ctx.wc.TrackObject(NewSoloScContext(ctx)) +func (ctx *SoloContext) init(onLoad wasmhost.ScOnloadFunc) *SoloContext { + ctx.wc = wasmhost.NewWasmContextForSoloContext("-solo-", NewSoloSandbox(ctx)) ctx.wasmHostOld = wasmhost.Connect(ctx.wc) - onLoad() + onLoad(-1) return ctx } @@ -276,20 +325,21 @@ func (ctx *SoloContext) InitFuncCallContext() { } // InitViewCallContext is a function that is required to use SoloContext as an ScViewCallContext -func (ctx *SoloContext) InitViewCallContext() { +func (ctx *SoloContext) InitViewCallContext(hContract wasmtypes.ScHname) wasmtypes.ScHname { _ = wasmhost.Connect(ctx.wc) + return ctx.Convertor.ScHname(iscp.Hn(ctx.scName)) } // Minted returns the color and amount of newly minted tokens -func (ctx *SoloContext) Minted() (wasmlib.ScColor, uint64) { +func (ctx *SoloContext) Minted() (wasmtypes.ScColor, uint64) { t := ctx.Chain.Env.T t.Logf("minting request tx: %s", ctx.Tx.ID().Base58()) mintedAmounts := colored.BalancesFromL1Map(utxoutil.GetMintedAmounts(ctx.Tx)) require.Len(t, mintedAmounts, 1) - var mintedColor wasmlib.ScColor + var mintedColor wasmtypes.ScColor var mintedAmount uint64 for c := range mintedAmounts { - mintedColor = ctx.Convertor.ScColor(c) + mintedColor = ctx.Convertor.ScColor(&c) mintedAmount = mintedAmounts[c] break } @@ -324,7 +374,7 @@ func (ctx *SoloContext) Sign(agent *SoloAgent, mint ...uint64) wasmlib.ScFuncCal return ctx } -func (ctx *SoloContext) SoloContextForCore(t *testing.T, scName string, onLoad func()) *SoloContext { +func (ctx *SoloContext) SoloContextForCore(t *testing.T, scName string, onLoad wasmhost.ScOnloadFunc) *SoloContext { ctxCore := soloContext(t, ctx.Chain, scName, nil).init(onLoad) ctxCore.wasmHostOld = ctx.wasmHostOld return ctxCore @@ -335,44 +385,30 @@ func (ctx *SoloContext) Transfer() wasmlib.ScTransfers { return wasmlib.NewScTransfers() } -// TODO can we make upload work through an off-ledger request instead? -// that way we can get rid of all the extra token code when checking balances - -func (ctx *SoloContext) upload(keyPair *ed25519.KeyPair) { - if *GoDebug { +func (ctx *SoloContext) uploadWasm(keyPair *cryptolib.KeyPair) { + wasmFile := "" + if *GoWasm { + // find Go Wasm file + wasmFile = ctx.existFile("../go/pkg/", "_go.wasm") + } else if *RsWasm { + // find Rust Wasm file + wasmFile = ctx.existFile("../pkg/", "_bg.wasm") + } else if *TsWasm { + // find TypeScript Wasm file + wasmFile = ctx.existFile("../ts/pkg/", "_ts.wasm") + } else { + // none of the Wasm modes selected, use WasmGoVM to run Go SC code directly ctx.Hprog, ctx.Err = ctx.Chain.UploadWasm(keyPair, []byte("go:"+ctx.scName)) return } - // start with file in test folder - wasmFile := ctx.scName + "_bg.wasm" - - // try (newer?) Rust Wasm file first - rsFile := "../pkg/" + wasmFile - exists, _ := util.ExistsFilePath(rsFile) - if exists { - wasmFile = rsFile - } - - // try Go Wasm file? - if !exists || *GoWasm { - goFile := "../go/pkg/" + ctx.scName + "_go.wasm" - exists, _ = util.ExistsFilePath(goFile) - if exists { - wasmFile = goFile - } - } - - // try TypeScript Wasm file? - if !exists || *TsWasm { - tsFile := "../ts/pkg/" + ctx.scName + "_ts.wasm" - exists, _ = util.ExistsFilePath(tsFile) - if exists { - wasmFile = tsFile - } + if wasmFile == "" { + panic("cannot find Wasm file for: " + ctx.scName) } + // upload the Wasm code into the core blob contract ctx.Hprog, ctx.Err = ctx.Chain.UploadWasmFromFile(keyPair, wasmFile) + ctx.IsWasm = true } // WaitForPendingRequests waits for expectedRequests pending requests to be processed. diff --git a/packages/wasmvm/wasmsolo/solosandbox.go b/packages/wasmvm/wasmsolo/solosandbox.go new file mode 100644 index 0000000000..8df4fc03c5 --- /dev/null +++ b/packages/wasmvm/wasmsolo/solosandbox.go @@ -0,0 +1,315 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmsolo + +import ( + "bytes" + "errors" + "time" + + "github.com/iotaledger/goshimmer/packages/ledgerstate" + "github.com/iotaledger/wasp/packages/iscp" + "github.com/iotaledger/wasp/packages/iscp/colored" + "github.com/iotaledger/wasp/packages/kv/codec" + "github.com/iotaledger/wasp/packages/kv/dict" + "github.com/iotaledger/wasp/packages/solo" + "github.com/iotaledger/wasp/packages/vm/sandbox/sandbox_utils" + "github.com/iotaledger/wasp/packages/wasmvm/wasmhost" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" + "golang.org/x/xerrors" +) + +// NOTE: These functions correspond to the Sandbox fnXxx constants in WasmLib +var sandboxFunctions = []func(*SoloSandbox, []byte) []byte{ + nil, + (*SoloSandbox).fnAccountID, + (*SoloSandbox).fnBalance, + (*SoloSandbox).fnBalances, + (*SoloSandbox).fnBlockContext, + (*SoloSandbox).fnCall, + (*SoloSandbox).fnCaller, + (*SoloSandbox).fnChainID, + (*SoloSandbox).fnChainOwnerID, + (*SoloSandbox).fnContract, + (*SoloSandbox).fnContractCreator, + (*SoloSandbox).fnDeployContract, + (*SoloSandbox).fnEntropy, + (*SoloSandbox).fnEvent, + (*SoloSandbox).fnIncomingTransfer, + (*SoloSandbox).fnLog, + (*SoloSandbox).fnMinted, + (*SoloSandbox).fnPanic, + (*SoloSandbox).fnParams, + (*SoloSandbox).fnPost, + (*SoloSandbox).fnRequest, + (*SoloSandbox).fnRequestID, + (*SoloSandbox).fnResults, + (*SoloSandbox).fnSend, + (*SoloSandbox).fnStateAnchor, + (*SoloSandbox).fnTimestamp, + (*SoloSandbox).fnTrace, + (*SoloSandbox).fnUtilsBase58Decode, + (*SoloSandbox).fnUtilsBase58Encode, + (*SoloSandbox).fnUtilsBlsAddress, + (*SoloSandbox).fnUtilsBlsAggregate, + (*SoloSandbox).fnUtilsBlsValid, + (*SoloSandbox).fnUtilsEd25519Address, + (*SoloSandbox).fnUtilsEd25519Valid, + (*SoloSandbox).fnUtilsHashBlake2b, + (*SoloSandbox).fnUtilsHashName, + (*SoloSandbox).fnUtilsHashSha3, +} + +// SoloSandbox acts as a temporary host side of the WasmLib Sandbox interface. +// It acts as a change-resistant layer to wrap changes to the Solo environment, +// to limit bothering users of WasmLib as little as possible with those changes. +// Note that only those functions that are related to invocation of SC requests +// are actually necessary here. These sandbox functions will never be called +// other than through the SC function call interface generated by schema tool. +type SoloSandbox struct { + ctx *SoloContext + cvt wasmhost.WasmConvertor + utils iscp.Utils +} + +var _ wasmhost.ISandbox = new(SoloSandbox) + +func NewSoloSandbox(ctx *SoloContext) *SoloSandbox { + return &SoloSandbox{ctx: ctx, utils: sandbox_utils.NewUtils()} +} + +func (s *SoloSandbox) Call(funcNr int32, params []byte) []byte { + s.ctx.Err = nil + defer func() { + r := recover() + if r == nil { + return + } + if s.ctx.Err != nil { + s.ctx.Chain.Log.Infof("stacked error: %s", s.ctx.Err.Error()) + } + switch errType := r.(type) { + case error: + s.ctx.Err = errType + case string: + s.ctx.Err = errors.New(errType) + default: + s.ctx.Err = xerrors.Errorf("RunScFunction: %v", errType) + } + s.ctx.Chain.Log.Infof("stolor error:: %s", s.ctx.Err.Error()) + }() + return sandboxFunctions[-funcNr](s, params) +} + +func (s *SoloSandbox) checkErr(err error) { + if err != nil { + panic(err.Error()) + } +} + +func (s *SoloSandbox) Panicf(format string, args ...interface{}) { + s.ctx.Chain.Log.Panicf(format, args...) +} + +func (s *SoloSandbox) Tracef(format string, args ...interface{}) { + s.ctx.Chain.Log.Debugf(format, args...) +} + +func (s *SoloSandbox) postSync(contract, function string, params dict.Dict, transfer colored.Balances) []byte { + req := solo.NewCallParamsFromDic(contract, function, params) + req.WithTransfers(transfer) + ctx := s.ctx + if ctx.mint > 0 { + mintAddress := ledgerstate.NewED25519Address(ctx.keyPair.PublicKey) + req.WithMint(mintAddress, ctx.mint) + } + _ = wasmhost.Connect(ctx.wasmHostOld) + var res dict.Dict + if ctx.offLedger { + ctx.offLedger = false + res, ctx.Err = ctx.Chain.PostRequestOffLedger(req, ctx.keyPair) + } else if !ctx.isRequest { + ctx.Tx, res, ctx.Err = ctx.Chain.PostRequestSyncTx(req, ctx.keyPair) + } else { + ctx.isRequest = false + ctx.Tx, _, ctx.Err = ctx.Chain.RequestFromParamsToLedger(req, nil) + if ctx.Err == nil { + ctx.Chain.Env.EnqueueRequests(ctx.Tx) + } + } + _ = wasmhost.Connect(ctx.wc) + if ctx.Err != nil { + return nil + } + return res.Bytes() +} + +//////////////////// sandbox functions \\\\\\\\\\\\\\\\\\\\ + +func (s *SoloSandbox) fnAccountID(args []byte) []byte { + return s.ctx.AccountID().Bytes() +} + +func (s *SoloSandbox) fnBalance(args []byte) []byte { + color := wasmtypes.ColorFromBytes(args) + return codec.EncodeUint64(s.ctx.Balance(s.ctx.Account(), color)) +} + +func (s *SoloSandbox) fnBalances(args []byte) []byte { + agent := s.ctx.Account() + account := iscp.NewAgentID(agent.address, agent.hname) + balances := s.ctx.Chain.GetAccountBalance(account) + return balances.Bytes() +} + +func (s *SoloSandbox) fnBlockContext(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnCall(args []byte) []byte { + ctx := s.ctx + req := wasmrequests.NewCallRequestFromBytes(args) + contract := s.cvt.IscpHname(req.Contract) + if contract != iscp.Hn(ctx.scName) { + s.Panicf("unknown contract: %s vs. %s", contract.String(), ctx.scName) + } + function := s.cvt.IscpHname(req.Function) + funcName := ctx.wc.FunctionFromCode(uint32(function)) + if funcName == "" { + s.Panicf("unknown function: %s", function.String()) + } + s.Tracef("CALL %s.%s", ctx.scName, funcName) + params, err := dict.FromBytes(req.Params) + s.checkErr(err) + transfer, err := colored.BalancesFromBytes(req.Transfer) + s.checkErr(err) + + if len(transfer) != 0 { + return s.postSync(ctx.scName, funcName, params, transfer) + } + + _ = wasmhost.Connect(ctx.wasmHostOld) + res, err := ctx.Chain.CallView(ctx.scName, funcName, params) + _ = wasmhost.Connect(ctx.wc) + ctx.Err = err + if ctx.Err != nil { + return nil + } + return res.Bytes() +} + +func (s *SoloSandbox) fnCaller(args []byte) []byte { + return s.ctx.Chain.OriginatorAgentID.Bytes() +} + +func (s *SoloSandbox) fnChainID(args []byte) []byte { + return s.ctx.ChainID().Bytes() +} + +func (s *SoloSandbox) fnChainOwnerID(args []byte) []byte { + return s.ctx.ChainOwnerID().Bytes() +} + +func (s *SoloSandbox) fnContract(args []byte) []byte { + return s.ctx.Account().hname.Bytes() +} + +func (s *SoloSandbox) fnContractCreator(args []byte) []byte { + return s.ctx.ContractCreator().Bytes() +} + +func (s *SoloSandbox) fnDeployContract(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnEntropy(args []byte) []byte { + return s.ctx.Chain.ChainID.Bytes()[1:] +} + +func (s *SoloSandbox) fnEvent(args []byte) []byte { + s.Panicf("solo cannot send events") + return nil +} + +func (s *SoloSandbox) fnIncomingTransfer(args []byte) []byte { + // zero incoming balance + return colored.NewBalances().Bytes() +} + +func (s *SoloSandbox) fnLog(args []byte) []byte { + s.ctx.Chain.Log.Infof(string(args)) + return nil +} + +func (s *SoloSandbox) fnMinted(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnPanic(args []byte) []byte { + s.ctx.Chain.Log.Panicf("SOLO panic: %s", string(args)) + return nil +} + +func (s *SoloSandbox) fnParams(args []byte) []byte { + return make(dict.Dict).Bytes() +} + +func (s *SoloSandbox) fnPost(args []byte) []byte { + req := wasmrequests.NewPostRequestFromBytes(args) + if !bytes.Equal(req.ChainID.Bytes(), s.fnChainID(nil)) { + s.Panicf("unknown chain id: %s", req.ChainID.String()) + } + contract := s.cvt.IscpHname(req.Contract) + if contract != iscp.Hn(s.ctx.scName) { + s.Panicf("unknown contract: %s", contract.String()) + } + function := s.cvt.IscpHname(req.Function) + funcName := s.ctx.wc.FunctionFromCode(uint32(function)) + if funcName == "" { + s.Panicf("unknown function: %s", function.String()) + } + s.Tracef("POST %s.%s", s.ctx.scName, funcName) + params, err := dict.FromBytes(req.Params) + s.checkErr(err) + transfer, err := colored.BalancesFromBytes(req.Transfer) + s.checkErr(err) + if len(transfer) == 0 && !s.ctx.offLedger { + transfer.Add(colored.Color{}, 1) + } + if req.Delay != 0 { + s.Panicf("cannot delay solo post") + } + return s.postSync(s.ctx.scName, funcName, params, transfer) +} + +func (s *SoloSandbox) fnRequest(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnRequestID(args []byte) []byte { + return append(s.ctx.Chain.ChainID.Bytes()[1:], 0, 0) +} + +func (s *SoloSandbox) fnResults(args []byte) []byte { + panic("implement me") +} + +// transfer tokens to L1 address +func (s *SoloSandbox) fnSend(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnStateAnchor(args []byte) []byte { + panic("implement me") +} + +func (s *SoloSandbox) fnTimestamp(args []byte) []byte { + return codec.EncodeInt64(time.Now().UnixNano()) +} + +func (s *SoloSandbox) fnTrace(args []byte) []byte { + s.ctx.Chain.Log.Debugf(string(args)) + return nil +} diff --git a/packages/wasmvm/wasmsolo/solosandboxutils.go b/packages/wasmvm/wasmsolo/solosandboxutils.go new file mode 100644 index 0000000000..0360d20e3f --- /dev/null +++ b/packages/wasmvm/wasmsolo/solosandboxutils.go @@ -0,0 +1,78 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +package wasmsolo + +import ( + "github.com/iotaledger/wasp/packages/kv/codec" + "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" +) + +func (s *SoloSandbox) fnUtilsBase58Decode(args []byte) []byte { + bytes, err := s.utils.Base58().Decode(string(args)) + s.checkErr(err) + return bytes +} + +func (s *SoloSandbox) fnUtilsBase58Encode(args []byte) []byte { + return []byte(s.utils.Base58().Encode(args)) +} + +func (s *SoloSandbox) fnUtilsBlsAddress(args []byte) []byte { + address, err := s.utils.BLS().AddressFromPublicKey(args) + s.checkErr(err) + return address.Bytes() +} + +func (s *SoloSandbox) fnUtilsBlsAggregate(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + count := int(wasmtypes.Uint32Decode(dec)) + pubKeysBin := make([][]byte, count) + for i := 0; i < count; i++ { + pubKeysBin[i] = dec.Bytes() + } + count = int(wasmtypes.Uint32Decode(dec)) + sigsBin := make([][]byte, count) + for i := 0; i < count; i++ { + sigsBin[i] = dec.Bytes() + } + pubKeyBin, sigBin, err := s.utils.BLS().AggregateBLSSignatures(pubKeysBin, sigsBin) + s.checkErr(err) + return wasmtypes.NewWasmEncoder().Bytes(pubKeyBin).Bytes(sigBin).Buf() +} + +func (s *SoloSandbox) fnUtilsBlsValid(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + data := dec.Bytes() + pubKey := dec.Bytes() + signature := dec.Bytes() + valid := s.utils.BLS().ValidSignature(data, pubKey, signature) + return codec.EncodeBool(valid) +} + +func (s *SoloSandbox) fnUtilsEd25519Address(args []byte) []byte { + address, err := s.utils.ED25519().AddressFromPublicKey(args) + s.checkErr(err) + return address.Bytes() +} + +func (s *SoloSandbox) fnUtilsEd25519Valid(args []byte) []byte { + dec := wasmtypes.NewWasmDecoder(args) + data := dec.Bytes() + pubKey := dec.Bytes() + signature := dec.Bytes() + valid := s.utils.ED25519().ValidSignature(data, pubKey, signature) + return codec.EncodeBool(valid) +} + +func (s *SoloSandbox) fnUtilsHashBlake2b(args []byte) []byte { + return s.utils.Hashing().Blake2b(args).Bytes() +} + +func (s *SoloSandbox) fnUtilsHashName(args []byte) []byte { + return codec.EncodeHname(s.utils.Hashing().Hname(string(args))) +} + +func (s *SoloSandbox) fnUtilsHashSha3(args []byte) []byte { + return s.utils.Hashing().Sha3(args).Bytes() +} diff --git a/packages/wasmvm/wasmvmhost/host.go b/packages/wasmvm/wasmvmhost/host.go new file mode 100644 index 0000000000..594c90c8b9 --- /dev/null +++ b/packages/wasmvm/wasmvmhost/host.go @@ -0,0 +1,109 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + +//go:build wasm +// +build wasm + +package wasmvmhost + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" + +// interface WasmLib to the VM host + +// These 2 external functions are funneling the entire WasmLib functionality +// to their counterparts on the host. + +//go:wasm-module WasmLib +//export hostStateGet +func hostStateGet(keyRef *byte, keyLen int32, valRef *byte, valLen int32) int32 + +//go:wasm-module WasmLib +//export hostStateSet +func hostStateSet(keyRef *byte, keyLen int32, valRef *byte, valLen int32) + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +// ptr returns pointer to slice or nil when slice is empty +func ptr(buf []byte) *byte { + // &buf[0] will panic on zero length slice, so use nil instead + if len(buf) == 0 { + return nil + } + return &buf[0] +} + +// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ + +type WasmVMHost struct { +} + +// implements wasmlib.ScHost interface +var _ wasmlib.ScHost = &WasmVMHost{} + +func ConnectWasmHost() { + w := &WasmVMHost{} + wasmlib.ConnectHost(w) +} + +func (w *WasmVMHost) ExportName(index int32, name string) { + // nil key indicates export name, with keyLen indicating index + // this removes the need for a separate hostExportName function + buf := []byte(name) + hostStateSet(nil, index, ptr(buf), int32(len(buf))) +} + +func (w *WasmVMHost) Sandbox(funcNr int32, params []byte) []byte { + // call sandbox function, result value will be cached by host + // always negative funcNr as keyLen indicates sandbox call + // this removes the need for a separate hostSandbox function + size := hostStateGet(nil, funcNr, ptr(params), int32(len(params))) + + // zero length, no need to retrieve cached value + if size == 0 { + return []byte{} + } + + // retrieve cached result value from host + result := make([]byte, size) + _ = hostStateGet(nil, 0, &result[0], size) + return result +} + +func (w *WasmVMHost) StateDelete(key []byte) { + // value size -1 means delete key + // this removes the need for a separate hostStateDel function + hostStateSet(&key[0], int32(len(key)), nil, -1) +} + +func (w *WasmVMHost) StateExists(key []byte) bool { + // value size -1 means only test for existence + // returned size -1 indicates keyID not found (or error) + // this removes the need for a separate hostStateExists function + return hostStateGet(&key[0], int32(len(key)), nil, -1) >= 0 +} + +func (w *WasmVMHost) StateGet(key []byte) []byte { + // variable sized result expected, + // query size first by passing zero length buffer + // value will be cached by host + size := hostStateGet(&key[0], int32(len(key)), nil, 0) + + // -1 means non-existent + if size < 0 { + return []byte(nil) + } + + // zero length, no need to retrieve cached value + if size == 0 { + return []byte{} + } + + // retrieve cached value from host + value := make([]byte, size) + _ = hostStateGet(nil, 0, &value[0], size) + return value +} + +func (w *WasmVMHost) StateSet(key, value []byte) { + hostStateSet(&key[0], int32(len(key)), ptr(value), int32(len(value))) +} diff --git a/packages/wasp/constants.go b/packages/wasp/constants.go index 265409ec52..75310e0477 100644 --- a/packages/wasp/constants.go +++ b/packages/wasp/constants.go @@ -4,7 +4,7 @@ var VersionHash string const ( // Version version number - Version = "0.2.3" + Version = "0.2.5" // Name app code name Name = "Wasp" diff --git a/packages/webapi/admapi/chainmetrics.go b/packages/webapi/admapi/chainmetrics.go index ecf32d8137..aecbc0dc53 100644 --- a/packages/webapi/admapi/chainmetrics.go +++ b/packages/webapi/admapi/chainmetrics.go @@ -19,6 +19,7 @@ func addChainMetricsEndpoints(adm echoswagger.ApiGroup, chainsProvider chains.Pr cms := &chainMetricsService{chainsProvider} addChainNodeConnMetricsEndpoints(adm, cms) addChainConsensusMetricsEndpoints(adm, cms) + addChainConcensusPipeMetricsEndpoints(adm, cms) } func addChainNodeConnMetricsEndpoints(adm echoswagger.ApiGroup, cms *chainMetricsService) { @@ -75,12 +76,12 @@ func addChainNodeConnMetricsEndpoints(adm echoswagger.ApiGroup, cms *chainMetric adm.GET(routes.GetChainsNodeConnectionMetrics(), cms.handleGetChainsNodeConnMetrics). SetSummary("Get cummulative chains node connection metrics"). - AddResponse(http.StatusOK, "Chains Metrics", example, nil) + AddResponse(http.StatusOK, "Cummulative chains metrics", example, nil) adm.GET(routes.GetChainNodeConnectionMetrics(":chainID"), cms.handleGetChainNodeConnMetrics). SetSummary("Get chain node connection metrics for the given chain ID"). AddParamPath("", "chainID", "ChainID (base58)"). - AddResponse(http.StatusOK, "Chain Metrics", chainExample, nil) + AddResponse(http.StatusOK, "Chain metrics", chainExample, nil) } func addChainConsensusMetricsEndpoints(adm echoswagger.ApiGroup, cms *chainMetricsService) { @@ -103,12 +104,33 @@ func addChainConsensusMetricsEndpoints(adm echoswagger.ApiGroup, cms *chainMetri TimeTransactionPosted: time.Time{}, TimeTransactionSeen: time.Time{}, TimeCompleted: time.Time{}, + + CurrentStateIndex: 0, } adm.GET(routes.GetChainConsensusWorkflowStatus(":chainID"), cms.handleGetChainConsensusWorkflowStatus). SetSummary("Get chain state statistics for the given chain ID"). AddParamPath("", "chainID", "ChainID (base58)"). - AddResponse(http.StatusOK, "Chain Stats", example, nil) + AddResponse(http.StatusOK, "Chain consensus stats", example, nil). + AddResponse(http.StatusNotFound, "Chain consensus hasn't been created", nil, nil) +} + +func addChainConcensusPipeMetricsEndpoints(adm echoswagger.ApiGroup, cms *chainMetricsService) { + example := &model.ConsensusPipeMetrics{ + EventStateTransitionMsgPipeSize: 0, + EventSignedResultMsgPipeSize: 0, + EventSignedResultAckMsgPipeSize: 0, + EventInclusionStateMsgPipeSize: 0, + EventACSMsgPipeSize: 0, + EventVMResultMsgPipeSize: 0, + EventTimerMsgPipeSize: 0, + } + + adm.GET(routes.GetChainConsensusPipeMetrics(":chainID"), cms.handleGetChainConsensusPipeMetrics). + SetSummary("Get consensus pipe metrics"). + AddParamPath("", "chainID", "CHAINid (base58)"). + AddResponse(http.StatusOK, "Chain consensus pipe metrics", example, nil). + AddResponse(http.StatusNotFound, "Chain consensus hasn't been created", nil, nil) } type chainMetricsService struct { @@ -143,11 +165,27 @@ func (cssT *chainMetricsService) handleGetChainConsensusWorkflowStatus(c echo.Co return err } status := theChain.GetConsensusWorkflowStatus() + if status == nil { + return c.NoContent(http.StatusNotFound) + } statusModel := model.NewConsensusWorkflowStatus(status) return c.JSON(http.StatusOK, statusModel) } +func (cssT *chainMetricsService) handleGetChainConsensusPipeMetrics(c echo.Context) error { + theChain, err := cssT.getChain(c) + if err != nil { + return err + } + pipeMetrics := theChain.GetConsensusPipeMetrics() + if pipeMetrics == nil { + return c.NoContent(http.StatusNotFound) + } + pipeMetricsModel := model.NewConsensusPipeMetrics(pipeMetrics) + return c.JSON(http.StatusOK, pipeMetricsModel) +} + func (cssT *chainMetricsService) getChain(c echo.Context) (chain.Chain, error) { chainID, err := iscp.ChainIDFromBase58(c.Param("chainID")) if err != nil { diff --git a/packages/webapi/model/consensus_metrics.go b/packages/webapi/model/consensus_metrics.go index be1841eed4..588b3ab781 100644 --- a/packages/webapi/model/consensus_metrics.go +++ b/packages/webapi/model/consensus_metrics.go @@ -25,6 +25,8 @@ type ConsensusWorkflowStatus struct { TimeTransactionPosted time.Time `swagger:"desc(Shows when transaction was last posted to L1 in current consensus iteration)"` TimeTransactionSeen time.Time `swagger:"desc(Shows when algorithm last noted that transaction hadd been seen by L1 in current consensus iteration)"` TimeCompleted time.Time `swagger:"desc(Shows when algorithm was last completed in current consensus iteration)"` + + CurrentStateIndex uint32 `swagger:"desc(Shows current state index of the consensus)"` } func NewConsensusWorkflowStatus(status chain.ConsensusWorkflowStatus) *ConsensusWorkflowStatus { @@ -47,5 +49,29 @@ func NewConsensusWorkflowStatus(status chain.ConsensusWorkflowStatus) *Consensus TimeTransactionPosted: status.GetTransactionPostedTime(), TimeTransactionSeen: status.GetTransactionSeenTime(), TimeCompleted: status.GetCompletedTime(), + + CurrentStateIndex: status.GetCurrentStateIndex(), + } +} + +type ConsensusPipeMetrics struct { + EventStateTransitionMsgPipeSize int + EventSignedResultMsgPipeSize int + EventSignedResultAckMsgPipeSize int + EventInclusionStateMsgPipeSize int + EventACSMsgPipeSize int + EventVMResultMsgPipeSize int + EventTimerMsgPipeSize int +} + +func NewConsensusPipeMetrics(pipeMetrics chain.ConsensusPipeMetrics) *ConsensusPipeMetrics { + return &ConsensusPipeMetrics{ + EventStateTransitionMsgPipeSize: pipeMetrics.GetEventStateTransitionMsgPipeSize(), + EventSignedResultMsgPipeSize: pipeMetrics.GetEventSignedResultMsgPipeSize(), + EventSignedResultAckMsgPipeSize: pipeMetrics.GetEventSignedResultAckMsgPipeSize(), + EventInclusionStateMsgPipeSize: pipeMetrics.GetEventInclusionStateMsgPipeSize(), + EventACSMsgPipeSize: pipeMetrics.GetEventACSMsgPipeSize(), + EventVMResultMsgPipeSize: pipeMetrics.GetEventVMResultMsgPipeSize(), + EventTimerMsgPipeSize: pipeMetrics.GetEventTimerMsgPipeSize(), } } diff --git a/packages/webapi/request/request_test.go b/packages/webapi/request/request_test.go index ecf7553448..039c4a7233 100644 --- a/packages/webapi/request/request_test.go +++ b/packages/webapi/request/request_test.go @@ -76,6 +76,10 @@ func (m *mockedChain) GetConsensusWorkflowStatus() chain.ConsensusWorkflowStatus panic("implement me") } +func (m *mockedChain) GetConsensusPipeMetrics() chain.ConsensusPipeMetrics { + panic("implement me") +} + // private methods func createMockedGetChain(t *testing.T) chains.ChainProvider { diff --git a/packages/webapi/routes/routes.go b/packages/webapi/routes/routes.go index e7b741fbad..46901838f8 100644 --- a/packages/webapi/routes/routes.go +++ b/packages/webapi/routes/routes.go @@ -63,6 +63,10 @@ func GetChainConsensusWorkflowStatus(chainID string) string { return "/adm/chain/" + chainID + "/consensus/status" } +func GetChainConsensusPipeMetrics(chainID string) string { + return "/adm/chain/" + chainID + "/consensus/metrics/pipe" +} + func DKSharesPost() string { return "/adm/dks" } diff --git a/plugins/dashboard/plugin.go b/plugins/dashboard/plugin.go index e0c703b325..668961427a 100644 --- a/plugins/dashboard/plugin.go +++ b/plugins/dashboard/plugin.go @@ -131,6 +131,14 @@ func (w *waspServices) GetChainConsensusWorkflowStatus(chainID *iscp.ChainID) (c return ch.GetConsensusWorkflowStatus(), nil } +func (w *waspServices) GetChainConsensusPipeMetrics(chainID *iscp.ChainID) (chain.ConsensusPipeMetrics, error) { + ch := chains.AllChains().Get(chainID) + if ch == nil { + return nil, echo.NewHTTPError(http.StatusNotFound, "Chain not found") + } + return ch.GetConsensusPipeMetrics(), nil +} + func (w *waspServices) CallView(chainID *iscp.ChainID, scName, funName string, params dict.Dict) (dict.Dict, error) { ch := chains.AllChains().Get(chainID) if ch == nil { diff --git a/plugins/wasmtimevm/plugin.go b/plugins/wasmtimevm/plugin.go index 20fb213f41..d9ab88d15c 100644 --- a/plugins/wasmtimevm/plugin.go +++ b/plugins/wasmtimevm/plugin.go @@ -10,7 +10,7 @@ import ( "github.com/iotaledger/hive.go/node" "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/vm/vmtypes" - "github.com/iotaledger/wasp/packages/vm/wasmproc" + "github.com/iotaledger/wasp/packages/wasmvm/wasmhost" "github.com/iotaledger/wasp/plugins/processors" ) @@ -30,7 +30,7 @@ func configure(_ *node.Plugin) { err := processors.Config.RegisterVMType(vmtypes.WasmTime, func(binary []byte) (iscp.VMProcessor, error) { // TODO (via config?) pass non-default timeout for WasmTime processor like this: // WasmTimeout = 3 * time.Second - return wasmproc.GetProcessor(binary, log) + return wasmhost.GetProcessor(binary, log) }) if err != nil { log.Panicf("%v: %v", pluginName, err) diff --git a/tools/cluster/tests/wasm/inccounter_bg.wasm b/tools/cluster/tests/wasm/inccounter_bg.wasm index 8f2f783f82..a1883fafa0 100644 Binary files a/tools/cluster/tests/wasm/inccounter_bg.wasm and b/tools/cluster/tests/wasm/inccounter_bg.wasm differ diff --git a/tools/evm-server/wasp-evm.nomad.tpl b/tools/evm-server/wasp-evm.nomad.tpl index f1cd533e3f..eee1ecd7bb 100644 --- a/tools/evm-server/wasp-evm.nomad.tpl +++ b/tools/evm-server/wasp-evm.nomad.tpl @@ -68,7 +68,8 @@ job "iscp-evm-server" { "evm", "jsonrpc", "-d", - "--chainid=1074", + "--chainid", + "1074", "-l=0.0.0.0:$${NOMAD_PORT_evm}", ] ports = [ diff --git a/tools/evm-server/waypoint.hcl b/tools/evm-server/waypoint.hcl index b9b464d5ed..92f46fc9e8 100644 --- a/tools/evm-server/waypoint.hcl +++ b/tools/evm-server/waypoint.hcl @@ -8,7 +8,6 @@ labels = { "team" = "iscp" } variable "chainid" { type = string - default = "jiCuv7Z4bYqAU8baSyCJP6HAxw8wC1YUYi722GibYPWW" } variable "wallet_seed" { diff --git a/tools/schema/generator/clientbase.go b/tools/schema/generator/clientbase.go index 4ccbf673c2..b71826abcd 100644 --- a/tools/schema/generator/clientbase.go +++ b/tools/schema/generator/clientbase.go @@ -1,10 +1,11 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package generator import ( "fmt" "os" - - "github.com/iotaledger/wasp/tools/schema/model" ) type ClientBase struct { @@ -31,27 +32,9 @@ func (g *ClientBase) Generate() error { } func (g *ClientBase) generateCode() error { - err := g.createSourceFile("events", !g.s.CoreContracts) - if err != nil { - return err - } - err = g.createSourceFile("service", true) + err := g.createSourceFile("events", len(g.s.Events) != 0) if err != nil { return err } - if !g.s.CoreContracts { - return g.generateFuncs(g.appendEvents) - } - return nil -} - -func (g *ClientBase) appendEvents(existing model.StringMap) { - for _, g.currentEvent = range g.s.Events { - name := g.s.ContractName + capitalize(g.currentEvent.Name) - if existing[name] == "" { - g.log("currentEvent: " + g.currentEvent.Name) - g.setMultiKeyValues("evtName", g.currentEvent.Name) - g.emit("funcSignature") - } - } + return g.createSourceFile("service", true) } diff --git a/tools/schema/generator/emitter.go b/tools/schema/generator/emitter.go index 85310d21e5..b84a02df07 100644 --- a/tools/schema/generator/emitter.go +++ b/tools/schema/generator/emitter.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package generator import ( @@ -20,6 +23,7 @@ const ( KeyEvents = "events" KeyExist = "exist" KeyFunc = "func" + KeyFuncs = "funcs" KeyInit = "init" KeyMandatory = "mandatory" KeyMap = "map" @@ -209,7 +213,7 @@ func (g *GenBase) emitEachMandatoryField(template string) { mandatoryFields := make([]*model.Field, 0) for _, g.currentField = range g.currentFunc.Params { fld := g.currentField - if !fld.Optional && fld.TypeID != 0 && !fld.Array && fld.MapKey == "" { + if !fld.Optional && fld.BaseType && !fld.Array && fld.MapKey == "" { mandatoryFields = append(mandatoryFields, g.currentField) } } @@ -267,7 +271,7 @@ func (g *GenBase) emitIf(line string) { case KeyArray: condition = g.currentField.Array case KeyBaseType: - condition = g.currentField.TypeID != 0 + condition = g.currentField.BaseType case KeyCore: condition = g.s.CoreContracts case KeyEvent: @@ -278,6 +282,8 @@ func (g *GenBase) emitIf(line string) { condition = g.newTypes[g.keys[KeyProxy]] case KeyFunc: condition = g.keys["kind"] == KeyFunc + case KeyFuncs: + condition = len(g.s.Funcs) != 0 case KeyInit: condition = g.currentFunc.Name == KeyInit case KeyMandatory: @@ -402,10 +408,17 @@ func (g *GenBase) setFieldKeys(pad bool, maxCamelLength, maxSnakeLength int) { } g.setMultiKeyValues("fldName", g.currentField.Name) g.setMultiKeyValues("fldType", g.currentField.Type) + g.setMultiKeyValues("fldMapKey", g.currentField.MapKey) + + isArray := "" + if g.currentField.Array { + isArray = "true" + } + g.keys["fldIsArray"] = isArray + g.keys["fldIsMap"] = g.currentField.MapKey g.keys["fldAlias"] = g.currentField.Alias g.keys["fldComment"] = g.currentField.Comment - g.keys["fldMapKey"] = g.currentField.MapKey g.keys["fldIndex"] = strconv.Itoa(g.currentField.KeyID) if pad { @@ -446,7 +459,7 @@ func (g *GenBase) setFuncKeys(pad bool, maxCamelLength, maxSnakeLength int) { comment = grant[index:] grant = strings.TrimSpace(grant[:index]) } - g.keys["funcAccess"] = grant + g.setMultiKeyValues("funcAccess", grant) g.keys["funcAccessComment"] = comment if pad { diff --git a/tools/schema/generator/generator.go b/tools/schema/generator/generator.go index 106ed72eb9..190c45486d 100644 --- a/tools/schema/generator/generator.go +++ b/tools/schema/generator/generator.go @@ -153,10 +153,6 @@ func (g *GenBase) generateCode() error { if err != nil { return err } - err = g.createSourceFile("keys", !g.s.CoreContracts) - if err != nil { - return err - } err = g.createSourceFile("events", len(g.s.Events) != 0) if err != nil { return err diff --git a/tools/schema/generator/goclienttemplates/alltemplates.go b/tools/schema/generator/goclienttemplates/alltemplates.go index 351de3f721..bd0ffb6c6f 100644 --- a/tools/schema/generator/goclienttemplates/alltemplates.go +++ b/tools/schema/generator/goclienttemplates/alltemplates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package goclienttemplates import "github.com/iotaledger/wasp/tools/schema/model" @@ -13,7 +16,6 @@ var Templates = []map[string]string{ config, // always first one common, eventsGo, - funcsGo, serviceGo, } @@ -163,6 +165,6 @@ var common = map[string]string{ "clientHeader": ` package $package$+client -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmclient" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" `, } diff --git a/tools/schema/generator/goclienttemplates/events.go b/tools/schema/generator/goclienttemplates/events.go index feabf1b3d1..5229a116c0 100644 --- a/tools/schema/generator/goclienttemplates/events.go +++ b/tools/schema/generator/goclienttemplates/events.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package goclienttemplates var eventsGo = map[string]string{ @@ -5,14 +8,37 @@ var eventsGo = map[string]string{ "events.go": ` $#emit clientHeader -var EventHandlers = map[string]func([]string) { +var $pkgName$+Handlers = map[string]func(*$PkgName$+Events, []string) { $#each events eventHandler } + +type $PkgName$+Events struct { +$#each events eventHandlerMember +} + +func (h *$PkgName$+Events) CallHandler(topic string, params []string) { + handler := $pkgName$+Handlers[topic] + if handler != nil { + handler(h, params) + } +} +$#each events funcSignature $#each events eventClass +`, + // ******************************* + "eventHandlerMember": ` + $evtName func(e *Event$EvtName) +`, + // ******************************* + "funcSignature": ` + +func (h *$PkgName$+Events) On$PkgName$EvtName(handler func(e *Event$EvtName)) { + h.$evtName = handler +} `, // ******************************* "eventHandler": ` - "$package.$evtName": on$PkgName$EvtName$+Thunk, + "$package.$evtName": func(evt *$PkgName$+Events, msg []string) { evt.on$PkgName$EvtName$+Thunk(msg) }, `, // ******************************* "eventClass": ` @@ -22,11 +48,14 @@ type Event$EvtName struct { $#each event eventClassField } -func on$PkgName$EvtName$+Thunk(message []string) { +func (h *$PkgName$+Events) on$PkgName$EvtName$+Thunk(message []string) { + if h.$evtName == nil { + return + } e := &Event$EvtName{} e.Init(message) $#each event eventHandlerField - On$PkgName$EvtName(e) + h.$evtName(e) } `, // ******************************* diff --git a/tools/schema/generator/goclienttemplates/funcs.go b/tools/schema/generator/goclienttemplates/funcs.go deleted file mode 100644 index ca29c3d132..0000000000 --- a/tools/schema/generator/goclienttemplates/funcs.go +++ /dev/null @@ -1,15 +0,0 @@ -package goclienttemplates - -var funcsGo = map[string]string{ - // ******************************* - "funcs.go": ` -$#emit clientHeader -$#each events funcSignature -`, - // ******************************* - "funcSignature": ` - -func On$PkgName$EvtName(event *Event$EvtName) { -} -`, -} diff --git a/tools/schema/generator/goclienttemplates/service.go b/tools/schema/generator/goclienttemplates/service.go index 9dc96e37d6..a889c4f591 100644 --- a/tools/schema/generator/goclienttemplates/service.go +++ b/tools/schema/generator/goclienttemplates/service.go @@ -1,9 +1,18 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package goclienttemplates var serviceGo = map[string]string{ // ******************************* "service.go": ` -$#emit clientHeader +package $package$+client +$#if funcs emitContract +`, + // ******************************* + "emitContract": ` + +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmclient" const ( $#each params constArg @@ -20,16 +29,11 @@ type $PkgName$+Service struct { func New$PkgName$+Service(cl *wasmclient.ServiceClient, chainID string) (*$PkgName$+Service, error) { s := &$PkgName$+Service{} -$#set eventHandlers EventHandlers -$#if core noEventHandlers - err := s.Service.Init(cl, chainID, 0x$hscName, $eventHandlers) + err := s.Service.Init(cl, chainID, 0x$hscName) return s, err } +$#if events newEventHandler $#each func serviceFunction -`, - // ******************************* - "noEventHandlers": ` -$#set eventHandlers nil `, // ******************************* "constArg": ` @@ -38,6 +42,13 @@ $#set eventHandlers nil // ******************************* "constRes": ` Res$FldName = "$fldAlias" +`, + // ******************************* + "newEventHandler": ` + +func (s *$PkgName$+Service) NewEventHandler() *$PkgName$+Events { + return &$PkgName$+Events{} +} `, // ******************************* "funcStruct": ` @@ -118,7 +129,11 @@ $#each result callResultGetter `, // ******************************* "callResultGetter": ` -$#if map callResultGetterMap callResultGetterBasic +$#if map callResultGetterMap callResultGetter2 +`, + // ******************************* + "callResultGetter2": ` +$#if basetype callResultGetterBasic callResultGetterStruct `, // ******************************* "callResultGetterMap": ` @@ -126,7 +141,7 @@ $#if map callResultGetterMap callResultGetterBasic func (r *$FuncName$+Results) $FldName() map[$fldKeyLangType]$fldLangType { res := make(map[$fldKeyLangType]$fldLangType) r.res.ForEach(func(key []byte, val []byte) { - res[r.res.To$fldMapKey(key)] = r.res.To$FldType(val) + res[r.res.To$FldMapKey(key)] = r.res.To$FldType(val) }) return res } @@ -138,6 +153,13 @@ $#if mandatory else callResultOptional func (r *$FuncName$+Results) $FldName() $fldLangType { return r.res.To$FldType(r.res.Get(Res$FldName)) } +`, + // ******************************* + "callResultGetterStruct": ` + +func (r *$FuncName$+Results) $FldName() *$FldType { + return New$FldType$+FromBytes(r.res.Get(Res$FldName)) +} `, // ******************************* "callResultOptional": ` diff --git a/tools/schema/generator/gotemplates/alltemplates.go b/tools/schema/generator/gotemplates/alltemplates.go index 3fe42a9552..371642b18b 100644 --- a/tools/schema/generator/gotemplates/alltemplates.go +++ b/tools/schema/generator/gotemplates/alltemplates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates import "github.com/iotaledger/wasp/tools/schema/model" @@ -16,7 +19,6 @@ var Templates = []map[string]string{ contractGo, eventsGo, funcsGo, - keysGo, libGo, mainGo, paramsGo, @@ -29,96 +31,44 @@ var Templates = []map[string]string{ var TypeDependent = model.StringMapMap{ "fldLangType": { - "Address": "wasmlib.ScAddress", - "AgentID": "wasmlib.ScAgentID", + "Address": "wasmtypes.ScAddress", + "AgentID": "wasmtypes.ScAgentID", "Bool": "bool", - "ChainID": "wasmlib.ScChainID", - "Color": "wasmlib.ScColor", - "Hash": "wasmlib.ScHash", - "Hname": "wasmlib.ScHname", + "Bytes": "[]byte", + "ChainID": "wasmtypes.ScChainID", + "Color": "wasmtypes.ScColor", + "Hash": "wasmtypes.ScHash", + "Hname": "wasmtypes.ScHname", "Int8": "int8", "Int16": "int16", "Int32": "int32", "Int64": "int64", - "RequestID": "wasmlib.ScRequestID", + "RequestID": "wasmtypes.ScRequestID", "String": "string", "Uint8": "uint8", "Uint16": "uint16", "Uint32": "uint32", "Uint64": "uint64", }, - "fldTypeID": { - "Address": "wasmlib.TYPE_ADDRESS", - "AgentID": "wasmlib.TYPE_AGENT_ID", - "Bool": "wasmlib.TYPE_BOOL", - "ChainID": "wasmlib.TYPE_CHAIN_ID", - "Color": "wasmlib.TYPE_COLOR", - "Hash": "wasmlib.TYPE_HASH", - "Hname": "wasmlib.TYPE_HNAME", - "Int8": "wasmlib.TYPE_INT8", - "Int16": "wasmlib.TYPE_INT16", - "Int32": "wasmlib.TYPE_INT32", - "Int64": "wasmlib.TYPE_INT64", - "RequestID": "wasmlib.TYPE_REQUEST_ID", - "String": "wasmlib.TYPE_STRING", - "Uint8": "wasmlib.TYPE_INT8", - "Uint16": "wasmlib.TYPE_INT16", - "Uint32": "wasmlib.TYPE_INT32", - "Uint64": "wasmlib.TYPE_INT64", - "": "wasmlib.TYPE_BYTES", - }, - "fldToKey32": { - "Address": "key.KeyID()", - "AgentID": "key.KeyID()", - "Bool": "???cannot use Bool as map key", - "ChainID": "key.KeyID()", - "Color": "key.KeyID()", - "Hash": "key.KeyID()", - "Hname": "key.KeyID()", - "Int8": "wasmlib.GetKeyIDFromUint64(uint64(key), 1)", - "Int16": "wasmlib.GetKeyIDFromUint64(uint64(key), 2)", - "Int32": "wasmlib.GetKeyIDFromUint64(uint64(key), 4)", - "Int64": "wasmlib.GetKeyIDFromUint64(uint64(key), 8)", - "RequestID": "key.KeyID()", - "String": "wasmlib.Key(key).KeyID()", - "Uint8": "wasmlib.GetKeyIDFromUint64(uint64(key), 1)", - "Uint16": "wasmlib.GetKeyIDFromUint64(uint64(key), 2)", - "Uint32": "wasmlib.GetKeyIDFromUint64(uint64(key), 4)", - "Uint64": "wasmlib.GetKeyIDFromUint64(key, 8)", - }, } var common = map[string]string{ // ******************************* - "initGlobals": ` -$#set arrayTypeID wasmlib.TYPE_ARRAY -$#if core setArrayTypeID + "importWasmLib": ` +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" `, // ******************************* - "setArrayTypeID": ` -$#set arrayTypeID wasmlib.TYPE_ARRAY16 + "importWasmTypes": ` +import "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" `, // ******************************* "goPackage": ` package $package -`, - // ******************************* - "importWasmLib": ` - -import "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" `, // ******************************* "goHeader": ` $#emit goPackage + $#emit importWasmLib -`, - // ******************************* - "setVarType": ` -$#set varType wasmlib.TYPE_MAP -$#if array setVarTypeArray -`, - // ******************************* - "setVarTypeArray": ` -$#set varType $arrayTypeID|$fldTypeID `, } diff --git a/tools/schema/generator/gotemplates/consts.go b/tools/schema/generator/gotemplates/consts.go index 81474d2c23..86ebbfbbcd 100644 --- a/tools/schema/generator/gotemplates/consts.go +++ b/tools/schema/generator/gotemplates/consts.go @@ -1,26 +1,24 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var constsGo = map[string]string{ // ******************************* "consts.go": ` -$#emit goHeader +$#emit goPackage + +$#emit importWasmTypes const ( ScName = "$scName" ScDescription = "$scDesc" - HScName = wasmlib.ScHname(0x$hscName) + HScName = wasmtypes.ScHname(0x$hscName) ) $#if params constParams $#if results constResults $#if state constState - -const ( -$#each func constFunc -) - -const ( -$#each func constHFunc -) +$#if funcs constFuncs `, // ******************************* "constParams": ` @@ -45,6 +43,17 @@ const ( $#set constPrefix State $#each state constField ) +`, + // ******************************* + "constFuncs": ` + +const ( +$#each func constFunc +) + +const ( +$#each func constHFunc +) `, // ******************************* "constField": ` @@ -56,6 +65,6 @@ $#each state constField `, // ******************************* "constHFunc": ` - H$Kind$FuncName$funcPad = wasmlib.ScHname(0x$hFuncName) + H$Kind$FuncName$funcPad = wasmtypes.ScHname(0x$hFuncName) `, } diff --git a/tools/schema/generator/gotemplates/contract.go b/tools/schema/generator/gotemplates/contract.go index 773be9aeec..c67816e571 100644 --- a/tools/schema/generator/gotemplates/contract.go +++ b/tools/schema/generator/gotemplates/contract.go @@ -1,9 +1,18 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var contractGo = map[string]string{ // ******************************* "contract.go": ` -$#emit goHeader +$#emit goPackage +$#if funcs emitContract +`, + // ******************************* + "emitContract": ` + +$#emit importWasmLib $#each func FuncNameCall type Funcs struct{} @@ -35,41 +44,82 @@ $#if result ImmutableFuncNameResults $#emit setupInitFunc func (sc Funcs) $FuncName(ctx wasmlib.Sc$Kind$+CallContext) *$FuncName$+Call { -$#set paramsID nil -$#set resultsID nil -$#if param setParamsID -$#if result setResultsID -$#if ptrs setPtrs noPtrs +$#set thisView f.Func +$#if func setThisView +$#set complex $false +$#if param setComplex +$#if result setComplex +$#if complex initComplex initSimple } +`, + // ******************************* + "setThisView": ` +$#set thisView &f.Func.ScView +`, + // ******************************* + "setComplex": ` +$#set complex $true `, // ******************************* "coreOnload": ` -func OnLoad() { - exports := wasmlib.NewScExports() +var exportMap = wasmlib.ScExportMap{ + Names: []string{ +$#each func coreExportName + }, + Funcs: []wasmlib.ScFuncContextFunction{ $#each func coreExportFunc + }, + Views: []wasmlib.ScViewContextFunction{ +$#each func coreExportView + }, +} + +func OnLoad(index int32) { + if index >= 0 { + panic("Calling core contract?") + } + + wasmlib.ScExportsExport(&exportMap) } `, // ******************************* - "coreExportFunc": ` - exports.Add$Kind($Kind$FuncName, wasmlib.$Kind$+Error) + "initComplex": ` + f := &$FuncName$+Call{Func: wasmlib.NewSc$initFunc$Kind(ctx, HScName, H$Kind$FuncName)} +$#if param initParams +$#if result initResults + return f `, // ******************************* - "setPtrs": ` - f := &$FuncName$+Call{Func: wasmlib.NewSc$initFunc$Kind(ctx, HScName, H$Kind$FuncName$initMap)} - f.Func.SetPtrs($paramsID, $resultsID) - return f + "initParams": ` + f.Params.proxy = wasmlib.NewCallParamsProxy($thisView) +`, + // ******************************* + "initResults": ` + wasmlib.NewCallResultsProxy($thisView, &f.Results.proxy) +`, + // ******************************* + "initSimple": ` + return &$FuncName$+Call{Func: wasmlib.NewSc$initFunc$Kind(ctx, HScName, H$Kind$FuncName)} +`, + // ******************************* + "coreExportName": ` + $Kind$FuncName, +`, + // ******************************* + "coreExportFunc": ` +$#if func coreExportFuncThunk `, // ******************************* - "setParamsID": ` -$#set paramsID &f.Params.id + "coreExportFuncThunk": ` + wasmlib.$Kind$+Error, `, // ******************************* - "setResultsID": ` -$#set resultsID &f.Results.id + "coreExportView": ` +$#if view coreExportViewThunk `, // ******************************* - "noPtrs": ` - return &$FuncName$+Call{Func: wasmlib.NewSc$initFunc$Kind(ctx, HScName, H$Kind$FuncName$initMap)} + "coreExportViewThunk": ` + wasmlib.$Kind$+Error, `, } diff --git a/tools/schema/generator/gotemplates/events.go b/tools/schema/generator/gotemplates/events.go index a52a60fb7b..42244cb117 100644 --- a/tools/schema/generator/gotemplates/events.go +++ b/tools/schema/generator/gotemplates/events.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var eventsGo = map[string]string{ @@ -5,6 +8,7 @@ var eventsGo = map[string]string{ "events.go": ` //nolint:gocritic $#emit goHeader +$#emit importWasmTypes $#set TypeName $Package$+Events type $TypeName struct { @@ -13,14 +17,14 @@ $#each events eventFunc `, // ******************************* "eventFunc": ` -$#set params $#set separator +$#set params $#each event eventParam func (e $TypeName) $EvtName($params) { - wasmlib.NewEventEncoder("$package.$evtName"). + evt := wasmlib.NewEventEncoder("$package.$evtName") $#each event eventEmit - Emit() + evt.Emit() } `, // ******************************* @@ -30,6 +34,6 @@ $#set separator , `, // ******************************* "eventEmit": ` - $FldType($fldName). + evt.Encode(wasmtypes.$FldType$+ToString($fldName)) `, } diff --git a/tools/schema/generator/gotemplates/funcs.go b/tools/schema/generator/gotemplates/funcs.go index e235163ff6..f9290d93f7 100644 --- a/tools/schema/generator/gotemplates/funcs.go +++ b/tools/schema/generator/gotemplates/funcs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var funcsGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/keys.go b/tools/schema/generator/gotemplates/keys.go deleted file mode 100644 index e8528d83bc..0000000000 --- a/tools/schema/generator/gotemplates/keys.go +++ /dev/null @@ -1,40 +0,0 @@ -package gotemplates - -var keysGo = map[string]string{ - // ******************************* - "keys.go": ` -$#emit goHeader - -const ( -$#set constPrefix Param -$#each params constFieldIdx - -$#set constPrefix Result -$#each results constFieldIdx - -$#set constPrefix State -$#each state constFieldIdx -) - -const keyMapLen = $maxIndex - -var keyMap = [keyMapLen]wasmlib.Key{ -$#set constPrefix Param -$#each params constFieldKey -$#set constPrefix Result -$#each results constFieldKey -$#set constPrefix State -$#each state constFieldKey -} - -var idxMap [keyMapLen]wasmlib.Key32 -`, - // ******************************* - "constFieldIdx": ` - Idx$constPrefix$FldName$fldPad = $fldIndex -`, - // ******************************* - "constFieldKey": ` - $constPrefix$FldName, -`, -} diff --git a/tools/schema/generator/gotemplates/lib.go b/tools/schema/generator/gotemplates/lib.go index ec5822463c..e60a438171 100644 --- a/tools/schema/generator/gotemplates/lib.go +++ b/tools/schema/generator/gotemplates/lib.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var libGo = map[string]string{ @@ -6,19 +9,47 @@ var libGo = map[string]string{ //nolint:dupl $#emit goHeader -func OnLoad() { - exports := wasmlib.NewScExports() +var exportMap = wasmlib.ScExportMap{ + Names: []string{ +$#each func libExportName + }, + Funcs: []wasmlib.ScFuncContextFunction{ $#each func libExportFunc + }, + Views: []wasmlib.ScViewContextFunction{ +$#each func libExportView + }, +} - for i, key := range keyMap { - idxMap[i] = key.KeyID() +func OnLoad(index int32) { + if index >= 0 { + wasmlib.ScExportsCall(index, &exportMap) + return } + + wasmlib.ScExportsExport(&exportMap) } $#each func libThunk +`, + // ******************************* + "libExportName": ` + $Kind$FuncName, `, // ******************************* "libExportFunc": ` - exports.Add$Kind($Kind$FuncName,$funcPad $kind$FuncName$+Thunk) +$#if func libExportFuncThunk +`, + // ******************************* + "libExportFuncThunk": ` + $kind$FuncName$+Thunk, +`, + // ******************************* + "libExportView": ` +$#if view libExportViewThunk +`, + // ******************************* + "libExportViewThunk": ` + $kind$FuncName$+Thunk, `, // ******************************* "libThunk": ` @@ -33,17 +64,23 @@ $#if view ImmutablePackageState func $kind$FuncName$+Thunk(ctx wasmlib.Sc$Kind$+Context) { ctx.Log("$package.$kind$FuncName") -$#emit accessCheck +$#if result initResultDict f := &$FuncName$+Context{ $#if param ImmutableFuncNameParamsInit $#if result MutableFuncNameResultsInit $#if func MutablePackageStateInit $#if view ImmutablePackageStateInit } +$#emit accessCheck $#each mandatory requireMandatory $kind$FuncName(ctx, f) +$#if result returnResultDict ctx.Log("$package.$kind$FuncName ok") } +`, + // ******************************* + "initResultDict": ` + results := wasmlib.NewScDict() `, // ******************************* "PackageEvents": ` @@ -60,7 +97,7 @@ $#if events PackageEventsExist // ******************************* "ImmutableFuncNameParamsInit": ` Params: Immutable$FuncName$+Params{ - id: wasmlib.OBJ_ID_PARAMS, + proxy: wasmlib.NewParamsProxy(), }, `, // ******************************* @@ -70,7 +107,7 @@ $#if events PackageEventsExist // ******************************* "MutableFuncNameResultsInit": ` Results: Mutable$FuncName$+Results{ - id: wasmlib.OBJ_ID_RESULTS, + proxy: results.AsProxy(), }, `, // ******************************* @@ -80,7 +117,7 @@ $#if events PackageEventsExist // ******************************* "MutablePackageStateInit": ` State: Mutable$Package$+State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, `, // ******************************* @@ -90,14 +127,17 @@ $#if events PackageEventsExist // ******************************* "ImmutablePackageStateInit": ` State: Immutable$Package$+State{ - id: wasmlib.OBJ_ID_STATE, + proxy: wasmlib.NewStateProxy(), }, +`, + // ******************************* + "returnResultDict": ` + ctx.Results(results) `, // ******************************* "requireMandatory": ` ctx.Require(f.Params.$FldName().Exists(), "missing mandatory $fldName") `, - // ******************************* "accessCheck": ` $#set accessFinalize accessOther @@ -132,7 +172,7 @@ $#set accessFinalize accessDone // ******************************* "accessOther": ` $#if funcAccessComment accessComment - access := ctx.State().GetAgentID(wasmlib.Key("$funcAccess")) + access := f.State.$FuncAccess() ctx.Require(access.Exists(), "access not set: $funcAccess") ctx.Require(ctx.Caller() == access.Value(), "no permission") diff --git a/tools/schema/generator/gotemplates/main.go b/tools/schema/generator/gotemplates/main.go index 9a2798990b..1f3ad54efa 100644 --- a/tools/schema/generator/gotemplates/main.go +++ b/tools/schema/generator/gotemplates/main.go @@ -1,24 +1,35 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var mainGo = map[string]string{ // ******************************* "../main.go": ` +//go:build wasm // +build wasm package main -import "github.com/iotaledger/wasp/packages/vm/wasmvmhost" +import "github.com/iotaledger/wasp/packages/wasmvm/wasmvmhost" import "$module/go/$package" func main() { } +func init() { + wasmvmhost.ConnectWasmHost() +} + +//export on_call +func onCall(index int32) { + $package.OnLoad(index) +} + //export on_load func onLoad() { - h := &wasmvmhost.WasmVMHost{} - h.ConnectWasmHost() - $package.OnLoad() + $package.OnLoad(-1) } `, } diff --git a/tools/schema/generator/gotemplates/params.go b/tools/schema/generator/gotemplates/params.go index 447ee0580f..aa5d1159dd 100644 --- a/tools/schema/generator/gotemplates/params.go +++ b/tools/schema/generator/gotemplates/params.go @@ -1,9 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var paramsGo = map[string]string{ // ******************************* "params.go": ` -$#emit goHeader +$#emit goPackage + +$#emit importWasmTypes $#each func paramsFunc `, // ******************************* @@ -24,7 +29,7 @@ $#set TypeName $mut$FuncName$+Params $#each param proxyContainers type $TypeName struct { - id int32 + proxy wasmtypes.Proxy } $#each param proxyMethods `, diff --git a/tools/schema/generator/gotemplates/proxy.go b/tools/schema/generator/gotemplates/proxy.go index 4e4725c4fb..72b5263cd2 100644 --- a/tools/schema/generator/gotemplates/proxy.go +++ b/tools/schema/generator/gotemplates/proxy.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var proxyGo = map[string]string{ @@ -8,14 +11,7 @@ $#if map typedefProxyMap `, // ******************************* "proxyMethods": ` -$#set varID wasmlib.KeyID($Kind$FldName) -$#if init setInitVarID -$#if core setCoreVarID $#if array proxyArray proxyMethods2 -`, - // ******************************* - "setInitVarID": ` -$#set varID idxMap[Idx$Kind$FldName] `, // ******************************* "proxyMethods2": ` @@ -23,22 +19,13 @@ $#if map proxyMap proxyMethods3 `, // ******************************* "proxyMethods3": ` -$#if basetype proxyBaseType proxyMethods4 -`, - // ******************************* - "proxyMethods4": ` -$#if typedef proxyTypeDef proxyStruct -`, - // ******************************* - "setCoreVarID": ` -$#set varID wasmlib.KeyID($Kind$FldName) +$#if basetype proxyBaseType proxyOtherType `, // ******************************* "proxyArray": ` func (s $TypeName) $FldName() ArrayOf$mut$FldType { - arrID := wasmlib.GetObjectID(s.id, $varID, $arrayTypeID|$fldTypeID) - return ArrayOf$mut$FldType{objID: arrID} + return ArrayOf$mut$FldType{proxy: s.proxy.Root($Kind$FldName)} } `, // ******************************* @@ -48,39 +35,30 @@ $#if this proxyMapThis proxyMapOther // ******************************* "proxyMapThis": ` -func (s $TypeName) $FldName() Map$fldMapKey$+To$mut$FldType { - return Map$fldMapKey$+To$mut$FldType{objID: s.id} +func (s $TypeName) $FldName() Map$FldMapKey$+To$mut$FldType { + //nolint:gosimple + return Map$FldMapKey$+To$mut$FldType{proxy: s.proxy} } `, // ******************************* "proxyMapOther": ` -func (s $TypeName) $FldName() Map$fldMapKey$+To$mut$FldType { - mapID := wasmlib.GetObjectID(s.id, $varID, wasmlib.TYPE_MAP) - return Map$fldMapKey$+To$mut$FldType{objID: mapID} +func (s $TypeName) $FldName() Map$FldMapKey$+To$mut$FldType { + return Map$FldMapKey$+To$mut$FldType{proxy: s.proxy.Root($Kind$FldName)} } `, // ******************************* "proxyBaseType": ` -func (s $TypeName) $FldName() wasmlib.Sc$mut$FldType { - return wasmlib.NewSc$mut$FldType(s.id, $varID) -} -`, - // ******************************* - "proxyTypeDef": ` -$#emit setVarType - -func (s $TypeName) $OldName() $mut$OldType { - subID := wasmlib.GetObjectID(s.id, $varID, $varType) - return $mut$OldType{objID: subID} +func (s $TypeName) $FldName() wasmtypes.Sc$mut$FldType { + return wasmtypes.NewSc$mut$FldType(s.proxy.Root($Kind$FldName)) } `, // ******************************* - "proxyStruct": ` + "proxyOtherType": ` func (s $TypeName) $FldName() $mut$FldType { - return $mut$FldType{objID: s.id, keyID: $varID} + return $mut$FldType{proxy: s.proxy.Root($Kind$FldName)} } `, } diff --git a/tools/schema/generator/gotemplates/results.go b/tools/schema/generator/gotemplates/results.go index 1b46ecd872..0a2d77d8f3 100644 --- a/tools/schema/generator/gotemplates/results.go +++ b/tools/schema/generator/gotemplates/results.go @@ -1,9 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var resultsGo = map[string]string{ // ******************************* "results.go": ` -$#emit goHeader +$#emit goPackage + +$#emit importWasmTypes $#each func resultsFunc `, // ******************************* @@ -24,7 +29,7 @@ $#set TypeName $mut$FuncName$+Results $#each result proxyContainers type $TypeName struct { - id int32 + proxy wasmtypes.Proxy } $#each result proxyMethods `, diff --git a/tools/schema/generator/gotemplates/state.go b/tools/schema/generator/gotemplates/state.go index 5cd4a0bd9a..d5891c169e 100644 --- a/tools/schema/generator/gotemplates/state.go +++ b/tools/schema/generator/gotemplates/state.go @@ -1,10 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var stateGo = map[string]string{ // ******************************* "state.go": ` $#emit goPackage -$#if state importWasmLib + +$#emit importWasmTypes $#set Kind State $#set mut Immutable $#emit stateProxyStruct @@ -17,7 +21,7 @@ $#set TypeName $mut$Package$+State $#each state proxyContainers type $TypeName struct { - id int32 + proxy wasmtypes.Proxy } $#if mut stateProxyImmutableFunc $#each state proxyMethods diff --git a/tools/schema/generator/gotemplates/structs.go b/tools/schema/generator/gotemplates/structs.go index af2a356a87..dd459384a5 100644 --- a/tools/schema/generator/gotemplates/structs.go +++ b/tools/schema/generator/gotemplates/structs.go @@ -1,9 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var structsGo = map[string]string{ // ******************************* "structs.go": ` -$#emit goHeader +$#emit goPackage + +$#emit importWasmTypes $#each structs structType `, // ******************************* @@ -13,18 +18,18 @@ type $StrName struct { $#each struct structField } -func New$StrName$+FromBytes(bytes []byte) *$StrName { - decode := wasmlib.NewBytesDecoder(bytes) +func New$StrName$+FromBytes(buf []byte) *$StrName { + dec := wasmtypes.NewWasmDecoder(buf) data := &$StrName$+{} $#each struct structDecode - decode.Close() + dec.Close() return data } func (o *$StrName) Bytes() []byte { - return wasmlib.NewBytesEncoder(). + enc := wasmtypes.NewWasmEncoder() $#each struct structEncode - Data() + return enc.Buf() } $#set mut Immutable $#emit structMethods @@ -37,42 +42,41 @@ $#emit structMethods `, // ******************************* "structDecode": ` - data.$FldName$fldPad = decode.$FldType() + data.$FldName$fldPad = wasmtypes.$FldType$+Decode(dec) `, // ******************************* "structEncode": ` - $FldType(o.$FldName). + wasmtypes.$FldType$+Encode(enc, o.$FldName) `, // ******************************* "structMethods": ` type $mut$StrName struct { - objID int32 - keyID wasmlib.Key32 + proxy wasmtypes.Proxy } $#if mut structMethodDelete func (o $mut$StrName) Exists() bool { - return wasmlib.Exists(o.objID, o.keyID, wasmlib.TYPE_BYTES) + return o.proxy.Exists() } $#if mut structMethodSetValue func (o $mut$StrName) Value() *$StrName { - return New$StrName$+FromBytes(wasmlib.GetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES)) + return New$StrName$+FromBytes(o.proxy.Get()) } `, // ******************************* "structMethodDelete": ` func (o $mut$StrName) Delete() { - wasmlib.DelKey(o.objID, o.keyID, wasmlib.TYPE_BYTES) + o.proxy.Delete() } `, // ******************************* "structMethodSetValue": ` func (o $mut$StrName) SetValue(value *$StrName) { - wasmlib.SetBytes(o.objID, o.keyID, wasmlib.TYPE_BYTES, value.Bytes()) + o.proxy.Set(value.Bytes()) } `, } diff --git a/tools/schema/generator/gotemplates/typedefs.go b/tools/schema/generator/gotemplates/typedefs.go index ed5fcb42e9..77c3b1aca7 100644 --- a/tools/schema/generator/gotemplates/typedefs.go +++ b/tools/schema/generator/gotemplates/typedefs.go @@ -1,9 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var typedefsGo = map[string]string{ // ******************************* "typedefs.go": ` -$#emit goHeader +$#emit goPackage + +$#emit importWasmTypes $#each typedef typedefProxy `, // ******************************* @@ -33,97 +38,86 @@ $#if exist else typedefProxyArrayNew "typedefProxyArrayNew": ` type $proxy struct { - objID int32 + proxy wasmtypes.Proxy } -$#if mut typedefProxyArrayClear +$#if mut typedefProxyArrayMut -func (a $proxy) Length() int32 { - return wasmlib.GetLength(a.objID) +func (a $proxy) Length() uint32 { + return a.proxy.Length() } $#if basetype typedefProxyArrayNewBaseType typedefProxyArrayNewOtherType $#set exist $proxy `, // ******************************* - "typedefProxyArrayClear": ` + "typedefProxyArrayMut": ` +$#if basetype typedefProxyArrayAppendBaseType typedefProxyArrayAppendOtherType func (a $proxy) Clear() { - wasmlib.Clear(a.objID) + a.proxy.ClearArray() } `, // ******************************* - "typedefProxyArrayNewBaseType": ` + "typedefProxyArrayAppendBaseType": ` -func (a $proxy) Get$FldType(index int32) wasmlib.Sc$mut$FldType { - return wasmlib.NewSc$mut$FldType(a.objID, wasmlib.Key32(index)) +func (a $proxy) Append$FldType() wasmtypes.Sc$mut$FldType { + return wasmtypes.NewSc$mut$FldType(a.proxy.Append()) } `, // ******************************* - "typedefProxyArrayNewOtherType": ` -$#if typedef typedefProxyArrayNewOtherTypeTypeDef typedefProxyArrayNewOtherTypeStruct + "typedefProxyArrayAppendOtherType": ` + +func (a $proxy) Append$FldType() $mut$FldType { + return $mut$FldType{proxy: a.proxy.Append()} +} `, // ******************************* - "typedefProxyArrayNewOtherTypeTypeDef": ` -$#emit setVarType + "typedefProxyArrayNewBaseType": ` -func (a $proxy) Get$OldType(index int32) $mut$OldType { - subID := wasmlib.GetObjectID(a.objID, wasmlib.Key32(index), $varType) - return $mut$OldType{objID: subID} +func (a $proxy) Get$FldType(index uint32) wasmtypes.Sc$mut$FldType { + return wasmtypes.NewSc$mut$FldType(a.proxy.Index(index)) } `, // ******************************* - "typedefProxyArrayNewOtherTypeStruct": ` + "typedefProxyArrayNewOtherType": ` -func (a $proxy) Get$FldType(index int32) $mut$FldType { - return $mut$FldType{objID: a.objID, keyID: wasmlib.Key32(index)} +func (a $proxy) Get$FldType(index uint32) $mut$FldType { + return $mut$FldType{proxy: a.proxy.Index(index)} } `, // ******************************* "typedefProxyMap": ` -$#set proxy Map$fldMapKey$+To$mut$FldType +$#set proxy Map$FldMapKey$+To$mut$FldType $#if exist else typedefProxyMapNew `, // ******************************* "typedefProxyMapNew": ` type $proxy struct { - objID int32 + proxy wasmtypes.Proxy } -$#if mut typedefProxyMapClear +$#if mut typedefProxyMapMut $#if basetype typedefProxyMapNewBaseType typedefProxyMapNewOtherType $#set exist $proxy `, // ******************************* - "typedefProxyMapClear": ` + "typedefProxyMapMut": ` func (m $proxy) Clear() { - wasmlib.Clear(m.objID) + m.proxy.ClearMap() } `, // ******************************* "typedefProxyMapNewBaseType": ` -func (m $proxy) Get$FldType(key $fldKeyLangType) wasmlib.Sc$mut$FldType { - return wasmlib.NewSc$mut$FldType(m.objID, $fldKeyToKey32) +func (m $proxy) Get$FldType(key $fldKeyLangType) wasmtypes.Sc$mut$FldType { + return wasmtypes.NewSc$mut$FldType(m.proxy.Key(wasmtypes.$FldMapKey$+ToBytes(key))) } `, // ******************************* "typedefProxyMapNewOtherType": ` -$#if typedef typedefProxyMapNewOtherTypeTypeDef typedefProxyMapNewOtherTypeStruct -`, - // ******************************* - "typedefProxyMapNewOtherTypeTypeDef": ` -$#emit setVarType - -func (m $proxy) Get$OldType(key $oldKeyLangType) $mut$OldType { - subID := wasmlib.GetObjectID(m.objID, $oldKeyToKey32, $varType) - return $mut$OldType{objID: subID} -} -`, - // ******************************* - "typedefProxyMapNewOtherTypeStruct": ` func (m $proxy) Get$FldType(key $fldKeyLangType) $mut$FldType { - return $mut$FldType{objID: m.objID, keyID: $fldKeyToKey32} + return $mut$FldType{proxy: m.proxy.Key(wasmtypes.$FldMapKey$+ToBytes(key))} } `, } diff --git a/tools/schema/generator/rstemplates/alltemplates.go b/tools/schema/generator/rstemplates/alltemplates.go index 0764cd0b16..b2f0979971 100644 --- a/tools/schema/generator/rstemplates/alltemplates.go +++ b/tools/schema/generator/rstemplates/alltemplates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates import "github.com/iotaledger/wasp/tools/schema/model" @@ -17,7 +20,6 @@ var Templates = []map[string]string{ contractRs, eventsRs, funcsRs, - keysRs, libRs, modRs, paramsRs, @@ -33,6 +35,7 @@ var TypeDependent = model.StringMapMap{ "Address": "ScAddress", "AgentID": "ScAgentID", "Bool": "bool", + "Bytes": "Vec", "ChainID": "ScChainID", "Color": "ScColor", "Hash": "ScHash", @@ -48,49 +51,11 @@ var TypeDependent = model.StringMapMap{ "Uint32": "u32", "Uint64": "u64", }, - "fldTypeID": { - "Address": "TYPE_ADDRESS", - "AgentID": "TYPE_AGENT_ID", - "Bool": "TYPE_BOOL", - "ChainID": "TYPE_CHAIN_ID", - "Color": "TYPE_COLOR", - "Hash": "TYPE_HASH", - "Hname": "TYPE_HNAME", - "Int8": "TYPE_INT8", - "Int16": "TYPE_INT16", - "Int32": "TYPE_INT32", - "Int64": "TYPE_INT64", - "RequestID": "TYPE_REQUEST_ID", - "String": "TYPE_STRING", - "Uint8": "TYPE_INT8", - "Uint16": "TYPE_INT16", - "Uint32": "TYPE_INT32", - "Uint64": "TYPE_INT64", - "": "TYPE_BYTES", - }, - "fldToKey32": { - "Address": "key.get_key_id()", - "AgentID": "key.get_key_id()", - "Bool": "???cannot use Bool as map key", - "ChainID": "key.get_key_id()", - "Color": "key.get_key_id()", - "Hash": "key.get_key_id()", - "Hname": "key.get_key_id()", - "Int8": "get_key_id_from_uint64(key as u64, 1)", - "Int16": "get_key_id_from_uint64(key as u64, 2)", - "Int32": "get_key_id_from_uint64(key as u64, 4)", - "Int64": "get_key_id_from_uint64(key as u64, 8)", - "RequestID": "key.get_key_id()", - "String": "key.get_key_id()", - "Uint8": "get_key_id_from_uint64(key as u64, 1)", - "Uint16": "get_key_id_from_uint64(key as u64, 2)", - "Uint32": "get_key_id_from_uint64(key as u64, 4)", - "Uint64": "get_key_id_from_uint64(key, 8)", - }, "fldParamLangType": { "Address": "ScAddress", "AgentID": "ScAgentID", "Bool": "bool", + "Bytes": "[u8]", "ChainID": "ScChainID", "Color": "ScColor", "Hash": "ScHash", @@ -108,6 +73,7 @@ var TypeDependent = model.StringMapMap{ }, "fldRef": { "Address": "&", + "Bytes": "&", "AgentID": "&", "ChainID": "&", "Color": "&", @@ -120,82 +86,23 @@ var TypeDependent = model.StringMapMap{ var common = map[string]string{ // ******************************* "initGlobals": ` -$#set arrayTypeID TYPE_ARRAY $#set crate -$#if core setArrayTypeID +$#if core setCrate `, // ******************************* - "setArrayTypeID": ` -$#set arrayTypeID TYPE_ARRAY16 + "setCrate": ` $#set crate (crate) -`, - // ******************************* - "rsHeader": ` -$#if core useCrate useWasmLib -`, - // ******************************* - "modEvents": ` -mod events; -`, - // ******************************* - "modParams": ` -mod params; -`, - // ******************************* - "modResults": ` -mod results; -`, - // ******************************* - "modStructs": ` -mod structs; -`, - // ******************************* - "modTypeDefs": ` -mod typedefs; -`, - // ******************************* - "useCrate": ` -use crate::*; `, // ******************************* "useCoreContract": ` use crate::$package::*; `, // ******************************* - "useEvents": ` -use crate::events::*; -`, - // ******************************* - "useHost": ` -use crate::host::*; -`, - // ******************************* - "useParams": ` -use crate::params::*; -`, - // ******************************* - "useResults": ` -use crate::results::*; -`, - // ******************************* - "useStructs": ` -use crate::structs::*; -`, - // ******************************* - "useTypeDefs": ` -use crate::typedefs::*; + "useCrate": ` +use crate::*; `, // ******************************* "useWasmLib": ` use wasmlib::*; -`, - // ******************************* - "setVarType": ` -$#set varType TYPE_MAP -$#if array setVarTypeArray -`, - // ******************************* - "setVarTypeArray": ` -$#set varType $arrayTypeID | $fldTypeID `, } diff --git a/tools/schema/generator/rstemplates/cargotoml.go b/tools/schema/generator/rstemplates/cargotoml.go index c7d245bed1..07a3866647 100644 --- a/tools/schema/generator/rstemplates/cargotoml.go +++ b/tools/schema/generator/rstemplates/cargotoml.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var cargoToml = map[string]string{ diff --git a/tools/schema/generator/rstemplates/consts.go b/tools/schema/generator/rstemplates/consts.go index 95913a1a8d..dc9ed0d16f 100644 --- a/tools/schema/generator/rstemplates/consts.go +++ b/tools/schema/generator/rstemplates/consts.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var constsRs = map[string]string{ @@ -13,10 +16,7 @@ pub const HSC_NAME : ScHname = ScHname(0x$hscName); $#if params constParams $#if results constResults $#if state constState - -$#each func constFunc - -$#each func constHFunc +$#if funcs constFuncs `, // ******************************* "constParams": ` @@ -35,6 +35,13 @@ $#each results constField $#set constPrefix STATE_ $#each state constField +`, + // ******************************* + "constFuncs": ` + +$#each func constFunc + +$#each func constHFunc `, // ******************************* "constField": ` diff --git a/tools/schema/generator/rstemplates/contract.go b/tools/schema/generator/rstemplates/contract.go index f43624e968..56a851e2ca 100644 --- a/tools/schema/generator/rstemplates/contract.go +++ b/tools/schema/generator/rstemplates/contract.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var contractRs = map[string]string{ @@ -5,10 +8,8 @@ var contractRs = map[string]string{ "contract.rs": ` #![allow(dead_code)] -use std::ptr; - -$#if core useCrate useWasmLib -$#if core useCoreContract contractUses +$#if core useCoreContract useWasmLib +use crate::*; $#each func FuncNameCall pub struct ScFuncs { @@ -18,13 +19,6 @@ impl ScFuncs { $#set separator $false $#each func FuncNameForCall } -`, - // ******************************* - "contractUses": ` - -use crate::consts::*; -$#if params useParams -$#if results useResults `, // ******************************* "FuncNameCall": ` @@ -49,11 +43,7 @@ $#if result ImmutableFuncNameResults $#emit setupInitFunc $#if separator newline $#set separator $true - pub fn $func_name(_ctx: & dyn Sc$Kind$+CallContext) -> $FuncName$+Call { -$#set paramsID ptr::null_mut() -$#set resultsID ptr::null_mut() -$#if param setParamsID -$#if result setResultsID + pub fn $func_name(_ctx: &dyn Sc$Kind$+CallContext) -> $FuncName$+Call { $#if ptrs setPtrs noPtrs } `, @@ -64,24 +54,25 @@ $#if ptrs setPtrs noPtrs $#if param FuncNameParamsInit $#if result FuncNameResultsInit }; - f.func.set_ptrs($paramsID, $resultsID); +$#if param FuncNameParamsLink +$#if result FuncNameResultsLink f `, // ******************************* "FuncNameParamsInit": ` - params: Mutable$FuncName$+Params { id: 0 }, + params: Mutable$FuncName$+Params { proxy: Proxy::nil() }, `, // ******************************* "FuncNameResultsInit": ` - results: Immutable$FuncName$+Results { id: 0 }, + results: Immutable$FuncName$+Results { proxy: Proxy::nil() }, `, // ******************************* - "setParamsID": ` -$#set paramsID &mut f.params.id + "FuncNameParamsLink": ` + Sc$initFunc$Kind::link_params(&mut f.params.proxy, &f.func); `, // ******************************* - "setResultsID": ` -$#set resultsID &mut f.results.id + "FuncNameResultsLink": ` + Sc$initFunc$Kind::link_results(&mut f.results.proxy, &f.func); `, // ******************************* "noPtrs": ` diff --git a/tools/schema/generator/rstemplates/events.go b/tools/schema/generator/rstemplates/events.go index 6d203ac398..3db4cac20d 100644 --- a/tools/schema/generator/rstemplates/events.go +++ b/tools/schema/generator/rstemplates/events.go @@ -1,11 +1,15 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var eventsRs = map[string]string{ // ******************************* "events.rs": ` #![allow(dead_code)] +#![allow(unused_mut)] -use wasmlib::*; +$#if core useCrate useWasmLib $#set TypeName $Package$+Events pub struct $TypeName { @@ -17,29 +21,23 @@ $#each events eventFunc `, // ******************************* "eventFunc": ` +$#set separator $#set params $#each event eventParam pub fn $evt_name(&self$params) { -$#if event eventParams eventParamNone + let mut evt = EventEncoder::new("$package.$evtName"); +$#each event eventEmit + evt.emit(); } `, // ******************************* "eventParam": ` $#set params $params, $fld_name: $fldRef$fldParamLangType -`, - // ******************************* - "eventParamNone": ` - EventEncoder::new("$package.$evtName").emit(); -`, - // ******************************* - "eventParams": ` - let mut encoder = EventEncoder::new("$package.$evtName"); -$#each event eventEmit - encoder.emit(); +$#set separator , `, // ******************************* "eventEmit": ` - encoder.$fld_type($fldRef$fld_name); + evt.encode(&$fld_type$+_to_string($fldRef$fld_name)); `, } diff --git a/tools/schema/generator/rstemplates/funcs.go b/tools/schema/generator/rstemplates/funcs.go index 0ea4fb2983..706de90107 100644 --- a/tools/schema/generator/rstemplates/funcs.go +++ b/tools/schema/generator/rstemplates/funcs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var funcsRs = map[string]string{ @@ -6,8 +9,6 @@ var funcsRs = map[string]string{ use wasmlib::*; use crate::*; -$#if structs useStructs -$#if typedefs useTypeDefs $#each func funcSignature `, // ******************************* diff --git a/tools/schema/generator/rstemplates/keys.go b/tools/schema/generator/rstemplates/keys.go deleted file mode 100644 index 6099c04e59..0000000000 --- a/tools/schema/generator/rstemplates/keys.go +++ /dev/null @@ -1,48 +0,0 @@ -package rstemplates - -var keysRs = map[string]string{ - // ******************************* - "keys.rs": ` -#![allow(dead_code)] - -use wasmlib::*; - -use crate::*; - -$#set constPrefix PARAM_ -$#each params constFieldIdx - -$#set constPrefix RESULT_ -$#each results constFieldIdx - -$#set constPrefix STATE_ -$#each state constFieldIdx - -pub const KEY_MAP_LEN: usize = $maxIndex; - -pub const KEY_MAP: [&str; KEY_MAP_LEN] = [ -$#set constPrefix PARAM_ -$#each params constFieldKey -$#set constPrefix RESULT_ -$#each results constFieldKey -$#set constPrefix STATE_ -$#each state constFieldKey -]; - -pub static mut IDX_MAP: [Key32; KEY_MAP_LEN] = [Key32(0); KEY_MAP_LEN]; - -pub fn idx_map(idx: usize) -> Key32 { - unsafe { - IDX_MAP[idx] - } -} -`, - // ******************************* - "constFieldIdx": ` -pub(crate) const IDX_$constPrefix$FLD_NAME$fld_pad : usize = $fldIndex; -`, - // ******************************* - "constFieldKey": ` - $constPrefix$FLD_NAME, -`, -} diff --git a/tools/schema/generator/rstemplates/lib.go b/tools/schema/generator/rstemplates/lib.go index b7b599232f..ce07de3491 100644 --- a/tools/schema/generator/rstemplates/lib.go +++ b/tools/schema/generator/rstemplates/lib.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var libRs = map[string]string{ @@ -8,42 +11,86 @@ var libRs = map[string]string{ use $package::*; use wasmlib::*; -use wasmlib::host::*; use crate::consts::*; -$#if events useEvents -use crate::keys::*; -$#if params useParams -$#if results useResults +$#set moduleName events +$#if events useModule +$#set moduleName params +$#if params useModule +$#set moduleName results +$#if results useModule use crate::state::*; +$#set moduleName structs +$#if structs useModule +$#set moduleName typedefs +$#if typedefs useModule mod consts; mod contract; -$#if events modEvents -mod keys; -$#if params modParams -$#if results modResults +$#set moduleName events +$#if events modModule +$#set moduleName params +$#if params modModule +$#set moduleName results +$#if results modModule mod state; -$#if structs modStructs -$#if typedefs modTypeDefs +$#set moduleName structs +$#if structs modModule +$#set moduleName typedefs +$#if typedefs modModule + mod $package; -#[no_mangle] -fn on_load() { - let exports = ScExports::new(); +const EXPORT_MAP: ScExportMap = ScExportMap { + names: &[ +$#each func libExportName + ], + funcs: &[ $#each func libExportFunc + ], + views: &[ +$#each func libExportView + ], +}; - unsafe { - for i in 0..KEY_MAP_LEN { - IDX_MAP[i] = get_key_id_from_string(KEY_MAP[i]); - } - } +#[no_mangle] +fn on_call(index: i32) { + ScExports::call(index, &EXPORT_MAP); +} + +#[no_mangle] +fn on_load() { + ScExports::export(&EXPORT_MAP); } $#each func libThunk +`, + // ******************************* + "useModule": ` +use crate::$moduleName::*; +`, + // ******************************* + "modModule": ` +mod $moduleName; +`, + // ******************************* + "libExportName": ` + $KIND$+_$FUNC_NAME, `, // ******************************* "libExportFunc": ` - exports.add_$kind($KIND$+_$FUNC_NAME,$func_pad $kind$+_$func_name$+_thunk); +$#if func libExportFuncThunk +`, + // ******************************* + "libExportFuncThunk": ` + $kind$+_$func_name$+_thunk, +`, + // ******************************* + "libExportView": ` +$#if view libExportViewThunk +`, + // ******************************* + "libExportViewThunk": ` + $kind$+_$func_name$+_thunk, `, // ******************************* "libThunk": ` @@ -58,7 +105,6 @@ $#if view ImmutablePackageState fn $kind$+_$func_name$+_thunk(ctx: &Sc$Kind$+Context) { ctx.log("$package.$kind$FuncName"); -$#emit accessCheck let f = $FuncName$+Context { $#if func PackageEventsInit $#if param ImmutableFuncNameParamsInit @@ -66,8 +112,10 @@ $#if result MutableFuncNameResultsInit $#if func MutablePackageStateInit $#if view ImmutablePackageStateInit }; +$#emit accessCheck $#each mandatory requireMandatory $kind$+_$func_name(ctx, &f); +$#if result returnResultDict ctx.log("$package.$kind$FuncName ok"); } `, @@ -93,9 +141,7 @@ $#if events PackageEventsInitExist `, // ******************************* "ImmutableFuncNameParamsInit": ` - params: Immutable$FuncName$+Params { - id: OBJ_ID_PARAMS, - }, + params: Immutable$FuncName$+Params { proxy: params_proxy() }, `, // ******************************* "MutableFuncNameResults": ` @@ -103,9 +149,7 @@ $#if events PackageEventsInitExist `, // ******************************* "MutableFuncNameResultsInit": ` - results: Mutable$FuncName$+Results { - id: OBJ_ID_RESULTS, - }, + results: Mutable$FuncName$+Results { proxy: results_proxy() }, `, // ******************************* "MutablePackageState": ` @@ -113,9 +157,7 @@ $#if events PackageEventsInitExist `, // ******************************* "MutablePackageStateInit": ` - state: Mutable$Package$+State { - id: OBJ_ID_STATE, - }, + state: Mutable$Package$+State { proxy: state_proxy() }, `, // ******************************* "ImmutablePackageState": ` @@ -123,15 +165,16 @@ $#if events PackageEventsInitExist `, // ******************************* "ImmutablePackageStateInit": ` - state: Immutable$Package$+State { - id: OBJ_ID_STATE, - }, + state: Immutable$Package$+State { proxy: state_proxy() }, +`, + // ******************************* + "returnResultDict": ` + ctx.results(&f.results.proxy.kv_store); `, // ******************************* "requireMandatory": ` ctx.require(f.params.$fld_name().exists(), "missing mandatory $fldName"); `, - // ******************************* "accessCheck": ` $#set accessFinalize accessOther @@ -166,7 +209,7 @@ $#set accessFinalize accessDone // ******************************* "accessOther": ` $#if funcAccessComment accessComment - let access = ctx.state().get_agent_id("$funcAccess"); + let access = f.state.$func_access(); ctx.require(access.exists(), "access not set: $funcAccess"); ctx.require(ctx.caller() == access.value(), "no permission"); diff --git a/tools/schema/generator/rstemplates/mod.go b/tools/schema/generator/rstemplates/mod.go index bfa74afb9f..0116b50783 100644 --- a/tools/schema/generator/rstemplates/mod.go +++ b/tools/schema/generator/rstemplates/mod.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var modRs = map[string]string{ @@ -7,12 +10,28 @@ var modRs = map[string]string{ pub use consts::*; pub use contract::*; -pub use params::*; -pub use results::*; +$#set moduleName params +$#if params pubUseModule +$#set moduleName results +$#if results pubUseModule +$#set moduleName structs +$#if structs pubUseModule pub mod consts; pub mod contract; -pub mod params; -pub mod results; +$#set moduleName params +$#if params pubModModule +$#set moduleName results +$#if results pubModModule +$#set moduleName structs +$#if structs pubModModule +`, + // ******************************* + "pubUseModule": ` +pub use $moduleName::*; +`, + // ******************************* + "pubModModule": ` +pub mod $moduleName; `, } diff --git a/tools/schema/generator/rstemplates/params.go b/tools/schema/generator/rstemplates/params.go index 81c9a9253b..773fb3aa3d 100644 --- a/tools/schema/generator/rstemplates/params.go +++ b/tools/schema/generator/rstemplates/params.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var paramsRs = map[string]string{ @@ -6,19 +9,9 @@ var paramsRs = map[string]string{ #![allow(dead_code)] #![allow(unused_imports)] -$#if core useCrate useWasmLib -$#if core useCoreContract -$#if core useHost paramsUses -$#each func paramsFunc -`, - // ******************************* - "paramsUses": ` -use wasmlib::host::*; - +$#if core useCoreContract useWasmLib use crate::*; -use crate::keys::*; -$#if structs useStructs -$#if typedefs useTypeDefs +$#each func paramsFunc `, // ******************************* "paramsFunc": ` @@ -37,9 +30,9 @@ $#if param paramsProxyStruct $#set TypeName $mut$FuncName$+Params $#each param proxyContainers -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $TypeName { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl $TypeName { diff --git a/tools/schema/generator/rstemplates/proxy.go b/tools/schema/generator/rstemplates/proxy.go index b391095c33..c6aea5842b 100644 --- a/tools/schema/generator/rstemplates/proxy.go +++ b/tools/schema/generator/rstemplates/proxy.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var proxyRs = map[string]string{ @@ -10,14 +13,7 @@ $#if map typedefProxyMap "proxyMethods": ` $#if separator newline $#set separator $true -$#set varID $Kind$FLD_NAME.get_key_id() -$#if init setInitVarID -$#if core setCoreVarID $#if array proxyArray proxyMethods2 -`, - // ******************************* - "setInitVarID": ` -$#set varID idx_map(IDX_$Kind$FLD_NAME) `, // ******************************* "proxyMethods2": ` @@ -25,21 +21,12 @@ $#if map proxyMap proxyMethods3 `, // ******************************* "proxyMethods3": ` -$#if basetype proxyBaseType proxyMethods4 -`, - // ******************************* - "proxyMethods4": ` -$#if typedef proxyTypeDef proxyStruct -`, - // ******************************* - "setCoreVarID": ` -$#set varID $Kind$FLD_NAME.get_key_id() +$#if basetype proxyBaseType proxyOtherType `, // ******************************* "proxyArray": ` pub fn $fld_name(&self) -> ArrayOf$mut$FldType { - let arr_id = get_object_id(self.id, $varID, $arrayTypeID | $fldTypeID); - ArrayOf$mut$FldType { obj_id: arr_id } + ArrayOf$mut$FldType { proxy: self.proxy.root($Kind$FLD_NAME) } } `, // ******************************* @@ -48,35 +35,26 @@ $#if this proxyMapThis proxyMapOther `, // ******************************* "proxyMapThis": ` - pub fn $fld_name(&self) -> Map$fldMapKey$+To$mut$FldType { - Map$fldMapKey$+To$mut$FldType { obj_id: self.id } + pub fn $fld_name(&self) -> Map$FldMapKey$+To$mut$FldType { + Map$FldMapKey$+To$mut$FldType { proxy: self.proxy.clone() } } `, // ******************************* "proxyMapOther": ` - pub fn $fld_name(&self) -> Map$fldMapKey$+To$mut$FldType { - let map_id = get_object_id(self.id, $varID, TYPE_MAP); - Map$fldMapKey$+To$mut$FldType { obj_id: map_id } + pub fn $fld_name(&self) -> Map$FldMapKey$+To$mut$FldType { + Map$FldMapKey$+To$mut$FldType { proxy: self.proxy.root($Kind$FLD_NAME) } } `, // ******************************* "proxyBaseType": ` pub fn $fld_name(&self) -> Sc$mut$FldType { - Sc$mut$FldType::new(self.id, $varID) - } -`, - // ******************************* - "proxyTypeDef": ` -$#emit setVarType - pub fn $old_name(&self) -> $mut$OldType { - let sub_id = get_object_id(self.id, $varID, $varType); - $mut$OldType { obj_id: sub_id } + Sc$mut$FldType::new(self.proxy.root($Kind$FLD_NAME)) } `, // ******************************* - "proxyStruct": ` + "proxyOtherType": ` pub fn $fld_name(&self) -> $mut$FldType { - $mut$FldType { obj_id: self.id, key_id: $varID } + $mut$FldType { proxy: self.proxy.root($Kind$FLD_NAME) } } `, } diff --git a/tools/schema/generator/rstemplates/results.go b/tools/schema/generator/rstemplates/results.go index 80b11aa37a..46afa124f1 100644 --- a/tools/schema/generator/rstemplates/results.go +++ b/tools/schema/generator/rstemplates/results.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var resultsRs = map[string]string{ @@ -6,19 +9,9 @@ var resultsRs = map[string]string{ #![allow(dead_code)] #![allow(unused_imports)] -$#if core useCrate useWasmLib -$#if core useCoreContract -$#if core useHost resultsUses -$#each func resultsFunc -`, - // ******************************* - "resultsUses": ` -use wasmlib::host::*; - +$#if core useCoreContract useWasmLib use crate::*; -use crate::keys::*; -$#if structs useStructs -$#if typedefs useTypeDefs +$#each func resultsFunc `, // ******************************* "resultsFunc": ` @@ -37,9 +30,9 @@ $#if result resultsProxyStruct $#set TypeName $mut$FuncName$+Results $#each result proxyContainers -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $TypeName { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } impl $TypeName { diff --git a/tools/schema/generator/rstemplates/state.go b/tools/schema/generator/rstemplates/state.go index b5aa40fd8a..ae844f6e9f 100644 --- a/tools/schema/generator/rstemplates/state.go +++ b/tools/schema/generator/rstemplates/state.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var stateRs = map[string]string{ @@ -7,12 +10,8 @@ var stateRs = map[string]string{ #![allow(unused_imports)] use wasmlib::*; -use wasmlib::host::*; use crate::*; -use crate::keys::*; -$#if structs useStructs -$#if typedefs useTypeDefs $#set Kind STATE_ $#set mut Immutable $#emit stateProxyStruct @@ -24,9 +23,9 @@ $#emit stateProxyStruct $#set TypeName $mut$Package$+State $#each state proxyContainers -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $TypeName { - pub(crate) id: i32, + pub(crate) proxy: Proxy, } $#if state stateProxyImpl `, @@ -43,7 +42,7 @@ $#each state proxyMethods "stateProxyImmutableFunc": ` $#set separator $true pub fn as_immutable(&self) -> Immutable$Package$+State { - Immutable$Package$+State { id: self.id } + Immutable$Package$+State { proxy: self.proxy.root("") } } `, } diff --git a/tools/schema/generator/rstemplates/structs.go b/tools/schema/generator/rstemplates/structs.go index 6d0e1fc499..6715b54009 100644 --- a/tools/schema/generator/rstemplates/structs.go +++ b/tools/schema/generator/rstemplates/structs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var structsRs = map[string]string{ @@ -6,9 +9,7 @@ var structsRs = map[string]string{ #![allow(dead_code)] #![allow(unused_imports)] -use wasmlib::*; -use wasmlib::host::*; -$#if typedefs useTypeDefs +$#if core useCrate useWasmLib $#each structs structType `, // ******************************* @@ -21,16 +22,16 @@ $#each struct structField impl $StrName { pub fn from_bytes(bytes: &[u8]) -> $StrName { - let mut decode = BytesDecoder::new(bytes); + let mut dec = WasmDecoder::new(bytes); $StrName { $#each struct structDecode } } pub fn to_bytes(&self) -> Vec { - let mut encode = BytesEncoder::new(); + let mut enc = WasmEncoder::new(); $#each struct structEncode - return encode.data(); + enc.buf() } } $#set mut Immutable @@ -44,37 +45,36 @@ $#emit structMethods `, // ******************************* "structDecode": ` - $fld_name$fld_pad : decode.$fld_type(), + $fld_name$fld_pad : $fld_type$+_decode(&mut dec), `, // ******************************* "structEncode": ` - encode.$fld_type($fldRef$+self.$fld_name); + $fld_type$+_encode(&mut enc, $fldRef$+self.$fld_name); `, // ******************************* "structMethods": ` -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $mut$StrName { - pub(crate) obj_id: i32, - pub(crate) key_id: Key32, + pub(crate) proxy: Proxy, } impl $mut$StrName { $#if mut structMethodDelete pub fn exists(&self) -> bool { - exists(self.obj_id, self.key_id, TYPE_BYTES) + self.proxy.exists() } $#if mut structMethodSetValue pub fn value(&self) -> $StrName { - $StrName::from_bytes(&get_bytes(self.obj_id, self.key_id, TYPE_BYTES)) + $StrName::from_bytes(&self.proxy.get()) } } `, // ******************************* "structMethodDelete": ` pub fn delete(&self) { - del_key(self.obj_id, self.key_id, TYPE_BYTES); + self.proxy.delete(); } `, @@ -82,7 +82,7 @@ $#if mut structMethodSetValue "structMethodSetValue": ` pub fn set_value(&self, value: &$StrName) { - set_bytes(self.obj_id, self.key_id, TYPE_BYTES, &value.to_bytes()); + self.proxy.set(&value.to_bytes()); } `, } diff --git a/tools/schema/generator/rstemplates/typedefs.go b/tools/schema/generator/rstemplates/typedefs.go index 06a3e60021..a62fbfb5ee 100644 --- a/tools/schema/generator/rstemplates/typedefs.go +++ b/tools/schema/generator/rstemplates/typedefs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var typedefsRs = map[string]string{ @@ -5,9 +8,8 @@ var typedefsRs = map[string]string{ "typedefs.rs": ` #![allow(dead_code)] -use wasmlib::*; -use wasmlib::host::*; -$#if structs useStructs +$#if core else useWasmLib +use crate::*; $#each typedef typedefProxy `, // ******************************* @@ -36,15 +38,15 @@ $#if exist else typedefProxyArrayNew // ******************************* "typedefProxyArrayNew": ` -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $proxy { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl $proxy { -$#if mut typedefProxyArrayClear - pub fn length(&self) -> i32 { - get_length(self.obj_id) +$#if mut typedefProxyArrayMut + pub fn length(&self) -> u32 { + self.proxy.length() } $#if basetype typedefProxyArrayNewBaseType typedefProxyArrayNewOtherType @@ -52,84 +54,76 @@ $#if basetype typedefProxyArrayNewBaseType typedefProxyArrayNewOtherType $#set exist $proxy `, // ******************************* - "typedefProxyArrayClear": ` - pub fn clear(&self) { - clear(self.obj_id); + "typedefProxyArrayMut": ` +$#if basetype typedefProxyArrayAppendBaseType typedefProxyArrayAppendOtherType + pub fn clear(&self) { + self.proxy.clear_array(); } `, // ******************************* - "typedefProxyArrayNewBaseType": ` - pub fn get_$fld_type(&self, index: i32) -> Sc$mut$FldType { - Sc$mut$FldType::new(self.obj_id, Key32(index)) - } + "typedefProxyArrayAppendBaseType": ` + pub fn append_$fld_type(&self) -> Sc$mut$FldType { + Sc$mut$FldType::new(self.proxy.append()) + } + `, // ******************************* - "typedefProxyArrayNewOtherType": ` -$#if typedef typedefProxyArrayNewOtherTypeTypeDef typedefProxyArrayNewOtherTypeStruct + "typedefProxyArrayAppendOtherType": ` + + pub fn append_$fld_type(&self) -> $mut$FldType { + $mut$FldType { proxy: self.proxy.append() } + } `, // ******************************* - "typedefProxyArrayNewOtherTypeTypeDef": ` -$#emit setVarType - pub fn get_$old_type(&self, index: i32) -> $mut$OldType { - let sub_id = get_object_id(self.obj_id, Key32(index), $varType); - $mut$OldType { obj_id: sub_id } - } + "typedefProxyArrayNewBaseType": ` + pub fn get_$fld_type(&self, index: u32) -> Sc$mut$FldType { + Sc$mut$FldType::new(self.proxy.index(index)) + } `, // ******************************* - "typedefProxyArrayNewOtherTypeStruct": ` - pub fn get_$fld_type(&self, index: i32) -> $mut$FldType { - $mut$FldType { obj_id: self.obj_id, key_id: Key32(index) } + "typedefProxyArrayNewOtherType": ` + + pub fn get_$fld_type(&self, index: u32) -> $mut$FldType { + $mut$FldType { proxy: self.proxy.index(index) } } `, // ******************************* "typedefProxyMap": ` -$#set proxy Map$fldMapKey$+To$mut$FldType +$#set proxy Map$FldMapKey$+To$mut$FldType $#if exist else typedefProxyMapNew `, // ******************************* "typedefProxyMapNew": ` -#[derive(Clone, Copy)] +#[derive(Clone)] pub struct $proxy { - pub(crate) obj_id: i32, + pub(crate) proxy: Proxy, } impl $proxy { -$#if mut typedefProxyMapClear +$#if mut typedefProxyMapMut $#if basetype typedefProxyMapNewBaseType typedefProxyMapNewOtherType } $#set exist $proxy `, // ******************************* - "typedefProxyMapClear": ` + "typedefProxyMapMut": ` pub fn clear(&self) { - clear(self.obj_id); + self.proxy.clear_map(); } `, // ******************************* "typedefProxyMapNewBaseType": ` pub fn get_$fld_type(&self, key: $fldKeyRef$fldKeyParamLangType) -> Sc$mut$FldType { - Sc$mut$FldType::new(self.obj_id, $fldKeyToKey32) + Sc$mut$FldType::new(self.proxy.key(&$fld_map_key$+_to_bytes(key))) } `, // ******************************* "typedefProxyMapNewOtherType": ` -$#if typedef typedefProxyMapNewOtherTypeTypeDef typedefProxyMapNewOtherTypeStruct -`, - // ******************************* - "typedefProxyMapNewOtherTypeTypeDef": ` -$#emit setVarType - pub fn get_$old_type(&self, key: $oldKeyRef$oldKeyParamLangType) -> $mut$OldType { - let sub_id = get_object_id(self.obj_id, $oldKeyToKey32, $varType); - $mut$OldType { obj_id: sub_id } - } -`, - // ******************************* - "typedefProxyMapNewOtherTypeStruct": ` pub fn get_$fld_type(&self, key: $fldKeyRef$fldKeyParamLangType) -> $mut$FldType { - $mut$FldType { obj_id: self.obj_id, key_id: $fldKeyToKey32 } + $mut$FldType { proxy: self.proxy.key(&$fld_map_key$+_to_bytes(key)) } } `, } diff --git a/tools/schema/generator/templates.go b/tools/schema/generator/templates.go index b4652457dd..aaee2053d6 100644 --- a/tools/schema/generator/templates.go +++ b/tools/schema/generator/templates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package generator import "github.com/iotaledger/wasp/tools/schema/model" @@ -36,7 +39,7 @@ import ( "testing" "$module/go/$package" - "github.com/iotaledger/wasp/packages/vm/wasmsolo" + "github.com/iotaledger/wasp/packages/wasmvm/wasmsolo" "github.com/stretchr/testify/require" ) @@ -48,12 +51,10 @@ func TestDeploy(t *testing.T) { // ******************************* "setupInitFunc": ` $#set initFunc -$#set initMap $#if init setInitFunc `, // ******************************* "setInitFunc": ` $#set initFunc Init -$#set initMap , keyMap[:], idxMap[:] `, } diff --git a/tools/schema/generator/tsclienttemplates/alltemplates.go b/tools/schema/generator/tsclienttemplates/alltemplates.go index fb9cfbe3b4..1114674454 100644 --- a/tools/schema/generator/tsclienttemplates/alltemplates.go +++ b/tools/schema/generator/tsclienttemplates/alltemplates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates import "github.com/iotaledger/wasp/tools/schema/model" @@ -13,7 +16,6 @@ var Templates = []map[string]string{ config, // always first one common, eventsTs, - funcsTs, indexTs, serviceTs, } @@ -103,7 +105,7 @@ import * as events from "./events" import * as service from "./service" `, // ******************************* - "importWasmLib": ` + "importWasmClient": ` import * as wasmclient from "wasmclient" `, } diff --git a/tools/schema/generator/tsclienttemplates/events.go b/tools/schema/generator/tsclienttemplates/events.go index b7bef5f608..71ed357a8f 100644 --- a/tools/schema/generator/tsclienttemplates/events.go +++ b/tools/schema/generator/tsclienttemplates/events.go @@ -1,19 +1,46 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var eventsTs = map[string]string{ // ******************************* "events.ts": ` -$#emit importWasmLib -import * as app from "./$package" +$#emit importWasmClient -export const eventHandlers: wasmclient.EventHandlers = new Map([ +const $pkgName$+Handlers = new Map void>([ $#each events eventHandler ]); + +export class $PkgName$+Events implements wasmclient.IEventHandler { +/* eslint-disable @typescript-eslint/no-empty-function */ +$#each events eventHandlerMember +/* eslint-enable @typescript-eslint/no-empty-function */ + + public callHandler(topic: string, params: string[]): void { + const handler = $pkgName$+Handlers.get(topic); + if (handler) { + handler(this, params); + } + } +$#each events funcSignature +} $#each events eventClass `, // ******************************* "eventHandler": ` - ["$package.$evtName", (msg: string[]) => app.on$PkgName$EvtName(new Event$EvtName(msg))], + ["$package.$evtName", (evt: $PkgName$+Events, msg: string[]) => evt.$evtName(new Event$EvtName(msg))], +`, + // ******************************* + "eventHandlerMember": ` + $evtName: (evt: Event$EvtName) => void = () => {}; +`, + // ******************************* + "funcSignature": ` + + public on$PkgName$EvtName(handler: (evt: Event$EvtName) => void): void { + this.$evtName = handler; + } `, // ******************************* "eventClass": ` @@ -22,7 +49,7 @@ export class Event$EvtName extends wasmclient.Event { $#each event eventClassField public constructor(msg: string[]) { - super(msg) + super(msg); $#each event eventHandlerField } } diff --git a/tools/schema/generator/tsclienttemplates/funcs.go b/tools/schema/generator/tsclienttemplates/funcs.go deleted file mode 100644 index 02e361eaf3..0000000000 --- a/tools/schema/generator/tsclienttemplates/funcs.go +++ /dev/null @@ -1,16 +0,0 @@ -package tsclienttemplates - -var funcsTs = map[string]string{ - // ******************************* - "funcs.ts": ` -$#emit importEvents -$#emit importService -$#each events funcSignature -`, - // ******************************* - "funcSignature": ` - -export function on$PkgName$EvtName(event: events.Event$EvtName): void { -} -`, -} diff --git a/tools/schema/generator/tsclienttemplates/index.go b/tools/schema/generator/tsclienttemplates/index.go index 5c075efe59..247d99bd9c 100644 --- a/tools/schema/generator/tsclienttemplates/index.go +++ b/tools/schema/generator/tsclienttemplates/index.go @@ -1,10 +1,16 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var indexTs = map[string]string{ // ******************************* "index.ts": ` -export * from "./$package"; -export * from "./events"; +$#if events exportEvents export * from "./service"; +`, + // ******************************* + "exportEvents": ` +export * from "./events"; `, } diff --git a/tools/schema/generator/tsclienttemplates/service.go b/tools/schema/generator/tsclienttemplates/service.go index e27327d93d..88163a688f 100644 --- a/tools/schema/generator/tsclienttemplates/service.go +++ b/tools/schema/generator/tsclienttemplates/service.go @@ -1,10 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var serviceTs = map[string]string{ // ******************************* "service.ts": ` -$#emit importWasmLib -$#if core else importEvents +$#emit importWasmClient +$#if events importEvents $#each params constArg @@ -16,16 +19,11 @@ $#each func funcStruct export class $PkgName$+Service extends wasmclient.Service { public constructor(cl: wasmclient.ServiceClient) { -$#set eventHandlers events.eventHandlers -$#if core noEventHandlers - super(cl, 0x$hscName, $eventHandlers); + super(cl, 0x$hscName); } +$#if events newEventHandler $#each func serviceFunction } -`, - // ******************************* - "noEventHandlers": ` -$#set eventHandlers new Map() `, // ******************************* "constArg": ` @@ -34,6 +32,13 @@ const Arg$FldName = "$fldAlias"; // ******************************* "constRes": ` const Res$FldName = "$fldAlias"; +`, + // ******************************* + "newEventHandler": ` + + public newEventHandler(): events.$PkgName$+Events { + return new events.$PkgName$+Events(); + } `, // ******************************* "funcStruct": ` @@ -113,7 +118,11 @@ $#each result callResultGetter `, // ******************************* "callResultGetter": ` -$#if map callResultGetterMap callResultGetterBasic +$#if map callResultGetterMap callResultGetter2 +`, + // ******************************* + "callResultGetter2": ` +$#if basetype callResultGetterBasic callResultGetterStruct `, // ******************************* "callResultGetterMap": ` @@ -121,7 +130,7 @@ $#if map callResultGetterMap callResultGetterBasic $fldName(): Map<$fldKeyLangType, $fldLangType> { const res = new Map<$fldKeyLangType, $fldLangType>(); this.forEach((key, val) => { - res.set(this.to$fldMapKey(key), this.to$FldType(val)); + res.set(this.to$FldMapKey(key), this.to$FldType(val)); }); return res; } @@ -133,6 +142,13 @@ $#if mandatory else callResultOptional $fldName(): $fldLangType { return this.to$FldType(this.get(Res$FldName)); } +`, + // ******************************* + "callResultGetterStruct": ` + + $fldName(): $FldType { + return $FldType.fromBytes(this.get(Res$FldName)); + } `, // ******************************* "callResultOptional": ` diff --git a/tools/schema/generator/tstemplates/alltemplates.go b/tools/schema/generator/tstemplates/alltemplates.go index 9fa0a18071..0f772d41ae 100644 --- a/tools/schema/generator/tstemplates/alltemplates.go +++ b/tools/schema/generator/tstemplates/alltemplates.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates import "github.com/iotaledger/wasp/tools/schema/model" @@ -17,7 +20,6 @@ var Templates = []map[string]string{ eventsTs, funcsTs, indexTs, - keysTs, libTs, paramsTs, proxyTs, @@ -29,76 +31,39 @@ var Templates = []map[string]string{ var TypeDependent = model.StringMapMap{ "fldLangType": { - "Address": "wasmlib.ScAddress", - "AgentID": "wasmlib.ScAgentID", + "Address": "wasmtypes.ScAddress", + "AgentID": "wasmtypes.ScAgentID", "Bool": "bool", - "ChainID": "wasmlib.ScChainID", - "Color": "wasmlib.ScColor", - "Hash": "wasmlib.ScHash", - "Hname": "wasmlib.ScHname", + "Bytes": "u8[]", + "ChainID": "wasmtypes.ScChainID", + "Color": "wasmtypes.ScColor", + "Hash": "wasmtypes.ScHash", + "Hname": "wasmtypes.ScHname", "Int8": "i8", "Int16": "i16", "Int32": "i32", "Int64": "i64", - "RequestID": "wasmlib.ScRequestID", + "RequestID": "wasmtypes.ScRequestID", "String": "string", "Uint8": "u8", "Uint16": "u16", "Uint32": "u32", "Uint64": "u64", }, - "fldTypeID": { - "Address": "wasmlib.TYPE_ADDRESS", - "AgentID": "wasmlib.TYPE_AGENT_ID", - "Bool": "wasmlib.TYPE_BOOL", - "ChainID": "wasmlib.TYPE_CHAIN_ID", - "Color": "wasmlib.TYPE_COLOR", - "Hash": "wasmlib.TYPE_HASH", - "Hname": "wasmlib.TYPE_HNAME", - "Int8": "wasmlib.TYPE_INT8", - "Int16": "wasmlib.TYPE_INT16", - "Int32": "wasmlib.TYPE_INT32", - "Int64": "wasmlib.TYPE_INT64", - "RequestID": "wasmlib.TYPE_REQUEST_ID", - "String": "wasmlib.TYPE_STRING", - "Uint8": "wasmlib.TYPE_INT8", - "Uint16": "wasmlib.TYPE_INT16", - "Uint32": "wasmlib.TYPE_INT32", - "Uint64": "wasmlib.TYPE_INT64", - "": "wasmlib.TYPE_BYTES", - }, - "fldToKey32": { - "Address": "key.getKeyID()", - "AgentID": "key.getKeyID()", - "Bool": "???cannot use Bool as map key", - "ChainID": "key.getKeyID()", - "Color": "key.getKeyID()", - "Hash": "key.getKeyID()", - "Hname": "key.getKeyID()", - "Int8": "wasmlib.getKeyIDFromUint64(key as u64, 1)", - "Int16": "wasmlib.getKeyIDFromUint64(key as u64, 2)", - "Int32": "wasmlib.getKeyIDFromUint64(key as u64, 4)", - "Int64": "wasmlib.getKeyIDFromUint64(key as u64, 8)", - "RequestID": "key.getKeyID()", - "String": "wasmlib.Key32.fromString(key)", - "Uint8": "wasmlib.getKeyIDFromUint64(key as u64, 1)", - "Uint16": "wasmlib.getKeyIDFromUint64(key as u64, 2)", - "Uint32": "wasmlib.getKeyIDFromUint64(key as u64, 4)", - "Uint64": "wasmlib.getKeyIDFromUint64(key, 8)", - }, "fldTypeInit": { - "Address": "new wasmlib.ScAddress()", - "AgentID": "new wasmlib.ScAgentID()", + "Address": "new wasmtypes.ScAddress()", + "AgentID": "wasmtypes.agentIDFromBytes([])", "Bool": "false", - "ChainID": "new wasmlib.ScChainID()", - "Color": "new wasmlib.ScColor(0)", - "Hash": "new wasmlib.ScHash()", - "Hname": "new wasmlib.ScHname(0)", + "Bytes": "[]", + "ChainID": "new wasmtypes.ScChainID()", + "Color": "new wasmtypes.ScColor(0)", + "Hash": "new wasmtypes.ScHash()", + "Hname": "new wasmtypes.ScHname(0)", "Int8": "0", "Int16": "0", "Int32": "0", "Int64": "0", - "RequestID": "new wasmlib.ScRequestID()", + "RequestID": "new wasmtypes.ScRequestID()", "String": "\"\"", "Uint8": "0", "Uint16": "0", @@ -108,27 +73,17 @@ var TypeDependent = model.StringMapMap{ } var common = map[string]string{ - // ******************************* - "initGlobals": ` -$#set arrayTypeID wasmlib.TYPE_ARRAY -$#if core setArrayTypeID -`, - // ******************************* - "setArrayTypeID": ` -$#set arrayTypeID wasmlib.TYPE_ARRAY16 -`, // ******************************* "importWasmLib": ` import * as wasmlib from "wasmlib"; `, // ******************************* - "importSc": ` -import * as sc from "./index"; + "importWasmTypes": ` +import * as wasmtypes from "wasmlib/wasmtypes"; `, // ******************************* - "tsImports": ` -$#emit importWasmLib -$#emit importSc + "importSc": ` +import * as sc from "./index"; `, // ******************************* "tsconfig.json": ` @@ -136,14 +91,5 @@ $#emit importSc "extends": "assemblyscript/std/assembly.json", "include": ["./*.ts"] } -`, - // ******************************* - "setVarType": ` -$#set varType wasmlib.TYPE_MAP -$#if array setVarTypeArray -`, - // ******************************* - "setVarTypeArray": ` -$#set varType $arrayTypeID|$fldTypeID `, } diff --git a/tools/schema/generator/tstemplates/consts.go b/tools/schema/generator/tstemplates/consts.go index 5f56e70bf0..b878857f00 100644 --- a/tools/schema/generator/tstemplates/consts.go +++ b/tools/schema/generator/tstemplates/consts.go @@ -1,20 +1,20 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var constsTs = map[string]string{ // ******************************* "consts.ts": ` -$#emit importWasmLib +$#emit importWasmTypes export const ScName = "$scName"; export const ScDescription = "$scDesc"; -export const HScName = new wasmlib.ScHname(0x$hscName); +export const HScName = new wasmtypes.ScHname(0x$hscName); $#if params constParams $#if results constResults $#if state constState - -$#each func constFunc - -$#each func constHFunc +$#if funcs constFuncs `, // ******************************* "constParams": ` @@ -33,6 +33,13 @@ $#each results constField $#set constPrefix State $#each state constField +`, + // ******************************* + "constFuncs": ` + +$#each func constFunc + +$#each func constHFunc `, // ******************************* "constField": ` @@ -44,6 +51,6 @@ export const $Kind$FuncName$funcPad = "$funcName"; `, // ******************************* "constHFunc": ` -export const H$Kind$FuncName$funcPad = new wasmlib.ScHname(0x$hFuncName); +export const H$Kind$FuncName$funcPad = new wasmtypes.ScHname(0x$hFuncName); `, } diff --git a/tools/schema/generator/tstemplates/contract.go b/tools/schema/generator/tstemplates/contract.go index 51788b0edb..2488b77b9a 100644 --- a/tools/schema/generator/tstemplates/contract.go +++ b/tools/schema/generator/tstemplates/contract.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var contractTs = map[string]string{ // ******************************* "contract.ts": ` -$#emit tsImports +$#emit importWasmLib +$#emit importSc $#each func FuncNameCall export class ScFuncs { @@ -43,57 +47,54 @@ $#if events PackageEventsExist `, // ******************************* "ImmutableFuncNameParams": ` - params: sc.Immutable$FuncName$+Params = new sc.Immutable$FuncName$+Params(); + params: sc.Immutable$FuncName$+Params = new sc.Immutable$FuncName$+Params(wasmlib.paramsProxy()); `, // ******************************* "MutableFuncNameParams": ` - params: sc.Mutable$FuncName$+Params = new sc.Mutable$FuncName$+Params(); + params: sc.Mutable$FuncName$+Params = new sc.Mutable$FuncName$+Params(wasmlib.ScView.nilProxy); `, // ******************************* "ImmutableFuncNameResults": ` - results: sc.Immutable$FuncName$+Results = new sc.Immutable$FuncName$+Results(); + results: sc.Immutable$FuncName$+Results = new sc.Immutable$FuncName$+Results(wasmlib.ScView.nilProxy); `, // ******************************* "MutableFuncNameResults": ` - results: sc.Mutable$FuncName$+Results = new sc.Mutable$FuncName$+Results(); + results: sc.Mutable$FuncName$+Results = new sc.Mutable$FuncName$+Results(wasmlib.ScView.nilProxy); `, // ******************************* "ImmutablePackageState": ` - state: sc.Immutable$Package$+State = new sc.Immutable$Package$+State(); + state: sc.Immutable$Package$+State = new sc.Immutable$Package$+State(wasmlib.ScState.proxy()); `, // ******************************* "MutablePackageState": ` - state: sc.Mutable$Package$+State = new sc.Mutable$Package$+State(); + state: sc.Mutable$Package$+State = new sc.Mutable$Package$+State(wasmlib.ScState.proxy()); `, // ******************************* "FuncNameForCall": ` $#emit setupInitFunc $#if separator newline $#set separator $true - static $funcName(ctx: wasmlib.Sc$Kind$+CallContext): $FuncName$+Call { -$#set paramsID null -$#set resultsID null -$#if param setParamsID -$#if result setResultsID + static $funcName(_ctx: wasmlib.Sc$Kind$+CallContext): $FuncName$+Call { $#if ptrs setPtrs noPtrs - } + } `, // ******************************* "setPtrs": ` - let f = new $FuncName$+Call(); - f.func.setPtrs($paramsID, $resultsID); - return f; + const f = new $FuncName$+Call(); +$#if param initParams +$#if result initResults + return f; `, // ******************************* - "setParamsID": ` -$#set paramsID f.params + "initParams": ` + f.params = new sc.Mutable$FuncName$+Params(wasmlib.newCallParamsProxy(f.func)); `, // ******************************* - "setResultsID": ` -$#set resultsID f.results + "initResults": ` + f.results = new sc.Immutable$FuncName$+Results(wasmlib.newCallResultsProxy(f.func)); `, // ******************************* "noPtrs": ` - return new $FuncName$+Call(); + return new $FuncName$+Call(); `, } diff --git a/tools/schema/generator/tstemplates/events.go b/tools/schema/generator/tstemplates/events.go index 1712275c9e..afeea9ea59 100644 --- a/tools/schema/generator/tstemplates/events.go +++ b/tools/schema/generator/tstemplates/events.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var eventsTs = map[string]string{ // ******************************* "events.ts": ` $#emit importWasmLib +$#emit importWasmTypes $#set TypeName $Package$+Events export class $TypeName { @@ -12,14 +16,14 @@ $#each events eventFunc `, // ******************************* "eventFunc": ` -$#set params $#set separator +$#set params $#each event eventParam $evtName($params): void { - new wasmlib.EventEncoder("$package.$evtName"). + const evt = new wasmlib.EventEncoder("$package.$evtName"); $#each event eventEmit - emit(); + evt.emit(); } `, // ******************************* @@ -29,6 +33,6 @@ $#set separator , `, // ******************************* "eventEmit": ` - $fldType($fldName). + evt.encode(wasmtypes.$fldType$+ToString($fldName)); `, } diff --git a/tools/schema/generator/tstemplates/funcs.go b/tools/schema/generator/tstemplates/funcs.go index 271f248056..3a9008e1a3 100644 --- a/tools/schema/generator/tstemplates/funcs.go +++ b/tools/schema/generator/tstemplates/funcs.go @@ -1,9 +1,14 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var funcsTs = map[string]string{ // ******************************* "funcs.ts": ` -$#emit tsImports +$#emit importWasmLib +$#emit importWasmTypes +$#emit importSc $#each func funcSignature `, // ******************************* @@ -15,18 +20,18 @@ $#emit init$Kind$FuncName `, // ******************************* "initFuncInit": ` - if (f.params.owner().exists()) { - f.state.owner().setValue(f.params.owner().value()); - return; - } - f.state.owner().setValue(ctx.contractCreator()); + if (f.params.owner().exists()) { + f.state.owner().setValue(f.params.owner().value()); + return; + } + f.state.owner().setValue(ctx.contractCreator()); `, // ******************************* "initFuncSetOwner": ` - f.state.owner().setValue(f.params.owner().value()); + f.state.owner().setValue(f.params.owner().value()); `, // ******************************* "initViewGetOwner": ` - f.results.owner().setValue(f.state.owner().value()); + f.results.owner().setValue(f.state.owner().value()); `, } diff --git a/tools/schema/generator/tstemplates/index.go b/tools/schema/generator/tstemplates/index.go index 4bb4725cad..10734c76a7 100644 --- a/tools/schema/generator/tstemplates/index.go +++ b/tools/schema/generator/tstemplates/index.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var indexTs = map[string]string{ @@ -7,11 +10,12 @@ $#if core else exportName export * from "./consts"; export * from "./contract"; $#if events exportEvents -$#if core else exportKeys $#if core else exportLib $#if params exportParams $#if results exportResults -$#if core else exportRest +$#if core else exportState +$#if structs exportStructs +$#if typedefs exportTypedefs `, // ******************************* "exportName": ` @@ -21,10 +25,6 @@ export * from "./$package"; // ******************************* "exportEvents": ` export * from "./events"; -`, - // ******************************* - "exportKeys": ` -export * from "./keys"; `, // ******************************* "exportLib": ` @@ -39,10 +39,8 @@ export * from "./params"; export * from "./results"; `, // ******************************* - "exportRest": ` + "exportState": ` export * from "./state"; -$#if structs exportStructs -$#if typedefs exportTypedefs `, // ******************************* "exportStructs": ` diff --git a/tools/schema/generator/tstemplates/keys.go b/tools/schema/generator/tstemplates/keys.go deleted file mode 100644 index 6aaa919ad5..0000000000 --- a/tools/schema/generator/tstemplates/keys.go +++ /dev/null @@ -1,36 +0,0 @@ -package tstemplates - -var keysTs = map[string]string{ - // ******************************* - "keys.ts": ` -$#emit tsImports - -$#set constPrefix Param -$#each params constFieldIdx - -$#set constPrefix Result -$#each results constFieldIdx - -$#set constPrefix State -$#each state constFieldIdx - -export let keyMap: string[] = [ -$#set constPrefix Param -$#each params constFieldKey -$#set constPrefix Result -$#each results constFieldKey -$#set constPrefix State -$#each state constFieldKey -]; - -export let idxMap: wasmlib.Key32[] = new Array(keyMap.length); -`, - // ******************************* - "constFieldIdx": ` -export const Idx$constPrefix$FldName$fldPad = $fldIndex; -`, - // ******************************* - "constFieldKey": ` - sc.$constPrefix$FldName, -`, -} diff --git a/tools/schema/generator/tstemplates/lib.go b/tools/schema/generator/tstemplates/lib.go index fa20ef1595..6ef7f0384c 100644 --- a/tools/schema/generator/tstemplates/lib.go +++ b/tools/schema/generator/tstemplates/lib.go @@ -1,56 +1,82 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var libTs = map[string]string{ // ******************************* "lib.ts": ` -$#emit tsImports +$#emit importWasmLib +$#emit importSc + +const exportMap: wasmlib.ScExportMap = { + names: [ +$#each func libExportName + ], + funcs: [ +$#each func libExportFunc + ], + views: [ +$#each func libExportView + ], +}; export function on_call(index: i32): void { - return wasmlib.onCall(index); + wasmlib.ScExports.call(index, exportMap); } export function on_load(): void { - let exports = new wasmlib.ScExports(); -$#each func libExportFunc - - for (let i = 0; i < sc.keyMap.length; i++) { - sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]); - } + wasmlib.ScExports.export(exportMap); } $#each func libThunk +`, + // ******************************* + "libExportName": ` + sc.$Kind$FuncName, `, // ******************************* "libExportFunc": ` - exports.add$Kind(sc.$Kind$FuncName,$funcPad $kind$FuncName$+Thunk); +$#if func libExportFuncThunk +`, + // ******************************* + "libExportFuncThunk": ` + $kind$FuncName$+Thunk, +`, + // ******************************* + "libExportView": ` +$#if view libExportViewThunk +`, + // ******************************* + "libExportViewThunk": ` + $kind$FuncName$+Thunk, `, // ******************************* "libThunk": ` function $kind$FuncName$+Thunk(ctx: wasmlib.Sc$Kind$+Context): void { ctx.log("$package.$kind$FuncName"); -$#emit accessCheck let f = new sc.$FuncName$+Context(); -$#if param ImmutableFuncNameParamsInit -$#if result MutableFuncNameResultsInit - f.state.mapID = wasmlib.OBJ_ID_STATE; +$#if result initResultsDict +$#emit accessCheck $#each mandatory requireMandatory sc.$kind$FuncName(ctx, f); +$#if result returnResultDict ctx.log("$package.$kind$FuncName ok"); } `, // ******************************* - "ImmutableFuncNameParamsInit": ` - f.params.mapID = wasmlib.OBJ_ID_PARAMS; + "initResultsDict": ` + const results = new wasmlib.ScDict([]); + f.results = new sc.Mutable$FuncName$+Results(results.asProxy()); `, // ******************************* - "MutableFuncNameResultsInit": ` - f.results.mapID = wasmlib.OBJ_ID_RESULTS; + "returnResultDict": ` + ctx.results(results); `, // ******************************* "requireMandatory": ` ctx.require(f.params.$fldName().exists(), "missing mandatory $fldName"); `, - // ******************************* "accessCheck": ` $#set accessFinalize accessOther @@ -85,7 +111,7 @@ $#set accessFinalize accessDone // ******************************* "accessOther": ` $#if funcAccessComment accessComment - let access = ctx.state().getAgentID(wasmlib.Key32.fromString("$funcAccess")); + const access = f.state.$funcAccess(); ctx.require(access.exists(), "access not set: $funcAccess"); ctx.require(ctx.caller().equals(access.value()), "no permission"); diff --git a/tools/schema/generator/tstemplates/params.go b/tools/schema/generator/tstemplates/params.go index 8216ac2135..8cb4ecf985 100644 --- a/tools/schema/generator/tstemplates/params.go +++ b/tools/schema/generator/tstemplates/params.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var paramsTs = map[string]string{ // ******************************* "params.ts": ` -$#emit tsImports +$#emit importWasmTypes +$#emit importSc $#each func paramsFunc `, // ******************************* @@ -23,7 +27,7 @@ $#if param paramsProxyStruct $#set TypeName $mut$FuncName$+Params $#each param proxyContainers -export class $TypeName extends wasmlib.ScMapID { +export class $TypeName extends wasmtypes.ScProxy { $#set separator $false $#each param proxyMethods } diff --git a/tools/schema/generator/tstemplates/proxy.go b/tools/schema/generator/tstemplates/proxy.go index 2e2f1ddaac..89cc9af978 100644 --- a/tools/schema/generator/tstemplates/proxy.go +++ b/tools/schema/generator/tstemplates/proxy.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var proxyTs = map[string]string{ @@ -10,14 +13,7 @@ $#if map typedefProxyMap "proxyMethods": ` $#if separator newline $#set separator $true -$#set varID wasmlib.Key32.fromString(sc.$Kind$FldName) -$#if init setInitVarID -$#if core setCoreVarID $#if array proxyArray proxyMethods2 -`, - // ******************************* - "setInitVarID": ` -$#set varID sc.idxMap[sc.Idx$Kind$FldName] `, // ******************************* "proxyMethods2": ` @@ -25,21 +21,12 @@ $#if map proxyMap proxyMethods3 `, // ******************************* "proxyMethods3": ` -$#if basetype proxyBaseType proxyMethods4 -`, - // ******************************* - "proxyMethods4": ` -$#if typedef proxyTypeDef proxyStruct -`, - // ******************************* - "setCoreVarID": ` -$#set varID wasmlib.Key32.fromString(sc.$Kind$FldName) +$#if basetype proxyBaseType proxyOtherType `, // ******************************* "proxyArray": ` - $fldName(): sc.ArrayOf$mut$FldType { - let arrID = wasmlib.getObjectID(this.mapID, $varID, $arrayTypeID|$fldTypeID); - return new sc.ArrayOf$mut$FldType(arrID); + $fldName(): sc.ArrayOf$mut$FldType { + return new sc.ArrayOf$mut$FldType(this.proxy.root(sc.$Kind$FldName)); } `, // ******************************* @@ -48,35 +35,26 @@ $#if this proxyMapThis proxyMapOther `, // ******************************* "proxyMapThis": ` - $fldName(): sc.Map$fldMapKey$+To$mut$FldType { - return new sc.Map$fldMapKey$+To$mut$FldType(this.mapID); + $fldName(): sc.Map$FldMapKey$+To$mut$FldType { + return new sc.Map$FldMapKey$+To$mut$FldType(this.proxy); } `, // ******************************* "proxyMapOther": ` - $fldName(): sc.Map$fldMapKey$+To$mut$FldType { - let mapID = wasmlib.getObjectID(this.mapID, $varID, wasmlib.TYPE_MAP); - return new sc.Map$fldMapKey$+To$mut$FldType(mapID); + $fldName(): sc.Map$FldMapKey$+To$mut$FldType { + return new sc.Map$FldMapKey$+To$mut$FldType(this.proxy.root(sc.$Kind$FldName)); } `, // ******************************* "proxyBaseType": ` - $fldName(): wasmlib.Sc$mut$FldType { - return new wasmlib.Sc$mut$FldType(this.mapID, $varID); - } -`, - // ******************************* - "proxyTypeDef": ` -$#emit setVarType - $oldName(): sc.$mut$OldType { - let subID = wasmlib.getObjectID(this.mapID, $varID, $varType); - return new sc.$mut$OldType(subID); + $fldName(): wasmtypes.Sc$mut$FldType { + return new wasmtypes.Sc$mut$FldType(this.proxy.root(sc.$Kind$FldName)); } `, // ******************************* - "proxyStruct": ` - $fldName(): sc.$mut$FldType { - return new sc.$mut$FldType(this.mapID, $varID); + "proxyOtherType": ` + $fldName(): sc.$mut$FldType { + return new sc.$mut$FldType(this.proxy.root(sc.$Kind$FldName)); } `, } diff --git a/tools/schema/generator/tstemplates/results.go b/tools/schema/generator/tstemplates/results.go index 61dabe5049..69aa442ed4 100644 --- a/tools/schema/generator/tstemplates/results.go +++ b/tools/schema/generator/tstemplates/results.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var resultsTs = map[string]string{ // ******************************* "results.ts": ` -$#emit tsImports +$#emit importWasmTypes +$#emit importSc $#each func resultsFunc `, // ******************************* @@ -23,7 +27,7 @@ $#if result resultsProxyStruct $#set TypeName $mut$FuncName$+Results $#each result proxyContainers -export class $TypeName extends wasmlib.ScMapID { +export class $TypeName extends wasmtypes.ScProxy { $#set separator $false $#each result proxyMethods } diff --git a/tools/schema/generator/tstemplates/state.go b/tools/schema/generator/tstemplates/state.go index 979756a368..d375182afb 100644 --- a/tools/schema/generator/tstemplates/state.go +++ b/tools/schema/generator/tstemplates/state.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var stateTs = map[string]string{ // ******************************* "state.ts": ` -$#emit tsImports +$#emit importWasmTypes +$#emit importSc $#set Kind State $#set mut Immutable $#emit stateProxyStruct @@ -15,7 +19,7 @@ $#emit stateProxyStruct $#set TypeName $mut$Package$+State $#each state proxyContainers -export class $TypeName extends wasmlib.ScMapID { +export class $TypeName extends wasmtypes.ScProxy { $#set separator $false $#if mut stateProxyImmutableFunc $#each state proxyMethods @@ -24,10 +28,8 @@ $#each state proxyMethods // ******************************* "stateProxyImmutableFunc": ` $#set separator $true - asImmutable(): sc.Immutable$Package$+State { - const imm = new sc.Immutable$Package$+State(); - imm.mapID = this.mapID; - return imm; + asImmutable(): sc.Immutable$Package$+State { + return new sc.Immutable$Package$+State(this.proxy); } `, } diff --git a/tools/schema/generator/tstemplates/structs.go b/tools/schema/generator/tstemplates/structs.go index 254d8b329d..a79f5ae0f4 100644 --- a/tools/schema/generator/tstemplates/structs.go +++ b/tools/schema/generator/tstemplates/structs.go @@ -1,9 +1,12 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var structsTs = map[string]string{ // ******************************* "structs.ts": ` -$#emit importWasmLib +$#emit importWasmTypes $#each structs structType `, // ******************************* @@ -12,19 +15,19 @@ $#each structs structType export class $StrName { $#each struct structField - static fromBytes(bytes: u8[]): $StrName { - let decode = new wasmlib.BytesDecoder(bytes); - let data = new $StrName(); + static fromBytes(buf: u8[]): $StrName { + const dec = new wasmtypes.WasmDecoder(buf); + const data = new $StrName(); $#each struct structDecode - decode.close(); - return data; - } + dec.close(); + return data; + } - bytes(): u8[] { - return new wasmlib.BytesEncoder(). + bytes(): u8[] { + const enc = new wasmtypes.WasmEncoder(); $#each struct structEncode - data(); - } + return enc.buf(); + } } $#set mut Immutable $#emit structMethods @@ -33,51 +36,44 @@ $#emit structMethods `, // ******************************* "structField": ` - $fldName$fldPad : $fldLangType = $fldTypeInit; $fldComment + $fldName$fldPad : $fldLangType = $fldTypeInit; $fldComment `, // ******************************* "structDecode": ` - data.$fldName$fldPad = decode.$fldType(); + data.$fldName$fldPad = wasmtypes.$fldType$+Decode(dec); `, // ******************************* "structEncode": ` - $fldType(this.$fldName). + wasmtypes.$fldType$+Encode(enc, this.$fldName); `, // ******************************* "structMethods": ` -export class $mut$StrName { - objID: i32; - keyID: wasmlib.Key32; - - constructor(objID: i32, keyID: wasmlib.Key32) { - this.objID = objID; - this.keyID = keyID; - } +export class $mut$StrName extends wasmtypes.ScProxy { $#if mut structMethodDelete - exists(): boolean { - return wasmlib.exists(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + exists(): bool { + return this.proxy.exists(); + } $#if mut structMethodSetValue - value(): $StrName { - return $StrName.fromBytes(wasmlib.getBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES)); - } + value(): $StrName { + return $StrName.fromBytes(this.proxy.get()); + } } `, // ******************************* "structMethodDelete": ` - delete(): void { - wasmlib.delKey(this.objID, this.keyID, wasmlib.TYPE_BYTES); - } + delete(): void { + this.proxy.delete(); + } `, // ******************************* "structMethodSetValue": ` - setValue(value: $StrName): void { - wasmlib.setBytes(this.objID, this.keyID, wasmlib.TYPE_BYTES, value.bytes()); - } + setValue(value: $StrName): void { + this.proxy.set(value.bytes()); + } `, } diff --git a/tools/schema/generator/tstemplates/typedefs.go b/tools/schema/generator/tstemplates/typedefs.go index 21ae67839b..1adcd2e45a 100644 --- a/tools/schema/generator/tstemplates/typedefs.go +++ b/tools/schema/generator/tstemplates/typedefs.go @@ -1,9 +1,13 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var typedefsTs = map[string]string{ // ******************************* "typedefs.ts": ` -$#emit tsImports +$#emit importWasmTypes +$#emit importSc $#each typedef typedefProxy `, // ******************************* @@ -23,7 +27,7 @@ $#if map typedefProxyAlias "typedefProxyAlias": ` export class $mut$FldName extends $proxy { -}; +} `, // ******************************* "typedefProxyArray": ` @@ -33,106 +37,85 @@ $#if exist else typedefProxyArrayNew // ******************************* "typedefProxyArrayNew": ` -export class $proxy { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } -$#if mut typedefProxyArrayClear +export class $proxy extends wasmtypes.ScProxy { +$#if mut typedefProxyArrayMut - length(): i32 { - return wasmlib.getLength(this.objID); - } + length(): u32 { + return this.proxy.length(); + } $#if basetype typedefProxyArrayNewBaseType typedefProxyArrayNewOtherType } $#set exist $proxy `, // ******************************* - "typedefProxyArrayClear": ` + "typedefProxyArrayMut": ` +$#if basetype typedefProxyArrayAppendBaseType typedefProxyArrayAppendOtherType - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearArray(); + } `, // ******************************* - "typedefProxyArrayNewBaseType": ` + "typedefProxyArrayAppendBaseType": ` - get$FldType(index: i32): wasmlib.Sc$mut$FldType { - return new wasmlib.Sc$mut$FldType(this.objID, new wasmlib.Key32(index)); - } + append$FldType(): wasmtypes.Sc$mut$FldType { + return new wasmtypes.Sc$mut$FldType(this.proxy.append()); + } `, // ******************************* - "typedefProxyArrayNewOtherType": ` -$#if typedef typedefProxyArrayNewOtherTypeTypeDef typedefProxyArrayNewOtherTypeStruct + "typedefProxyArrayAppendOtherType": ` + + append$FldType(): sc.$mut$FldType { + return new sc.$mut$FldType(this.proxy.append()); + } `, // ******************************* - "typedefProxyArrayNewOtherTypeTypeDef": ` -$#emit setVarType + "typedefProxyArrayNewBaseType": ` - get$OldType(index: i32): sc.$mut$OldType { - let subID = wasmlib.getObjectID(this.objID, new wasmlib.Key32(index), $varType); - return new sc.$mut$OldType(subID); + get$FldType(index: u32): wasmtypes.Sc$mut$FldType { + return new wasmtypes.Sc$mut$FldType(this.proxy.index(index)); } `, // ******************************* - "typedefProxyArrayNewOtherTypeStruct": ` + "typedefProxyArrayNewOtherType": ` - get$FldType(index: i32): sc.$mut$FldType { - return new sc.$mut$FldType(this.objID, new wasmlib.Key32(index)); + get$FldType(index: u32): sc.$mut$FldType { + return new sc.$mut$FldType(this.proxy.index(index)); } `, // ******************************* "typedefProxyMap": ` -$#set proxy Map$fldMapKey$+To$mut$FldType +$#set proxy Map$FldMapKey$+To$mut$FldType $#if exist else typedefProxyMapNew `, // ******************************* "typedefProxyMapNew": ` -export class $proxy { - objID: i32; - - constructor(objID: i32) { - this.objID = objID; - } -$#if mut typedefProxyMapClear +export class $proxy extends wasmtypes.ScProxy { +$#if mut typedefProxyMapMut $#if basetype typedefProxyMapNewBaseType typedefProxyMapNewOtherType } $#set exist $proxy `, // ******************************* - "typedefProxyMapClear": ` + "typedefProxyMapMut": ` - clear(): void { - wasmlib.clear(this.objID); - } + clear(): void { + this.proxy.clearMap(); + } `, // ******************************* "typedefProxyMapNewBaseType": ` - get$FldType(key: $fldKeyLangType): wasmlib.Sc$mut$FldType { - return new wasmlib.Sc$mut$FldType(this.objID, $fldKeyToKey32); - } + get$FldType(key: $fldKeyLangType): wasmtypes.Sc$mut$FldType { + return new wasmtypes.Sc$mut$FldType(this.proxy.key(wasmtypes.$fldMapKey$+ToBytes(key))); + } `, // ******************************* "typedefProxyMapNewOtherType": ` -$#if typedef typedefProxyMapNewOtherTypeTypeDef typedefProxyMapNewOtherTypeStruct -`, - // ******************************* - "typedefProxyMapNewOtherTypeTypeDef": ` -$#emit setVarType - get$OldType(key: $oldKeyLangType): sc.$mut$OldType { - let subID = wasmlib.getObjectID(this.objID, $oldKeyToKey32, $varType); - return new sc.$mut$OldType(subID); - } -`, - // ******************************* - "typedefProxyMapNewOtherTypeStruct": ` - - get$FldType(key: $fldKeyLangType): sc.$mut$FldType { - return new sc.$mut$FldType(this.objID, $fldKeyToKey32); - } + get$FldType(key: $fldKeyLangType): sc.$mut$FldType { + return new sc.$mut$FldType(this.proxy.key(wasmtypes.$fldMapKey$+ToBytes(key))); + } `, } diff --git a/tools/schema/generator/utils.go b/tools/schema/generator/utils.go index ae12a5aec8..d59c8bf16e 100644 --- a/tools/schema/generator/utils.go +++ b/tools/schema/generator/utils.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package generator import ( @@ -18,6 +21,9 @@ var ( // capitalize first letter func capitalize(name string) string { + if name == "" { + return "" + } return upper(name[:1]) + name[1:] } @@ -92,6 +98,9 @@ func snake(name string) string { // uncapitalize first letter func uncapitalize(name string) string { + if name == "" { + return "" + } return lower(name[:1]) + name[1:] } diff --git a/tools/schema/main.go b/tools/schema/main.go index 3595845ca3..ab375cadbe 100644 --- a/tools/schema/main.go +++ b/tools/schema/main.go @@ -114,7 +114,11 @@ func generateSchema(file *os.File) error { s.SchemaTime = info.ModTime() // also force regeneration when schema tool itself is newer - info, err = os.Stat(os.Args[0]) + exe, err := os.Executable() + if err != nil { + return err + } + info, err = os.Stat(exe) if err != nil { return err } @@ -123,6 +127,10 @@ func generateSchema(file *os.File) error { } } + if *flagClient && !*flagGo && !*flagTs { + return errors.New("missing language specification") + } + if *flagGo { g := generator.NewGoGenerator(s) err = g.Generate() diff --git a/tools/schema/model/field.go b/tools/schema/model/field.go index 38232a01df..360f99c805 100644 --- a/tools/schema/model/field.go +++ b/tools/schema/model/field.go @@ -7,8 +7,6 @@ import ( "fmt" "regexp" "strings" - - "github.com/iotaledger/wasp/packages/vm/wasmlib/go/wasmlib" ) var ( @@ -17,25 +15,25 @@ var ( fldTypeRegexp = regexp.MustCompile(`^[A-Z][a-zA-Z0-9]+$`) ) -var FieldTypes = map[string]int32{ - "Address": wasmlib.TYPE_ADDRESS, - "AgentID": wasmlib.TYPE_AGENT_ID, - "Bool": wasmlib.TYPE_BOOL, - "Bytes": wasmlib.TYPE_BYTES, - "ChainID": wasmlib.TYPE_CHAIN_ID, - "Color": wasmlib.TYPE_COLOR, - "Hash": wasmlib.TYPE_HASH, - "Hname": wasmlib.TYPE_HNAME, - "Int8": wasmlib.TYPE_INT8, - "Int16": wasmlib.TYPE_INT16, - "Int32": wasmlib.TYPE_INT32, - "Int64": wasmlib.TYPE_INT64, - "RequestID": wasmlib.TYPE_REQUEST_ID, - "String": wasmlib.TYPE_STRING, - "Uint8": wasmlib.TYPE_INT8, - "Uint16": wasmlib.TYPE_INT16, - "Uint32": wasmlib.TYPE_INT32, - "Uint64": wasmlib.TYPE_INT64, +var FieldTypes = map[string]bool{ + "Address": true, + "AgentID": true, + "Bool": true, + "Bytes": true, + "ChainID": true, + "Color": true, + "Hash": true, + "Hname": true, + "Int8": true, + "Int16": true, + "Int32": true, + "Int64": true, + "RequestID": true, + "String": true, + "Uint8": true, + "Uint16": true, + "Uint32": true, + "Uint64": true, } type Field struct { @@ -47,7 +45,7 @@ type Field struct { MapKey string Optional bool Type string - TypeID int32 + BaseType bool } func (f *Field) Compile(s *Schema, fldName, fldType string) error { @@ -102,9 +100,8 @@ func (f *Field) Compile(s *Schema, fldName, fldType string) error { if !fldTypeRegexp.MatchString(f.Type) { return fmt.Errorf("invalid field type: %s", f.Type) } - typeID, ok := FieldTypes[f.Type] - if ok { - f.TypeID = typeID + f.BaseType = FieldTypes[f.Type] + if f.BaseType { return nil } for _, typeDef := range s.Structs { diff --git a/tools/wasp-cli/chain/alias.go b/tools/wasp-cli/chain/alias.go index 88e15ddf9d..dc0541594a 100644 --- a/tools/wasp-cli/chain/alias.go +++ b/tools/wasp-cli/chain/alias.go @@ -34,7 +34,11 @@ func AddChainAlias(chainAlias, id string) { } func GetCurrentChainID() *iscp.ChainID { - chid, err := iscp.ChainIDFromBase58(viper.GetString("chains." + GetChainAlias())) + return GetChainFromAlias(GetChainAlias()) +} + +func GetChainFromAlias(alias string) *iscp.ChainID { + chid, err := iscp.ChainIDFromBase58(viper.GetString("chains." + alias)) log.Check(err) return chid } diff --git a/tools/wasp-cli/metrics/consensus.go b/tools/wasp-cli/metrics/consensus.go index 07dad27713..de11f85113 100644 --- a/tools/wasp-cli/metrics/consensus.go +++ b/tools/wasp-cli/metrics/consensus.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/iotaledger/wasp/packages/iscp" + "github.com/iotaledger/wasp/tools/wasp-cli/chain" "github.com/iotaledger/wasp/tools/wasp-cli/config" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/spf13/cobra" @@ -18,12 +18,16 @@ var consensusMetricsCmd = &cobra.Command{ Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { client := config.WaspClient() - chid, err := iscp.ChainIDFromBase58(chainIDStr) - log.Check(err) + if chainAlias == "" { + log.Fatalf("Call `chain metrics consensus --chain=`") + } + chid := chain.GetChainFromAlias(chainAlias) workflowStatus, err := client.GetChainConsensusWorkflowStatus(chid) log.Check(err) + pipeMetrics, err := client.GetChainConsensusPipeMetrics(chid) + log.Check(err) header := []string{"Flag name", "Value", "Last time set"} - table := make([][]string, 9) + table := make([][]string, 17) table[0] = makeWorkflowTableRow("State received", workflowStatus.FlagStateReceived, time.Time{}) table[1] = makeWorkflowTableRow("Batch proposal sent", workflowStatus.FlagBatchProposalSent, workflowStatus.TimeBatchProposalSent) table[2] = makeWorkflowTableRow("Consensus on batch reached", workflowStatus.FlagConsensusBatchKnown, workflowStatus.TimeConsensusBatchKnown) @@ -33,11 +37,19 @@ var consensusMetricsCmd = &cobra.Command{ table[6] = makeWorkflowTableRow("Transaction posted to L1", workflowStatus.FlagTransactionPosted, workflowStatus.TimeTransactionPosted) // TODO: is not meaningful, if I am not a contributor table[7] = makeWorkflowTableRow("Transaction seen by L1", workflowStatus.FlagTransactionSeen, workflowStatus.TimeTransactionSeen) table[8] = makeWorkflowTableRow("Consensus is completed", !(workflowStatus.FlagInProgress), workflowStatus.TimeCompleted) + table[9] = makeWorkflowTableRow("Current state index", workflowStatus.CurrentStateIndex, time.Time{}) + table[10] = makeWorkflowTableRow("Event state transition message pipe size", pipeMetrics.EventStateTransitionMsgPipeSize, time.Time{}) + table[11] = makeWorkflowTableRow("Event signed result message pipe metrics size", pipeMetrics.EventSignedResultMsgPipeSize, time.Time{}) + table[12] = makeWorkflowTableRow("Event signed result ack message pipe size", pipeMetrics.EventSignedResultAckMsgPipeSize, time.Time{}) + table[13] = makeWorkflowTableRow("Event inclusion state message pipe size", pipeMetrics.EventInclusionStateMsgPipeSize, time.Time{}) + table[14] = makeWorkflowTableRow("Event ACS message pipe size", pipeMetrics.EventACSMsgPipeSize, time.Time{}) + table[15] = makeWorkflowTableRow("Event VM result message pipe size", pipeMetrics.EventVMResultMsgPipeSize, time.Time{}) + table[16] = makeWorkflowTableRow("Event timer message pipe size", pipeMetrics.EventTimerMsgPipeSize, time.Time{}) log.PrintTable(header, table) }, } -func makeWorkflowTableRow(name string, value bool, timestamp time.Time) []string { +func makeWorkflowTableRow(name string, value interface{}, timestamp time.Time) []string { res := make([]string, 3) res[0] = name res[1] = fmt.Sprintf("%v", value) diff --git a/tools/wasp-cli/metrics/metrics.go b/tools/wasp-cli/metrics/metrics.go index 77e9256f30..7e43dd1c7e 100644 --- a/tools/wasp-cli/metrics/metrics.go +++ b/tools/wasp-cli/metrics/metrics.go @@ -14,12 +14,12 @@ var metricsCmd = &cobra.Command{ }, } -var chainIDStr string +var chainAlias string func Init(rootCmd *cobra.Command) { rootCmd.AddCommand(metricsCmd) metricsCmd.AddCommand(nodeconnMetricsCmd) metricsCmd.AddCommand(consensusMetricsCmd) - metricsCmd.PersistentFlags().StringVarP(&chainIDStr, "chain", "", "", "chain ID for which metrics should be displayed") + metricsCmd.PersistentFlags().StringVarP(&chainAlias, "chain", "", "", "chain for which metrics should be displayed") } diff --git a/tools/wasp-cli/metrics/nodeconn.go b/tools/wasp-cli/metrics/nodeconn.go index ebe05c46ac..cedcb2e8a8 100644 --- a/tools/wasp-cli/metrics/nodeconn.go +++ b/tools/wasp-cli/metrics/nodeconn.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/webapi/model" + "github.com/iotaledger/wasp/tools/wasp-cli/chain" "github.com/iotaledger/wasp/tools/wasp-cli/config" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/spf13/cobra" @@ -19,7 +19,7 @@ var nodeconnMetricsCmd = &cobra.Command{ Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { client := config.WaspClient() - if chainIDStr == "" { + if chainAlias == "" { nodeconnMetrics, err := client.GetNodeConnectionMetrics() log.Check(err) log.Printf("Following chains subscribed to L1 events:\n") @@ -28,8 +28,7 @@ var nodeconnMetricsCmd = &cobra.Command{ } printMessagesMetrics(&nodeconnMetrics.NodeConnectionMessagesMetrics) } else { - chid, err := iscp.ChainIDFromBase58(chainIDStr) - log.Check(err) + chid := chain.GetChainFromAlias(chainAlias) msgsMetrics, err := client.GetChainNodeConnectionMetrics(chid) log.Check(err) printMessagesMetrics(msgsMetrics) diff --git a/wasp.nomad.tpl b/wasp.nomad.tpl index ad3f8c113d..ce5e714312 100644 --- a/wasp.nomad.tpl +++ b/wasp.nomad.tpl @@ -1,5 +1,5 @@ variable "wasp_config" { - default = <