diff --git a/contracts/wasm/dividend/src/dividend.rs b/contracts/wasm/dividend/src/dividend.rs index 595609d1f5..3baabb030f 100644 --- a/contracts/wasm/dividend/src/dividend.rs +++ b/contracts/wasm/dividend/src/dividend.rs @@ -180,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); } } } diff --git a/contracts/wasm/dividend/test/dividend_bg.wasm b/contracts/wasm/dividend/test/dividend_bg.wasm index 1822c90b4f..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 2f2943492d..f7da833e81 100644 --- a/contracts/wasm/dividend/test/dividend_test.go +++ b/contracts/wasm/dividend/test/dividend_test.go @@ -4,7 +4,6 @@ package test import ( - "strings" "testing" "github.com/iotaledger/wasp/contracts/wasm/dividend/go/dividend" @@ -17,7 +16,7 @@ func dividendMember(ctx *wasmsolo.SoloContext, agent *wasmsolo.SoloAgent, factor 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 uint64) { @@ -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/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go index 75bb332187..a44016c186 100644 --- a/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go +++ b/contracts/wasm/donatewithfeedback/go/donatewithfeedback/donatewithfeedback.go @@ -9,8 +9,9 @@ import ( ) func funcDonate(ctx wasmlib.ScFuncContext, f *DonateContext) { + amount := ctx.IncomingTransfer().Balance(wasmtypes.IOTA) donation := &Donation{ - Amount: ctx.IncomingTransfer().Balance(wasmtypes.IOTA), + Amount: amount, Donator: ctx.Caller(), Error: "", Feedback: f.Params.Feedback().Value(), diff --git a/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs b/contracts/wasm/donatewithfeedback/src/donatewithfeedback.rs index a814c6636d..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,7 +18,7 @@ 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; } } @@ -44,7 +45,7 @@ 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) { diff --git a/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm b/contracts/wasm/donatewithfeedback/test/donatewithfeedback_bg.wasm index b8b0a534f5..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/ts/donatewithfeedback/donatewithfeedback.ts b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts index a821861169..2b8fd30250 100644 --- a/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts +++ b/contracts/wasm/donatewithfeedback/ts/donatewithfeedback/donatewithfeedback.ts @@ -6,8 +6,9 @@ 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(wasmtypes.IOTA); + donation.amount = amount; donation.donator = ctx.caller(); donation.error = ""; donation.feedback = f.params.feedback().value(); @@ -15,7 +16,7 @@ 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; } } @@ -42,7 +43,7 @@ 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 { diff --git a/contracts/wasm/erc20/test/erc20_bg.wasm b/contracts/wasm/erc20/test/erc20_bg.wasm index 72d2bd6b40..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 282d50aa0e..e4c1ffd7c1 100644 --- a/contracts/wasm/erc20/test/erc20_test.go +++ b/contracts/wasm/erc20/test/erc20_test.go @@ -68,7 +68,7 @@ func approve(ctx *wasmsolo.SoloContext, from, to *wasmsolo.SoloAgent, amount uin appr := erc20.ScFuncs.Approve(ctx.Sign(from)) appr.Params.Delegation().SetValue(to.ScAgentID()) appr.Params.Amount().SetValue(amount) - appr.Func.TransferIotas(1).Post() + appr.Func.Post() return ctx.Err } @@ -76,7 +76,7 @@ func transfer(ctx *wasmsolo.SoloContext, from, to *wasmsolo.SoloAgent, amount ui tx := erc20.ScFuncs.Transfer(ctx.Sign(from)) tx.Params.Account().SetValue(to.ScAgentID()) tx.Params.Amount().SetValue(amount) - tx.Func.TransferIotas(1).Post() + tx.Func.Post() return ctx.Err } @@ -85,7 +85,7 @@ func transferFrom(ctx *wasmsolo.SoloContext, delegate, from, to *wasmsolo.SoloAg tx.Params.Account().SetValue(from.ScAgentID()) tx.Params.Recipient().SetValue(to.ScAgentID()) tx.Params.Amount().SetValue(amount) - tx.Func.TransferIotas(1).Post() + tx.Func.Post() return ctx.Err } diff --git a/contracts/wasm/erc721/src/erc721.rs b/contracts/wasm/erc721/src/erc721.rs index 503bc78f26..656740c01e 100644 --- a/contracts/wasm/erc721/src/erc721.rs +++ b/contracts/wasm/erc721/src/erc721.rs @@ -73,7 +73,7 @@ fn transfer(ctx: &ScFuncContext, state: &MutableErc721State, from: &ScAgentID, t } fn zero() -> ScAgentID { - ScAgentID::from_bytes(&[]) + agent_id_from_bytes(&[]) } /////////////////////////// SC FUNCS //////////////////////////// diff --git a/contracts/wasm/erc721/test/erc721_bg.wasm b/contracts/wasm/erc721/test/erc721_bg.wasm index fc00c6c32a..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 77ed2f6d21..9bdbe14232 100644 --- a/contracts/wasm/erc721/test/erc721_test.go +++ b/contracts/wasm/erc721/test/erc721_test.go @@ -161,7 +161,7 @@ func approve(ctx *wasmsolo.SoloContext, owner, approved *wasmsolo.SoloAgent, tok 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 wasmtypes.ScHash) *wasmtypes.ScAgentID { @@ -189,7 +189,7 @@ func isApprovedForAll(t *testing.T, ctx *wasmsolo.SoloContext, owner, friend *wa 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 wasmtypes.ScHash) wasmtypes.ScAgentID { @@ -204,7 +204,7 @@ 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 wasmtypes.ScHash) { @@ -212,5 +212,5 @@ func transferFrom(ctx *wasmsolo.SoloContext, sender, from, to *wasmsolo.SoloAgen 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/fairauction/go/fairauction/fairauction.go b/contracts/wasm/fairauction/go/fairauction/fairauction.go index 62b9322886..9f11e5494c 100644 --- a/contracts/wasm/fairauction/go/fairauction/fairauction.go +++ b/contracts/wasm/fairauction/go/fairauction/fairauction.go @@ -180,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) { diff --git a/contracts/wasm/fairauction/src/fairauction.rs b/contracts/wasm/fairauction/src/fairauction.rs index 6f3b4c1644..76a6b30e66 100644 --- a/contracts/wasm/fairauction/src/fairauction.rs +++ b/contracts/wasm/fairauction/src/fairauction.rs @@ -167,7 +167,7 @@ pub fn func_start_auction(ctx: &ScFuncContext, f: &StartAuctionContext) { description: description, duration: duration, highest_bid: 0, - highest_bidder: ScAgentID::from_bytes(&[0; 37]), + 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) { @@ -205,10 +205,10 @@ pub fn view_get_info(ctx: &ScViewContext, f: &GetInfoContext) { 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/test/fairauction_bg.wasm b/contracts/wasm/fairauction/test/fairauction_bg.wasm index 0095801e80..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 8219200521..b4efe52675 100644 --- a/contracts/wasm/fairauction/test/fairauction_test.go +++ b/contracts/wasm/fairauction/test/fairauction_test.go @@ -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) @@ -120,17 +125,22 @@ func TestFaOneBidTooLow(t *testing.T) { 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/fairauction.ts b/contracts/wasm/fairauction/ts/fairauction/fairauction.ts index 1b34e2e1ff..8f3e31efca 100644 --- a/contracts/wasm/fairauction/ts/fairauction/fairauction.ts +++ b/contracts/wasm/fairauction/ts/fairauction/fairauction.ts @@ -42,7 +42,7 @@ export function funcFinalizeAuction(ctx: wasmlib.ScFuncContext, f: sc.FinalizeAu let size = bidderList.length(); 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, wasmtypes.IOTA, bid.amount); } @@ -172,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 { @@ -200,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/fairroulette/go/fairroulette/fairroulette.go b/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go index 67d70bba54..cfc5bb5f21 100644 --- a/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go +++ b/contracts/wasm/fairroulette/go/fairroulette/fairroulette.go @@ -114,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() } } } @@ -212,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. @@ -227,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/src/fairroulette.rs b/contracts/wasm/fairroulette/src/fairroulette.rs index 9b897835e2..00424e9070 100644 --- a/contracts/wasm/fairroulette/src/fairroulette.rs +++ b/contracts/wasm/fairroulette/src/fairroulette.rs @@ -114,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(); } } } @@ -215,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. @@ -230,7 +227,7 @@ pub fn func_pay_winners(ctx: &ScFuncContext, f: &PayWinnersContext) { 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 diff --git a/contracts/wasm/fairroulette/test/fairroulette_bg.wasm b/contracts/wasm/fairroulette/test/fairroulette_bg.wasm index 004331c959..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 d937c7715e..4d10887e26 100644 --- a/contracts/wasm/fairroulette/test/fairroulette_test.go +++ b/contracts/wasm/fairroulette/test/fairroulette_test.go @@ -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/fairroulette.ts b/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts index f5ebb791b3..a7161c4409 100644 --- a/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts +++ b/contracts/wasm/fairroulette/ts/fairroulette/fairroulette.ts @@ -111,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(); } } } @@ -212,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. @@ -227,7 +224,7 @@ export function funcPayWinners(ctx: wasmlib.ScFuncContext, f: sc.PayWinnersConte 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 diff --git a/contracts/wasm/helloworld/test/helloworld_bg.wasm b/contracts/wasm/helloworld/test/helloworld_bg.wasm index b5d2f48bab..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 e385fddb4b..a027332cfb 100644 --- a/contracts/wasm/helloworld/test/helloworld_test.go +++ b/contracts/wasm/helloworld/test/helloworld_test.go @@ -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/inccounter/go/inccounter/inccounter.go b/contracts/wasm/inccounter/go/inccounter/inccounter.go index 7df1839aee..9a1ee47c00 100644 --- a/contracts/wasm/inccounter/go/inccounter/inccounter.go +++ b/contracts/wasm/inccounter/go/inccounter/inccounter.go @@ -55,7 +55,7 @@ func funcIncrement(ctx wasmlib.ScFuncContext, f *IncrementContext) { func funcIncrementWithDelay(ctx wasmlib.ScFuncContext, f *IncrementWithDelayContext) { delay := f.Params.Delay().Value() inc := ScFuncs.CallIncrement(ctx) - inc.Func.Delay(delay).TransferIotas(1).Post() + inc.Func.Delay(delay).Post() } func funcLocalStateInternalCall(ctx wasmlib.ScFuncContext, f *LocalStateInternalCallContext) { @@ -93,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() } } @@ -110,7 +110,7 @@ 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 @@ -214,7 +214,7 @@ 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) { diff --git a/contracts/wasm/inccounter/src/inccounter.rs b/contracts/wasm/inccounter/src/inccounter.rs index 676c8ff3d9..5750a09296 100644 --- a/contracts/wasm/inccounter/src/inccounter.rs +++ b/contracts/wasm/inccounter/src/inccounter.rs @@ -47,7 +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(); + inc.func.delay(delay).post(); } pub fn func_local_state_internal_call(ctx: &ScFuncContext, f: &LocalStateInternalCallContext) { @@ -95,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(); } } @@ -112,7 +112,7 @@ 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) { @@ -216,7 +216,7 @@ 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) { diff --git a/contracts/wasm/inccounter/test/inccounter_bg.wasm b/contracts/wasm/inccounter/test/inccounter_bg.wasm index 74acb7588e..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 12b57909f9..2046564ad6 100644 --- a/contracts/wasm/inccounter/test/inccounter_test.go +++ b/contracts/wasm/inccounter/test/inccounter_test.go @@ -33,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) @@ -43,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) @@ -58,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)) @@ -70,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) @@ -80,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) @@ -90,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)) @@ -102,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) @@ -112,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) { @@ -135,34 +135,36 @@ 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 TestVliCodec(t *testing.T) { - wasmhost.DisableWasmTimeout = true ctx := setupTest(t) - wasmhost.DisableWasmTimeout = false f := inccounter.ScFuncs.TestVliCodec(ctx) - f.Func.TransferIotas(1).Post() + save := wasmhost.DisableWasmTimeout + wasmhost.DisableWasmTimeout = false + f.Func.Post() + wasmhost.DisableWasmTimeout = save require.NoError(t, ctx.Err) } func TestVluCodec(t *testing.T) { - wasmhost.DisableWasmTimeout = true ctx := setupTest(t) - wasmhost.DisableWasmTimeout = false f := inccounter.ScFuncs.TestVluCodec(ctx) - f.Func.TransferIotas(1).Post() + save := wasmhost.DisableWasmTimeout + wasmhost.DisableWasmTimeout = false + f.Func.Post() + wasmhost.DisableWasmTimeout = save require.NoError(t, ctx.Err) } @@ -195,24 +197,24 @@ func TestVlu(t *testing.T) { } 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/inccounter.ts b/contracts/wasm/inccounter/ts/inccounter/inccounter.ts index 3c3524186b..d576686478 100644 --- a/contracts/wasm/inccounter/ts/inccounter/inccounter.ts +++ b/contracts/wasm/inccounter/ts/inccounter/inccounter.ts @@ -47,7 +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(); + inc.func.delay(delay).post(); } export function funcLocalStateInternalCall(ctx: wasmlib.ScFuncContext, f: sc.LocalStateInternalCallContext): void { @@ -83,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(); } } @@ -100,11 +100,11 @@ 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(); } export function funcTestVliCodec(ctx: wasmlib.ScFuncContext, f: sc.TestVliCodecContext): void { - for (let i: i64 = -1000000; i < 1000000; i++) { + for (let i: i64 = -1600; i < 1600; i++) { let enc = new wasmtypes.WasmEncoder(); wasmtypes.int64Encode(enc, i); let buf = enc.buf(); @@ -144,7 +144,7 @@ export function funcTestVliCodec(ctx: wasmlib.ScFuncContext, f: sc.TestVliCodecC } export function funcTestVluCodec(ctx: wasmlib.ScFuncContext, f: sc.TestVluCodecContext): void { - for (let i: u64 = 0; i < 2000000; i++) { + for (let i: u64 = 0; i < 3200; i++) { let enc = new wasmtypes.WasmEncoder(); wasmtypes.uint64Encode(enc, i); let buf = enc.buf(); @@ -234,7 +234,7 @@ 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 { diff --git a/contracts/wasm/testcore/go/testcore/testcore.go b/contracts/wasm/testcore/go/testcore/testcore.go index 7a302e2b49..3c2bce1111 100644 --- a/contracts/wasm/testcore/go/testcore/testcore.go +++ b/contracts/wasm/testcore/go/testcore/testcore.go @@ -153,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) { diff --git a/contracts/wasm/testcore/src/testcore.rs b/contracts/wasm/testcore/src/testcore.rs index 0f97c9fee0..aacb6bb788 100644 --- a/contracts/wasm/testcore/src/testcore.rs +++ b/contracts/wasm/testcore/src/testcore.rs @@ -160,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) { diff --git a/contracts/wasm/testcore/test/2chains_test.go b/contracts/wasm/testcore/test/2chains_test.go index 40ff5d02c6..957fc83cf2 100644 --- a/contracts/wasm/testcore/test/2chains_test.go +++ b/contracts/wasm/testcore/test/2chains_test.go @@ -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 03b4a33b1b..a8d3442b32 100644 --- a/contracts/wasm/testcore/test/concurrency_test.go +++ b/contracts/wasm/testcore/test/concurrency_test.go @@ -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/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 9a897ad579..a8a029677a 100644 --- a/contracts/wasm/testcore/test/sandbox_panic_test.go +++ b/contracts/wasm/testcore/test/sandbox_panic_test.go @@ -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 06eac7ecbe..dd43db735c 100644 --- a/contracts/wasm/testcore/test/spawn_test.go +++ b/contracts/wasm/testcore/test/spawn_test.go @@ -13,8 +13,8 @@ func TestSpawn(t *testing.T) { ctx := deployTestCore(t, w) f := testcore.ScFuncs.Spawn(ctx) - f.Params.ProgHash().SetValue(ctx.Convertor.ScHash(&ctx.Hprog)) - f.Func.TransferIotas(1).Post() + f.Params.ProgHash().SetValue(ctx.Convertor.ScHash(ctx.Hprog)) + f.Func.Post() require.NoError(t, ctx.Err) spawnedName := testcore.ScName + "_spawned" diff --git a/contracts/wasm/testcore/test/testcore_bg.wasm b/contracts/wasm/testcore/test/testcore_bg.wasm index f40473f847..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 57b0280479..c64c87aedc 100644 --- a/contracts/wasm/testcore/test/testcore_test.go +++ b/contracts/wasm/testcore/test/testcore_test.go @@ -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 } @@ -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 f3ea6b68f2..e95571724d 100644 --- a/contracts/wasm/testcore/test/types_test.go +++ b/contracts/wasm/testcore/test/types_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" ) +//nolint:dupl func TestTypesFull(t *testing.T) { run2(t, func(t *testing.T, w bool) { ctx := deployTestCore(t, w) @@ -19,18 +20,19 @@ func TestTypesFull(t *testing.T) { f.Params.ChainID().SetValue(ctx.ChainID()) f.Params.ContractID().SetValue(ctx.AccountID()) hashValue := hashing.HashStrings("Hash") - f.Params.Hash().SetValue(ctx.Convertor.ScHash(&hashValue)) + 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) @@ -41,7 +43,7 @@ func TestTypesView(t *testing.T) { v.Params.ChainID().SetValue(ctx.ChainID()) v.Params.ContractID().SetValue(ctx.AccountID()) hashValue := hashing.HashStrings("Hash") - v.Params.Hash().SetValue(ctx.Convertor.ScHash(&hashValue)) + 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) diff --git a/contracts/wasm/testcore/ts/testcore/testcore.ts b/contracts/wasm/testcore/ts/testcore/testcore.ts index ab91309231..e50a7631ae 100644 --- a/contracts/wasm/testcore/ts/testcore/testcore.ts +++ b/contracts/wasm/testcore/ts/testcore/testcore.ts @@ -160,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 { diff --git a/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm b/contracts/wasm/testwasmlib/test/testwasmlib_bg.wasm index ce37df28f0..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_test.go b/contracts/wasm/testwasmlib/test/testwasmlib_test.go index 5c3fa8857b..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 ( @@ -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) } @@ -101,7 +104,7 @@ func testValidParams(t *testing.T) *wasmsolo.SoloContext { 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 } @@ -117,7 +120,7 @@ func TestValidSizeParams(t *testing.T) { 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(), paramMismatch) }) @@ -136,20 +139,20 @@ func TestInvalidSizeParams(t *testing.T) { if allLengths[index] != 1 { pt := testwasmlib.ScFuncs.ParamTypes(ctx) pt.Params.Param().GetBytes(param).SetValue(make([]byte, 1)) - pt.Func.TransferIotas(1).Post() + 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.TransferIotas(1).Post() + 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.TransferIotas(1).Post() + pt.Func.Post() require.Error(t, ctx.Err) require.Contains(t, ctx.Err.Error(), invalidLength) }) @@ -199,19 +202,19 @@ func TestClearArray(t *testing.T) { as := testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") as.Params.Value().SetValue("Simple Minds") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) as = testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") as.Params.Value().SetValue("Dire Straits") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) as = testwasmlib.ScFuncs.ArrayAppend(ctx) as.Params.Name().SetValue("bands") as.Params.Value().SetValue("ELO") - as.Func.TransferIotas(1).Post() + as.Func.Post() require.NoError(t, ctx.Err) al := testwasmlib.ScFuncs.ArrayLength(ctx) @@ -233,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) @@ -255,28 +258,27 @@ 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("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("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) @@ -290,7 +292,7 @@ func TestClearMap(t *testing.T) { ac := testwasmlib.ScFuncs.MapClear(ctx) ac.Params.Name().SetValue("albums") - ac.Func.TransferIotas(1).Post() + ac.Func.Post() require.NoError(t, ctx.Err) av = testwasmlib.ScFuncs.MapValue(ctx) @@ -330,7 +332,7 @@ 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) @@ -347,7 +349,7 @@ func TestMultiRandom(t *testing.T) { 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) diff --git a/contracts/wasm/timestamp/go/timestamp/consts.go b/contracts/wasm/timestamp/go/timestamp/consts.go index bd40a8f418..3e11452c57 100644 --- a/contracts/wasm/timestamp/go/timestamp/consts.go +++ b/contracts/wasm/timestamp/go/timestamp/consts.go @@ -19,10 +19,6 @@ const ( ResultTimestamp = "timestamp" ) -const ( - StateTimestamp = "timestamp" -) - const ( FuncNow = "now" ViewGetTimestamp = "getTimestamp" diff --git a/contracts/wasm/timestamp/go/timestamp/state.go b/contracts/wasm/timestamp/go/timestamp/state.go index 10998f42aa..6c04f0877a 100644 --- a/contracts/wasm/timestamp/go/timestamp/state.go +++ b/contracts/wasm/timestamp/go/timestamp/state.go @@ -13,10 +13,6 @@ type ImmutabletimestampState struct { proxy wasmtypes.Proxy } -func (s ImmutabletimestampState) Timestamp() wasmtypes.ScImmutableUint64 { - return wasmtypes.NewScImmutableUint64(s.proxy.Root(StateTimestamp)) -} - type MutabletimestampState struct { proxy wasmtypes.Proxy } @@ -24,7 +20,3 @@ type MutabletimestampState struct { func (s MutabletimestampState) AsImmutable() ImmutabletimestampState { return ImmutabletimestampState(s) } - -func (s MutabletimestampState) Timestamp() wasmtypes.ScMutableUint64 { - return wasmtypes.NewScMutableUint64(s.proxy.Root(StateTimestamp)) -} diff --git a/contracts/wasm/timestamp/go/timestamp/timestamp.go b/contracts/wasm/timestamp/go/timestamp/timestamp.go index e84a4ad822..c16d40a25b 100644 --- a/contracts/wasm/timestamp/go/timestamp/timestamp.go +++ b/contracts/wasm/timestamp/go/timestamp/timestamp.go @@ -6,9 +6,8 @@ package timestamp 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 f273364817..3f901f04f5 100644 --- a/contracts/wasm/timestamp/schema.yaml +++ b/contracts/wasm/timestamp/schema.yaml @@ -3,7 +3,6 @@ description: Extremely simple timestamp server structs: {} typedefs: {} state: - timestamp: Uint64 // last official timestamp generated funcs: now: views: 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/state.rs b/contracts/wasm/timestamp/src/state.rs index 704666f724..35fe5c6ee0 100644 --- a/contracts/wasm/timestamp/src/state.rs +++ b/contracts/wasm/timestamp/src/state.rs @@ -17,23 +17,7 @@ pub struct ImmutabletimestampState { pub(crate) proxy: Proxy, } -impl ImmutabletimestampState { - pub fn timestamp(&self) -> ScImmutableUint64 { - ScImmutableUint64::new(self.proxy.root(STATE_TIMESTAMP)) - } -} - #[derive(Clone)] pub struct MutabletimestampState { pub(crate) proxy: Proxy, } - -impl MutabletimestampState { - pub fn as_immutable(&self) -> ImmutabletimestampState { - ImmutabletimestampState { proxy: self.proxy.root("") } - } - - pub fn timestamp(&self) -> ScMutableUint64 { - ScMutableUint64::new(self.proxy.root(STATE_TIMESTAMP)) - } -} 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 8f793791a7..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 bc353b842e..1eb2423fee 100644 --- a/contracts/wasm/timestamp/test/timestamp_test.go +++ b/contracts/wasm/timestamp/test/timestamp_test.go @@ -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 b3856cae71..f2926df660 100644 --- a/contracts/wasm/timestamp/ts/timestamp/consts.ts +++ b/contracts/wasm/timestamp/ts/timestamp/consts.ts @@ -13,8 +13,6 @@ export const HScName = new wasmtypes.ScHname(0x3988002e); export const ResultTimestamp = "timestamp"; -export const StateTimestamp = "timestamp"; - export const FuncNow = "now"; export const ViewGetTimestamp = "getTimestamp"; diff --git a/contracts/wasm/timestamp/ts/timestamp/state.ts b/contracts/wasm/timestamp/ts/timestamp/state.ts index 99e8c93277..14ff8b02f4 100644 --- a/contracts/wasm/timestamp/ts/timestamp/state.ts +++ b/contracts/wasm/timestamp/ts/timestamp/state.ts @@ -9,17 +9,10 @@ import * as wasmtypes from "wasmlib/wasmtypes"; import * as sc from "./index"; export class ImmutabletimestampState extends wasmtypes.ScProxy { - timestamp(): wasmtypes.ScImmutableUint64 { - return new wasmtypes.ScImmutableUint64(this.proxy.root(sc.StateTimestamp)); - } } export class MutabletimestampState extends wasmtypes.ScProxy { asImmutable(): sc.ImmutabletimestampState { return new sc.ImmutabletimestampState(this.proxy); } - - timestamp(): wasmtypes.ScMutableUint64 { - return new wasmtypes.ScMutableUint64(this.proxy.root(sc.StateTimestamp)); - } } 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/test/tokenregistry_bg.wasm b/contracts/wasm/tokenregistry/test/tokenregistry_bg.wasm index 9d8b841681..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/documentation/tutorial-examples/test/example_tutorial_bg.wasm b/documentation/tutorial-examples/test/example_tutorial_bg.wasm index f3bb2be086..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 1eab4fdde9..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 diff --git a/go.sum b/go.sum index 2b7ccbbff9..6ed3f6ab95 100644 --- a/go.sum +++ b/go.sum @@ -153,6 +153,8 @@ github.com/bygui86/multi-profile/v2 v2.1.0 h1:x/jPqeL/6hJqLXoDI/H5zLPsSFbDR6IEbr github.com/bygui86/multi-profile/v2 v2.1.0/go.mod h1:f4qCZiQo1nnJdwbPoADUtdDXg3hhnpfgZ9iq3/kW4BA= 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= diff --git a/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm b/packages/vm/core/testcore/sbtests/sbtestsc/testcore_bg.wasm index f40473f847..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/wasmvm/wasmhost/wasmcontext.go b/packages/wasmvm/wasmhost/wasmcontext.go index dd121a894b..3e7d1ef1a4 100644 --- a/packages/wasmvm/wasmhost/wasmcontext.go +++ b/packages/wasmvm/wasmhost/wasmcontext.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package wasmhost import ( @@ -14,6 +17,7 @@ const ( type ISandbox interface { Call(funcNr int32, params []byte) []byte + Tracef(format string, args ...interface{}) } type WasmContext struct { @@ -72,7 +76,7 @@ func (wc *WasmContext) Call(ctx interface{}) (dict.Dict, error) { return nil, nil } - wc.log().Debugf("Calling " + wc.funcName) + wc.tracef("Calling " + wc.funcName) wc.results = nil err := wc.callFunction() if err != nil { @@ -95,6 +99,9 @@ func (wc *WasmContext) callFunction() error { 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 } @@ -126,7 +133,14 @@ func (wc *WasmContext) log() iscp.LogInterface { } func (wc *WasmContext) Sandbox(funcNr int32, params []byte) []byte { - return wc.sandbox.Call(funcNr, params) + 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 @@ -143,6 +157,9 @@ func (wc *WasmContext) state() kv.KVStoreReader { } 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") @@ -155,6 +172,9 @@ func (wc *WasmContext) StateExists(key []byte) bool { if err != nil { panic("StateExists: " + err.Error()) } + if HostTracing { + wc.tracef("StateExists(%s) = %v", traceHex(key), exists) + } return exists } @@ -163,13 +183,82 @@ func (wc *WasmContext) StateGet(key []byte) []byte { 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 index 5531a72637..587fe97063 100644 --- a/packages/wasmvm/wasmhost/wasmcontextsandbox.go +++ b/packages/wasmvm/wasmhost/wasmcontextsandbox.go @@ -149,7 +149,7 @@ func (s *WasmContextSandbox) Tracef(format string, args ...interface{}) { //////////////////// sandbox functions \\\\\\\\\\\\\\\\\\\\ func (s *WasmContextSandbox) fnAccountID(args []byte) []byte { - return s.common.AccountID().Bytes() + return s.cvt.ScAgentID(s.common.AccountID()).Bytes() } func (s *WasmContextSandbox) fnBalance(args []byte) []byte { @@ -191,23 +191,23 @@ func (s *WasmContextSandbox) callUnlocked(contract, function iscp.Hname, params } func (s *WasmContextSandbox) fnCaller(args []byte) []byte { - return s.ctx.Caller().Bytes() + return s.cvt.ScAgentID(s.ctx.Caller()).Bytes() } func (s *WasmContextSandbox) fnChainID(args []byte) []byte { - return s.common.ChainID().Bytes() + return s.cvt.ScChainID(s.common.ChainID()).Bytes() } func (s *WasmContextSandbox) fnChainOwnerID(args []byte) []byte { - return s.common.ChainOwnerID().Bytes() + return s.cvt.ScAgentID(s.common.ChainOwnerID()).Bytes() } func (s *WasmContextSandbox) fnContract(args []byte) []byte { - return s.common.Contract().Bytes() + return s.cvt.ScHname(s.common.Contract()).Bytes() } func (s *WasmContextSandbox) fnContractCreator(args []byte) []byte { - return s.common.ContractCreator().Bytes() + return s.cvt.ScAgentID(s.common.ContractCreator()).Bytes() } func (s *WasmContextSandbox) fnDeployContract(args []byte) []byte { @@ -230,7 +230,7 @@ func (s *WasmContextSandbox) deployUnlocked(programHash hashing.HashValue, name, } func (s *WasmContextSandbox) fnEntropy(args []byte) []byte { - return s.ctx.GetEntropy().Bytes() + return s.cvt.ScHash(s.ctx.GetEntropy()).Bytes() } func (s *WasmContextSandbox) fnEvent(args []byte) []byte { @@ -252,7 +252,7 @@ func (s *WasmContextSandbox) fnMinted(args []byte) []byte { } func (s *WasmContextSandbox) fnPanic(args []byte) []byte { - s.common.Log().Panicf("WASM panic: %s", string(args)) + s.common.Log().Panicf(string(args)) return nil } @@ -270,26 +270,24 @@ func (s *WasmContextSandbox) fnPost(args []byte) []byte { transfer, err := colored.BalancesFromBytes(req.Transfer) s.checkErr(err) if len(transfer) == 0 { - s.Panicf("transfer is required for post") + transfer.Add(colored.Color{}, 1) } - s.Tracef("POST hContract '%s, hFunction %s, chain ", contract.String(), function.String(), chainID.String()) + 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 req.Delay != 0 { if !s.ctx.Send(chainID.AsAddress(), transfer, metadata) { s.Panicf("failed to send to %s", chainID.AsAddress().String()) } return nil } - timeLock := time.Unix(0, s.ctx.GetTimestamp()) - timeLock = timeLock.Add(time.Duration(req.Delay) * time.Second) options := iscp.SendOptions{ - TimeLock: uint32(timeLock.Unix()), + 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()) @@ -302,7 +300,7 @@ func (s *WasmContextSandbox) fnRequest(args []byte) []byte { } func (s *WasmContextSandbox) fnRequestID(args []byte) []byte { - return s.ctx.Request().ID().Bytes() + return s.cvt.ScRequestID(s.ctx.Request().ID()).Bytes() } func (s *WasmContextSandbox) fnResults(args []byte) []byte { @@ -354,7 +352,7 @@ func (s WasmContextSandbox) fnUtilsBase58Encode(args []byte) []byte { func (s WasmContextSandbox) fnUtilsBlsAddress(args []byte) []byte { address, err := s.common.Utils().BLS().AddressFromPublicKey(args) s.checkErr(err) - return address.Bytes() + return s.cvt.ScAddress(address).Bytes() } func (s WasmContextSandbox) fnUtilsBlsAggregate(args []byte) []byte { @@ -386,7 +384,7 @@ func (s WasmContextSandbox) fnUtilsBlsValid(args []byte) []byte { func (s WasmContextSandbox) fnUtilsEd25519Address(args []byte) []byte { address, err := s.common.Utils().ED25519().AddressFromPublicKey(args) s.checkErr(err) - return address.Bytes() + return s.cvt.ScAddress(address).Bytes() } func (s WasmContextSandbox) fnUtilsEd25519Valid(args []byte) []byte { @@ -399,13 +397,13 @@ func (s WasmContextSandbox) fnUtilsEd25519Valid(args []byte) []byte { } func (s WasmContextSandbox) fnUtilsHashBlake2b(args []byte) []byte { - return s.common.Utils().Hashing().Blake2b(args).Bytes() + return s.cvt.ScHash(s.common.Utils().Hashing().Blake2b(args)).Bytes() } func (s WasmContextSandbox) fnUtilsHashName(args []byte) []byte { - return codec.EncodeHname(s.common.Utils().Hashing().Hname(string(args))) + return s.cvt.ScHname(s.common.Utils().Hashing().Hname(string(args))).Bytes() } func (s WasmContextSandbox) fnUtilsHashSha3(args []byte) []byte { - return s.common.Utils().Hashing().Sha3(args).Bytes() + 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 index 3e52c923ee..e5837d1225 100644 --- a/packages/wasmvm/wasmhost/wasmconvertor.go +++ b/packages/wasmvm/wasmhost/wasmconvertor.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package wasmhost import ( @@ -77,7 +80,7 @@ func (cvt WasmConvertor) ScColor(color *colored.Color) wasmtypes.ScColor { return wasmtypes.ColorFromBytes(color.Bytes()) } -func (cvt WasmConvertor) ScHash(hash *hashing.HashValue) wasmtypes.ScHash { +func (cvt WasmConvertor) ScHash(hash hashing.HashValue) wasmtypes.ScHash { return wasmtypes.HashFromBytes(hash.Bytes()) } @@ -85,6 +88,6 @@ func (cvt WasmConvertor) ScHname(hname iscp.Hname) wasmtypes.ScHname { return wasmtypes.ScHname(hname) } -func (cvt WasmConvertor) ScRequestID(requestID *iscp.RequestID) wasmtypes.ScRequestID { +func (cvt WasmConvertor) ScRequestID(requestID iscp.RequestID) wasmtypes.ScRequestID { return wasmtypes.RequestIDFromBytes(requestID.Bytes()) } diff --git a/packages/wasmvm/wasmhost/wasmedgevm.go b/packages/wasmvm/wasmhost/wasmedgevm.go index d958e33364..d23f9d55a7 100644 --- a/packages/wasmvm/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 @@ -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,20 +57,6 @@ 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(proc *WasmProcessor) error { _ = vm.WasmVMBase.LinkHost(proc) @@ -105,16 +100,8 @@ 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 { @@ -193,3 +180,17 @@ func (vm *WasmEdgeVM) exportHostStateSet(args []interface{}) []interface{} { vm.HostStateSet(keyRef, keyLen, valRef, valLen) return nil } + +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) importModule(name string) { + vm.module = wasmedge.NewImportObject(name) + vm.importers = append(vm.importers, vm.module) +} diff --git a/packages/wasmvm/wasmhost/wasmervm.go b/packages/wasmvm/wasmhost/wasmervm.go index 4981429325..60297effb7 100644 --- a/packages/wasmvm/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,10 +27,6 @@ func NewWasmerVM() WasmVM { return vm } -func (vm *WasmerVM) NewInstance() WasmVM { - return &WasmerVM{store: vm.store} -} - //TODO func (vm *WasmerVM) Interrupt() { panic("implement me") @@ -60,13 +57,6 @@ func (vm *WasmerVM) LinkHost(proc *WasmProcessor) 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) @@ -81,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 { @@ -143,3 +137,10 @@ func (vm *WasmerVM) exportHostStateSet(args []wasmer.Value) ([]wasmer.Value, err vm.HostStateSet(keyRef, keyLen, valRef, valLen) 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/wasmgovm.go b/packages/wasmvm/wasmhost/wasmgovm.go index 3f1bb0d2b1..abd13da7e5 100644 --- a/packages/wasmvm/wasmhost/wasmgovm.go +++ b/packages/wasmvm/wasmhost/wasmgovm.go @@ -27,10 +27,6 @@ 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 } @@ -51,6 +47,10 @@ 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" { // note: on_load is funneled through onload() diff --git a/packages/wasmvm/wasmhost/wasmprocessor.go b/packages/wasmvm/wasmhost/wasmprocessor.go index 9a1f5970bc..f033d8b062 100644 --- a/packages/wasmvm/wasmhost/wasmprocessor.go +++ b/packages/wasmvm/wasmhost/wasmprocessor.go @@ -16,6 +16,7 @@ type WasmProcessor struct { contexts map[int32]*WasmContext currentContextID int32 funcTable *WasmFuncTable + gasFactorX uint64 instanceLock sync.Mutex log *logger.Logger mainProcessor *WasmProcessor @@ -32,10 +33,11 @@ var GoWasmVM func() WasmVM // GetProcessor creates a new Wasm VM processor. func GetProcessor(wasmBytes []byte, log *logger.Logger) (iscp.VMProcessor, error) { proc := &WasmProcessor{ - contexts: make(map[int32]*WasmContext), - funcTable: NewWasmFuncTable(), - log: log, - wasmVM: NewWasmTimeVM, + 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 @@ -58,7 +60,12 @@ func GetProcessor(wasmBytes []byte, log *logger.Logger) (iscp.VMProcessor, error if err != nil { return nil, err } + // 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 } @@ -74,7 +81,7 @@ func (proc *WasmProcessor) GetContext(id int32) *WasmContext { return proc.scContext } - mainProcessor := proc.MainProc() + mainProcessor := proc.mainProc() mainProcessor.contextLock.Lock() defer mainProcessor.contextLock.Unlock() @@ -118,12 +125,36 @@ func (proc *WasmProcessor) getSubProcessor(vmInstance WasmVM) *WasmProcessor { return processor } +func (proc *WasmProcessor) IsView(function string) bool { + return (proc.mainProc().funcTable.funcToIndex[function] & 0x8000) != 0 +} + func (proc *WasmProcessor) KillContext(id int32) { proc.contextLock.Lock() defer proc.contextLock.Unlock() 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.vm.NewInstance() @@ -140,22 +171,3 @@ func (proc *WasmProcessor) wasmContext(function string) *WasmContext { proc.contexts[wc.id] = wc return wc } - -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) -} - -func (proc *WasmProcessor) IsView(function string) bool { - return (proc.MainProc().funcTable.funcToIndex[function] & 0x8000) != 0 -} - -func (proc *WasmProcessor) MainProc() *WasmProcessor { - if proc.mainProcessor == nil { - return proc - } - return proc.mainProcessor -} diff --git a/packages/wasmvm/wasmhost/wasmtimevm.go b/packages/wasmvm/wasmhost/wasmtimevm.go index ebe3b0c1e8..4254ee3f4a 100644 --- a/packages/wasmvm/wasmhost/wasmtimevm.go +++ b/packages/wasmvm/wasmhost/wasmtimevm.go @@ -11,25 +11,82 @@ 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() { @@ -79,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/wasmvm/wasmhost/wasmvm.go b/packages/wasmvm/wasmhost/wasmvm.go index 1ca28b97b4..72aab26229 100644 --- a/packages/wasmvm/wasmhost/wasmvm.go +++ b/packages/wasmvm/wasmhost/wasmvm.go @@ -7,10 +7,10 @@ import ( "encoding/binary" "errors" "fmt" + "strings" "time" "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib" - "github.com/iotaledger/wasp/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes" ) const ( @@ -37,6 +37,9 @@ var ( ) type WasmVM interface { + GasBudget(budget uint64) + GasBurned() uint64 + GasDisable(disable bool) Instantiate() error Interrupt() LinkHost(proc *WasmProcessor) error @@ -51,32 +54,24 @@ type WasmVM interface { } type WasmVMBase struct { - proc *WasmProcessor - panicErr error cachedResult []byte + gasDisabled bool + panicErr error + 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 +} + +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 { @@ -84,9 +79,10 @@ func (vm *WasmVMBase) getContext(id int32) *WasmContext { } 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 @@ -109,11 +105,12 @@ func (vm *WasmVMBase) HostAbort(errMsg, fileName, line, col int32) { } func (vm *WasmVMBase) HostFdWrite(_fd, iovs, _size, written int32) int32 { - defer vm.catchPanicMessage() - impl := vm.proc.vm + vm.reportGasBurned() + defer vm.wrapUp() ctx := vm.getContext(0) ctx.log().Debugf("HostFdWrite(...)") + impl := vm.proc.vm // very basic implementation that expects fd to be stdout and iovs to be only one element ptr := impl.VMGetBytes(iovs, 8) @@ -131,13 +128,11 @@ func (vm *WasmVMBase) HostFdWrite(_fd, iovs, _size, written int32) int32 { } func (vm *WasmVMBase) HostStateGet(keyRef, keyLen, valRef, valLen int32) int32 { - defer vm.catchPanicMessage() - impl := vm.proc.vm + vm.reportGasBurned() + defer vm.wrapUp() ctx := vm.getContext(0) - if HostTracing { - vm.traceGet(ctx, keyRef, keyLen, valRef, valLen) - } + impl := vm.proc.vm // only check for existence ? if valLen < 0 { @@ -169,19 +164,20 @@ func (vm *WasmVMBase) HostStateGet(keyRef, keyLen, valRef, valLen int32) int32 { } func (vm *WasmVMBase) HostStateSet(keyRef, keyLen, valRef, valLen int32) { - defer vm.catchPanicMessage() - impl := vm.proc.vm + vm.reportGasBurned() + defer vm.wrapUp() ctx := vm.getContext(0) - if HostTracing { - vm.traceSet(ctx, keyRef, keyLen, valRef, valLen) - } + impl := vm.proc.vm // 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 } @@ -215,6 +211,14 @@ func (vm *WasmVMBase) LinkHost(proc *WasmProcessor) error { 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() @@ -236,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 } @@ -267,6 +274,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 } @@ -290,109 +300,34 @@ func (vm *WasmVMBase) VMSetBytes(offset, size int32, bytes []byte) int32 { return int32(len(bytes)) } -func (vm *WasmVMBase) traceGet(ctx *WasmContext, keyRef, keyLen, valRef, valLen int32) { - impl := vm.proc.vm - - // only check for existence ? - if valLen < 0 { - key := impl.VMGetBytes(keyRef, keyLen) - ctx.log().Debugf("StateExists(%s) = %v", vm.traceKey(key), ctx.StateExists(key)) - return - } - - // get value for key request, or get cached result request (keyLen == 0) - if keyLen >= 0 { - if keyLen == 0 { - ctx.log().Debugf(" => %s", vm.traceVal(vm.cachedResult)) - return - } - // retrieve value associated with key - key := impl.VMGetBytes(keyRef, keyLen) - ctx.log().Debugf("StateGet(%s)", vm.traceKey(key)) - return - } - - // sandbox func call request, keyLen is func nr - if keyLen == wasmlib.FnLog { - return - } - params := impl.VMGetBytes(valRef, valLen) - ctx.log().Debugf("Sandbox(%s)", vm.traceSandbox(keyLen, params)) -} - -func (vm *WasmVMBase) 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 (vm *WasmVMBase) traceSet(ctx *WasmContext, keyRef, keyLen, valRef, valLen int32) { - impl := vm.proc.vm - - // export name? - if keyRef == 0 { - name := string(impl.VMGetBytes(valRef, valLen)) - ctx.log().Debugf("ExportName(%d, %s)", keyLen, name) - return - } - - key := impl.VMGetBytes(keyRef, keyLen) - - // delete key ? - if valLen < 0 { - ctx.log().Debugf("StateDelete(%s)", vm.traceKey(key)) +// 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 } - // set key - val := impl.VMGetBytes(valRef, valLen) - ctx.log().Debugf("StateSet(%s, %s)", vm.traceKey(key), vm.traceVal(val)) -} - -func (vm *WasmVMBase) traceKey(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 (vm *WasmVMBase) traceVal(val []byte) string { - for _, b := range val { - if b < ' ' || b > '~' { - return hex(val) + // 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) } } - 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) + // rethrow and let nature run its course... + panic(panicMsg) } diff --git a/packages/wasmvm/wasmlib/go/wasmclient/clientfunc.go b/packages/wasmvm/wasmlib/go/wasmclient/clientfunc.go index 07654bbc88..82ab514548 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/go/wasmclient/decoder.go b/packages/wasmvm/wasmlib/go/wasmclient/decoder.go index 11d17e749f..3bf828b445 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/go/wasmclient/encoder.go b/packages/wasmvm/wasmlib/go/wasmclient/encoder.go index 3f4ce6f227..53fbeb8e79 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/go/wasmclient/seed.go b/packages/wasmvm/wasmlib/go/wasmclient/seed.go index 6c5cc8a7c4..c2b7abfadb 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/go/wasmclient/service.go b/packages/wasmvm/wasmlib/go/wasmclient/service.go index 57937b25f2..57c4d32a62 100644 --- a/packages/wasmvm/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" @@ -43,7 +43,7 @@ type IEventHandler interface { type Service struct { chainID *iscp.ChainID eventHandlers []IEventHandler - keyPair *ed25519.KeyPair + keyPair *cryptolib.KeyPair scHname iscp.Hname waspClient *client.WaspClient } @@ -74,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} @@ -99,7 +99,7 @@ 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{} } @@ -118,7 +118,7 @@ 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 } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/assets.go b/packages/wasmvm/wasmlib/go/wasmlib/assets.go index 9084fbe9e9..4d3c14ba18 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/assets.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/assets.go @@ -93,6 +93,15 @@ func NewScTransfer(color wasmtypes.ScColor, amount uint64) ScTransfers { 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) { diff --git a/packages/wasmvm/wasmlib/go/wasmlib/host.go b/packages/wasmvm/wasmlib/go/wasmlib/host.go index de4c54a3b2..dc97214259 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/host.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/host.go @@ -26,6 +26,9 @@ 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 { diff --git a/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go b/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go index c4c2c1a7bc..f2b2cd1c29 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/sandbox.go @@ -83,9 +83,6 @@ func (s ScSandbox) Balances() ScBalances { // calls a smart contract function func (s ScSandbox) call(hContract, hFunction wasmtypes.ScHname, params *ScDict, transfer ScTransfers) *ScImmutableDict { - if params == nil { - params = NewScDict() - } req := &wasmrequests.CallRequest{ Contract: hContract, Function: hFunction, @@ -143,9 +140,6 @@ func (s ScSandbox) Require(cond bool, msg string) { } func (s ScSandbox) Results(results *ScDict) { - if results == nil { - results = NewScDict() - } Sandbox(FnResults, results.Bytes()) } @@ -193,9 +187,6 @@ func (s ScSandboxFunc) Caller() wasmtypes.ScAgentID { // deploys a smart contract func (s ScSandboxFunc) DeployContract(programHash wasmtypes.ScHash, name, description string, initParams *ScDict) { - if initParams == nil { - initParams = NewScDict() - } req := &wasmrequests.DeployRequest{ ProgHash: programHash, Name: name, @@ -228,12 +219,6 @@ func (s ScSandboxFunc) Minted() ScBalances { // (delayed) posts a smart contract function request func (s ScSandboxFunc) Post(chainID wasmtypes.ScChainID, hContract, hFunction wasmtypes.ScHname, params *ScDict, transfer ScTransfers, delay uint32) { - if params == nil { - params = NewScDict() - } - if len(transfer) == 0 { - s.Panic("missing transfer") - } req := &wasmrequests.PostRequest{ ChainID: chainID, Contract: hContract, @@ -285,15 +270,10 @@ func (s ScSandboxFunc) RequestID() wasmtypes.ScRequestID { return wasmtypes.RequestIDFromBytes(Sandbox(FnRequestID, nil)) } -// transfer assetss to the specified Tangle ledger address +// transfer assets to the specified Tangle ledger address func (s ScSandboxFunc) Send(address wasmtypes.ScAddress, transfer ScTransfers) { // we need some assets to send - assets := uint64(0) - for _, amount := range transfer { - assets += amount - } - if assets == 0 { - // only try to send when non-zero assets + if transfer.IsEmpty() { return } diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go index 9ed3019507..7429229688 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmrequests/structs.go @@ -244,3 +244,59 @@ func (o MutableSendRequest) SetValue(value *SendRequest) { 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 index 8d4db04082..df05456283 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/codec.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/codec.go @@ -59,6 +59,14 @@ func (d *WasmDecoder) FixedBytes(size uint32) []byte { 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() diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go index 0a8feae932..ab45d51e4f 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/scaddress.go @@ -6,9 +6,9 @@ package wasmtypes // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ const ( - ScAddressEd25519 byte = 0 // length 32 - ScAddressNFT byte = 1 // actually 16, length 20 - ScAddressAlias byte = 2 // actually 8, length 20 + ScAddressAlias byte = 2 + ScAddressEd25519 byte = 0 + ScAddressNFT byte = 1 ScAddressLength = 33 ) @@ -32,17 +32,21 @@ func (o ScAddress) String() string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ +// TODO address type-dependent encoding/decoding? func AddressDecode(dec *WasmDecoder) ScAddress { - return addressFromBytesUnchecked(dec.FixedBytes(ScAddressLength)) + addr := ScAddress{} + copy(addr.id[:], dec.FixedBytes(ScAddressLength)) + return addr } func AddressEncode(enc *WasmEncoder, value ScAddress) { - enc.FixedBytes(value.Bytes(), ScAddressLength) + enc.FixedBytes(value.id[:], ScAddressLength) } func AddressFromBytes(buf []byte) ScAddress { + addr := ScAddress{} if len(buf) == 0 { - return ScAddress{} + return addr } if len(buf) != ScAddressLength { panic("invalid Address length") @@ -50,7 +54,8 @@ func AddressFromBytes(buf []byte) ScAddress { if buf[0] > ScAddressAlias { panic("invalid Address type") } - return addressFromBytesUnchecked(buf) + copy(addr.id[:], buf) + return addr } func AddressToBytes(value ScAddress) []byte { @@ -62,12 +67,6 @@ func AddressToString(value ScAddress) string { return Base58Encode(value.id[:]) } -func addressFromBytesUnchecked(buf []byte) ScAddress { - o := ScAddress{} - copy(o.id[:], buf) - return o -} - // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ type ScImmutableAddress struct { diff --git a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go index 7a832aa7ce..0189eaee5c 100644 --- a/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go +++ b/packages/wasmvm/wasmlib/go/wasmlib/wasmtypes/schname.go @@ -13,9 +13,7 @@ const ScHnameLength = 4 type ScHname uint32 -//func HnameFromString(name string) ScHname { -// return HnameFromBytes(wasmlib.Sandbox(wasmstore.FnUtilsHashName, []byte(name))) -//} +var NewScHname func(name string) ScHname func (o ScHname) Bytes() []byte { return HnameToBytes(o) diff --git a/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml b/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml index afbd41a39a..2b94ced241 100644 --- a/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml +++ b/packages/wasmvm/wasmlib/interfaces/wasmrequests.yaml @@ -26,6 +26,11 @@ structs: address: Address transfer: Bytes + TransferRequest: + agentID: AgentID + create: Bool + transfer: Bytes + typedefs: {} state: {} funcs: {} diff --git a/packages/wasmvm/wasmlib/src/assets.rs b/packages/wasmvm/wasmlib/src/assets.rs index 7f405eb47e..a92e9eb091 100644 --- a/packages/wasmvm/wasmlib/src/assets.rs +++ b/packages/wasmvm/wasmlib/src/assets.rs @@ -99,6 +99,15 @@ impl 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); diff --git a/packages/wasmvm/wasmlib/src/sandbox.rs b/packages/wasmvm/wasmlib/src/sandbox.rs index 49cd5e504f..92d14ae628 100644 --- a/packages/wasmvm/wasmlib/src/sandbox.rs +++ b/packages/wasmvm/wasmlib/src/sandbox.rs @@ -233,9 +233,6 @@ pub trait ScSandboxFunc: ScSandbox { // (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) { - if transfer.balances().colors().len() == 0 { - self.panic("missing transfer"); - } let req = wasmrequests::PostRequest { chain_id, contract: h_contract, @@ -285,17 +282,10 @@ pub trait ScSandboxFunc: ScSandbox { return request_id_from_bytes(&sandbox(FN_REQUEST_ID, &[])); } - // transfer assetss to the specified Tangle ledger address + // transfer assets to the specified Tangle ledger address fn send(&self, address: &ScAddress, transfer: &ScTransfers) { // we need some assets to send - let mut assets: u64 = 0; - let colors = transfer.balances().colors(); - for i in 0..colors.len() { - let color = colors.get(i).unwrap(); - assets += transfer.balances().balance(color); - } - if assets == 0 { - // only try to send when non-zero assets + if transfer.is_empty() { return; } diff --git a/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs b/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs index b5a9f3f61e..8507a87bea 100644 --- a/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs +++ b/packages/wasmvm/wasmlib/src/wasmrequests/structs.rs @@ -277,3 +277,67 @@ impl MutableSendRequest { 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 index 3da32e57a2..6c6415f1af 100644 --- a/packages/wasmvm/wasmlib/src/wasmtypes/codec.rs +++ b/packages/wasmvm/wasmlib/src/wasmtypes/codec.rs @@ -42,6 +42,14 @@ impl WasmDecoder<'_> { 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(); @@ -137,7 +145,7 @@ impl WasmEncoder { // 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"); + panic(&("invalid fixed bytes length (".to_string() + &length.to_string() + "), found " + &value.len().to_string())); } self.buf.extend_from_slice(value); self diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs index 652f055cba..14193c3b86 100644 --- a/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scaddress.rs @@ -7,9 +7,9 @@ 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_ALIAS: u8 = 2; pub const SC_ADDRESS_LENGTH: usize = 33; diff --git a/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs b/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs index cee88eef69..0bddc3a23d 100644 --- a/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs +++ b/packages/wasmvm/wasmlib/src/wasmtypes/scagentid.rs @@ -20,10 +20,6 @@ impl ScAgentID { ScAgentID { address: address_from_bytes(&address.to_bytes()), hname: hname_from_bytes(&hname.to_bytes()) } } - pub fn from_bytes(buf: &[u8]) -> ScAgentID { - agent_id_from_bytes(buf) - } - pub fn address(&self) -> ScAddress { self.address.clone() } diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts b/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts index ee877e4b7b..1a4484ee8d 100644 --- a/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/arguments.ts @@ -1,7 +1,7 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import {Bytes, Int32, panic, Items, Item} from "." +import {Bytes, Int32, Item, Items, panic} from "." import {Encoder} from "./encoder" import {Buffer} from "./buffer"; diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/clientfunc.ts b/packages/wasmvm/wasmlib/ts/wasmclient/clientfunc.ts index b3ef97b507..c3fd9ed5dc 100644 --- a/packages/wasmvm/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; diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/colors.ts b/packages/wasmvm/wasmlib/ts/wasmclient/colors.ts index 475b229cb6..3d3e8d65f9 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/ts/wasmclient/configuration.ts b/packages/wasmvm/wasmlib/ts/wasmclient/configuration.ts index 4f25142a2f..5e1cdd7775 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/ts/wasmclient/decoder.ts b/packages/wasmvm/wasmlib/ts/wasmclient/decoder.ts index c83f5a9e64..f721171517 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/ts/wasmclient/results.ts b/packages/wasmvm/wasmlib/ts/wasmclient/results.ts index 49f28cf6c8..4bbb572b07 100644 --- a/packages/wasmvm/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"; diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/service.ts b/packages/wasmvm/wasmlib/ts/wasmclient/service.ts index 7175b2665f..a14bae2067 100644 --- a/packages/wasmvm/wasmlib/ts/wasmclient/service.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/service.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 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 {Hash, IKeyPair} from "./crypto"; +import {IOnLedger} from "./goshimmer/models/on_ledger"; +import {Colors} from "./colors"; +import {Buffer} from "./buffer"; export interface IEventHandler { callHandler(topic: string, params: string[]): void; @@ -42,7 +42,7 @@ export class Service { onLedger: boolean ): Promise { const chainId = this.serviceClient.configuration.chainId; - if (!onLedger) { + if (! onLedger) { // requested off-ledger request const requestID = await this.serviceClient.waspClient.postOffLedgerRequest(chainId, this.scHname, hFuncName, args, transfer, keyPair); return requestID; diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/serviceclient.ts b/packages/wasmvm/wasmlib/ts/wasmclient/serviceclient.ts index 2bcb81a278..01c27d586f 100644 --- a/packages/wasmvm/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; diff --git a/packages/wasmvm/wasmlib/ts/wasmclient/transfer.ts b/packages/wasmvm/wasmlib/ts/wasmclient/transfer.ts index 267eb32e12..06a1697803 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/ts/wasmclient/tsconfig.json b/packages/wasmvm/wasmlib/ts/wasmclient/tsconfig.json index 6154e4f4be..4066cb02ba 100644 --- a/packages/wasmvm/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/wasmvm/wasmlib/ts/wasmclient/waspclient.ts b/packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts index b81f0570b8..2087149090 100644 --- a/packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts +++ b/packages/wasmvm/wasmlib/ts/wasmclient/waspclient.ts @@ -6,8 +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"; +import {Colors} from "./colors"; +import {CoreAccountsService} from "./coreaccounts/service"; interface ICallViewResponse extends IResponse { Items: [{ Key: string; Value: string }]; @@ -102,8 +102,8 @@ export class WaspClient { 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; + ? 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 index 958f0da455..bea7c1445f 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/assets.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/assets.ts @@ -87,6 +87,16 @@ export class ScTransfers extends ScAssets { 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/index.ts b/packages/wasmvm/wasmlib/ts/wasmlib/index.ts index d93844e1c6..97e96f0e2b 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/index.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/index.ts @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + export * from "./assets" export * from "./context" export * from "./contract" diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts b/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts index 2a5cdbd05d..d014a69534 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/sandbox.ts @@ -226,9 +226,6 @@ export class ScSandboxFunc extends ScSandbox { // (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 { - if (transfer.balances().colors().length == 0) { - this.panic("missing transfer"); - } const req = new wasmrequests.PostRequest(); req.chainID = chainID; req.contract = hContract; @@ -274,17 +271,10 @@ export class ScSandboxFunc extends ScSandbox { return wasmtypes.requestIDFromBytes(sandbox(FnRequestID, null)); } - // transfer assetss to the specified Tangle ledger address + // transfer assets to the specified Tangle ledger address public send(address: wasmtypes.ScAddress, transfer: ScTransfers): void { // we need some assets to send - let assets: u64 = 0; - const colors = transfer.balances().colors(); - for (let i = 0; i < colors.length; i++) { - const color = colors[i]; - assets += transfer.balances().balance(color); - } - if (assets == 0) { - // only try to send when non-zero assets + if (transfer.isEmpty()) { return; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts index 710b243d43..e34ebc677a 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmrequests/structs.ts @@ -234,3 +234,57 @@ export class MutableSendRequest extends wasmtypes.ScProxy { 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/wasmtypes/codec.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts index 7f9fa92431..b3df713fe0 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/codec.ts @@ -1,9 +1,9 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import {FnUtilsBase58Encode, panic} from "../sandbox"; -import {stringFromBytes} from "./scstring"; import {sandbox} from "../host"; +import {FnUtilsBase58Encode, panic} from "../sandbox"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ @@ -51,6 +51,14 @@ export class WasmDecoder { 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(); @@ -119,20 +127,20 @@ export class WasmEncoder { } // encodes a single byte into the byte buffer - byte(value: u8): WasmEncoder { + 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[]): WasmEncoder { + 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): WasmEncoder { + fixedBytes(value: u8[], length: u32): wasmtypes.WasmEncoder { if ((value.length as u32) != length) { panic("invalid fixed bytes length"); } @@ -141,7 +149,7 @@ export class WasmEncoder { } // Variable Length Integer encoder, uses modified LEB128 - vliEncode(value: i64): WasmEncoder { + vliEncode(value: i64): wasmtypes.WasmEncoder { // bit 7 is always continuation bit // first group: 6 bits of data plus sign bit @@ -173,7 +181,7 @@ export class WasmEncoder { } // Variable Length Unsigned encoder, uses ULEB128 - vluEncode(value: u64): WasmEncoder { + vluEncode(value: u64): wasmtypes.WasmEncoder { // bit 7 is always continuation bit // first group of 7 data bits @@ -200,7 +208,7 @@ export class WasmEncoder { // wrapper for simplified use by hashtypes export function base58Encode(buf: u8[]): string { - return stringFromBytes(sandbox(FnUtilsBase58Encode, buf)); + return wasmtypes.stringFromBytes(sandbox(FnUtilsBase58Encode, buf)); } export function zeroes(count: u32): u8[] { diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts index a74b9433b7..cb40039708 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/proxy.ts @@ -1,10 +1,8 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import {WasmDecoder, WasmEncoder} from "./codec"; -import {uint32Decode, uint32Encode} from "./scuint32"; -import {stringToBytes} from "./scstring"; import {panic} from "../sandbox"; +import * as wasmtypes from "./index" export interface IKvStore { delete(key: u8[]): void; @@ -73,8 +71,8 @@ export class Proxy { } protected element(index: u32): Proxy { - let enc = new WasmEncoder(); - uint32Encode(enc, index); + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint32Encode(enc, index); // 0x23 is '#' return this.sub(0x23, enc.buf()); } @@ -87,8 +85,8 @@ export class Proxy { //TODO have a Grow function that grows an array? protected expand(length: u32): void { // update the length counter - let enc = new WasmEncoder(); - uint32Encode(enc, length); + let enc = new wasmtypes.WasmEncoder(); + wasmtypes.uint32Encode(enc, length); this.set(enc.buf()); } @@ -124,14 +122,14 @@ export class Proxy { if (buf.length == 0) { return 0; } - const dec = new WasmDecoder(buf) - return uint32Decode(dec); + 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, stringToBytes(key)); + return this.proxy(this.kvStore, wasmtypes.stringToBytes(key)); } set(value: u8[]): void { diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts index 3954875709..aa79518419 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scaddress.ts @@ -2,30 +2,26 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {base58Encode, WasmDecoder, WasmEncoder, zeroes} from "./codec"; -import {Proxy} from "./proxy"; -import {ScAgentID} from "./scagentid"; -import {bytesCompare} from "./scbytes"; -import {ScHname} from "./schname"; +import * as wasmtypes from "./index" // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ +export const ScAddressAlias : u8 = 2; export const ScAddressEd25519: u8 = 0; export const ScAddressNFT : u8 = 1; -export const ScAddressAlias : u8 = 2; export const ScAddressLength = 33; export class ScAddress { - id: u8[] = zeroes(ScAddressLength); + id: u8[] = wasmtypes.zeroes(ScAddressLength); - asAgentID(): ScAgentID { + asAgentID(): wasmtypes.ScAgentID { // agentID for address has Hname zero - return new ScAgentID(this, new ScHname(0)); + return new wasmtypes.ScAgentID(this, new wasmtypes.ScHname(0)); } public equals(other: ScAddress): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -41,11 +37,11 @@ export class ScAddress { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function addressDecode(dec: WasmDecoder): ScAddress { +export function addressDecode(dec: wasmtypes.WasmDecoder): ScAddress { return addressFromBytesUnchecked(dec.fixedBytes(ScAddressLength)) } -export function addressEncode(enc: WasmEncoder, value: ScAddress): void { +export function addressEncode(enc: wasmtypes.WasmEncoder, value: ScAddress): void { enc.fixedBytes(value.toBytes(), ScAddressLength) } @@ -68,7 +64,7 @@ export function addressToBytes(value: ScAddress): u8[] { export function addressToString(value: ScAddress): string { // TODO standardize human readable string - return base58Encode(value.id); + return wasmtypes.base58Encode(value.id); } function addressFromBytesUnchecked(buf: u8[]): ScAddress { @@ -80,9 +76,9 @@ function addressFromBytesUnchecked(buf: u8[]): ScAddress { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableAddress { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts index f12b754ec5..3d86126e97 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scagentid.ts @@ -2,20 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; -import {addressDecode, addressEncode, addressFromBytes, ScAddress, ScAddressAlias, ScAddressLength} from "./scaddress"; -import {hnameDecode, hnameEncode, hnameFromBytes, ScHname} from "./schname"; +import * as wasmtypes from "./index" // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export const ScAgentIDLength = 37; export class ScAgentID { - _address: ScAddress; - _hname: ScHname; + _address: wasmtypes.ScAddress; + _hname: wasmtypes.ScHname; - constructor(address: ScAddress, hname: ScHname) { + constructor(address: wasmtypes.ScAddress, hname: wasmtypes.ScHname) { this._address = address; this._hname = hname; } @@ -25,16 +22,16 @@ export class ScAgentID { this._hname.equals(other._hname); } - public address(): ScAddress { + public address(): wasmtypes.ScAddress { return this._address; } - public hname(): ScHname { + public hname(): wasmtypes.ScHname { return this._hname; } public isAddress(): bool { - return this._hname.equals(new ScHname(0)); + return this._hname.equals(new wasmtypes.ScHname(0)); } // convert to byte array representation @@ -50,32 +47,32 @@ export class ScAgentID { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function agentIDDecode(dec: WasmDecoder): ScAgentID { - return new ScAgentID(addressDecode(dec), hnameDecode(dec)) +export function agentIDDecode(dec: wasmtypes.WasmDecoder): ScAgentID { + return new ScAgentID(wasmtypes.addressDecode(dec), wasmtypes.hnameDecode(dec)) } -export function agentIDEncode(enc: WasmEncoder, value: ScAgentID): void { - addressEncode(enc, value._address); - hnameEncode(enc, value._hname); +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(addressFromBytes(buf), hnameFromBytes(buf)); + return new ScAgentID(wasmtypes.addressFromBytes(buf), wasmtypes.hnameFromBytes(buf)); } if (buf.length != ScAgentIDLength) { panic("invalid AgentID length"); } - if (buf[0] > ScAddressAlias) { + if (buf[0] > wasmtypes.ScAddressAlias) { panic("invalid AgentID address type"); } - return new ScAgentID( - addressFromBytes(buf.slice(0, ScAddressLength)), - hnameFromBytes(buf.slice(ScAddressLength))); + 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 WasmEncoder(); + const enc = new wasmtypes.WasmEncoder(); agentIDEncode(enc, value); return enc.buf(); } @@ -88,9 +85,9 @@ export function agentIDToString(value: ScAgentID): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableAgentID { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts index bf0fd997a3..3af9f5c8a4 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbool.ts @@ -2,8 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScBoolLength = 1; export const ScBoolFalse = 0x00 @@ -11,11 +10,11 @@ export const ScBoolTrue = 0xff // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function boolDecode(dec: WasmDecoder): bool { +export function boolDecode(dec: wasmtypes.WasmDecoder): bool { return dec.byte() != ScBoolFalse; } -export function boolEncode(enc: WasmEncoder, value: bool): void { +export function boolEncode(enc: wasmtypes.WasmEncoder, value: bool): void { enc.byte((value ? ScBoolTrue : ScBoolFalse) as u8); } @@ -46,9 +45,9 @@ export function boolToString(value: bool): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableBool { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts index 0e22898dbb..702fd9dced 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scbytes.ts @@ -1,8 +1,7 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import {base58Encode, WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export function bytesCompare(lhs: u8[], rhs: u8[]): i32 { const size = (lhs.length < rhs.length) ? lhs.length : rhs.length; @@ -16,11 +15,11 @@ export function bytesCompare(lhs: u8[], rhs: u8[]): i32 { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function bytesDecode(dec: WasmDecoder): u8[] { +export function bytesDecode(dec: wasmtypes.WasmDecoder): u8[] { return dec.bytes(); } -export function bytesEncode(enc: WasmEncoder, value: u8[]): void { +export function bytesEncode(enc: wasmtypes.WasmEncoder, value: u8[]): void { enc.bytes(value); } @@ -33,15 +32,15 @@ export function bytesToBytes(buf: u8[]): u8[] { } export function bytesToString(value: u8[]): string { - return base58Encode(value); + return wasmtypes.base58Encode(value); } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableBytes { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts index 82bdd2de70..ddae982fd6 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scchainid.ts @@ -2,24 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {base58Encode, WasmDecoder, WasmEncoder, zeroes} from "./codec"; -import {Proxy} from "./proxy"; -import {addressFromBytes, ScAddress, ScAddressAlias} from "./scaddress"; -import {bytesCompare} from "./scbytes"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export const ScChainIDLength = 33; export class ScChainID { - id: u8[] = zeroes(ScChainIDLength); + id: u8[] = wasmtypes.zeroes(ScChainIDLength); - public address(): ScAddress { - return addressFromBytes(this.id); + public address(): wasmtypes.ScAddress { + return wasmtypes.addressFromBytes(this.id); } public equals(other: ScChainID): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -35,24 +32,24 @@ export class ScChainID { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function chainIDDecode(dec: WasmDecoder): ScChainID { +export function chainIDDecode(dec: wasmtypes.WasmDecoder): ScChainID { return chainIDFromBytesUnchecked(dec.fixedBytes(ScChainIDLength)); } -export function chainIDEncode(enc: WasmEncoder, value: ScChainID): void { +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] = ScAddressAlias; + chainID.id[0] = wasmtypes.ScAddressAlias; return chainID; } if (buf.length != ScChainIDLength) { panic("invalid ChainID length"); } - if (buf[0] != ScAddressAlias) { + if (buf[0] != wasmtypes.ScAddressAlias) { panic("invalid ChainID: not an alias address"); } return chainIDFromBytesUnchecked(buf); @@ -64,7 +61,7 @@ export function chainIDToBytes(value: ScChainID): u8[] { export function chainIDToString(value: ScChainID): string { // TODO standardize human readable string - return base58Encode(value.id); + return wasmtypes.base58Encode(value.id); } function chainIDFromBytesUnchecked(buf: u8[]): ScChainID { @@ -76,9 +73,9 @@ function chainIDFromBytesUnchecked(buf: u8[]): ScChainID { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableChainID { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts index 5cff8f301f..c95852517c 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/sccolor.ts @@ -2,23 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {base58Encode, WasmDecoder, WasmEncoder, zeroes} from "./codec"; -import {Proxy} from "./proxy"; -import {bytesCompare} from "./scbytes"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export const ScColorLength = 32; export class ScColor { - id: u8[] = zeroes(ScColorLength); + id: u8[] = wasmtypes.zeroes(ScColorLength); constructor(fill: u8) { this.id.fill(fill); } public equals(other: ScColor): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -39,11 +37,11 @@ export const MINT: ScColor = new ScColor(0xff); // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function colorDecode(dec: WasmDecoder): ScColor { +export function colorDecode(dec: wasmtypes.WasmDecoder): ScColor { return colorFromBytesUnchecked(dec.fixedBytes(ScColorLength)); } -export function colorEncode(enc: WasmEncoder, value: ScColor): void { +export function colorEncode(enc: wasmtypes.WasmEncoder, value: ScColor): void { enc.fixedBytes(value.toBytes(), ScColorLength); } @@ -63,7 +61,7 @@ export function colorToBytes(value: ScColor): u8[] { export function colorToString(value: ScColor): string { // TODO standardize human readable string - return base58Encode(value.id); + return wasmtypes.base58Encode(value.id); } function colorFromBytesUnchecked(buf: u8[]): ScColor { @@ -75,9 +73,9 @@ function colorFromBytesUnchecked(buf: u8[]): ScColor { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableColor { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts index baebece7f0..dbf8826ded 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schash.ts @@ -2,19 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {base58Encode, WasmDecoder, WasmEncoder, zeroes} from "./codec"; -import {Proxy} from "./proxy"; -import {bytesCompare} from "./scbytes"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export const ScHashLength = 32; export class ScHash { - id: u8[] = zeroes(ScHashLength); + id: u8[] = wasmtypes.zeroes(ScHashLength); public equals(other: ScHash): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -30,11 +28,11 @@ export class ScHash { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function hashDecode(dec: WasmDecoder): ScHash { +export function hashDecode(dec: wasmtypes.WasmDecoder): ScHash { return hashFromBytesUnchecked(dec.fixedBytes(ScHashLength)); } -export function hashEncode(enc: WasmEncoder, value: ScHash): void { +export function hashEncode(enc: wasmtypes.WasmEncoder, value: ScHash): void { enc.fixedBytes(value.toBytes(), ScHashLength); } @@ -54,7 +52,7 @@ export function hashToBytes(value: ScHash): u8[] { export function hashToString(value: ScHash): string { // TODO standardize human readable string - return base58Encode(value.id); + return wasmtypes.base58Encode(value.id); } function hashFromBytesUnchecked(buf: u8[]): ScHash { @@ -66,9 +64,9 @@ function hashFromBytesUnchecked(buf: u8[]): ScHash { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableHash { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts index 9871a949f0..f3aa8c4b3c 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/schname.ts @@ -2,10 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; -import {bytesCompare} from "./scbytes"; -import {uint32FromBytes, uint32ToBytes} from "./scuint32"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ @@ -15,11 +12,11 @@ export class ScHname { id: u8[]; constructor(id: u32) { - this.id = uint32ToBytes(id); + this.id = wasmtypes.uint32ToBytes(id); } public equals(other: ScHname): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -35,11 +32,11 @@ export class ScHname { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function hnameDecode(dec: WasmDecoder): ScHname { +export function hnameDecode(dec: wasmtypes.WasmDecoder): ScHname { return hnameFromBytesUnchecked(dec.fixedBytes(ScHnameLength)); } -export function hnameEncode(enc: WasmEncoder, value: ScHname): void { +export function hnameEncode(enc: wasmtypes.WasmEncoder, value: ScHname): void { enc.fixedBytes(value.toBytes(), ScHnameLength); } @@ -58,7 +55,7 @@ export function hnameToBytes(value: ScHname): u8[] { } export function hnameToString(value: ScHname): string { - const res = uint32FromBytes(value.id).toString(16); + const res = wasmtypes.uint32FromBytes(value.id).toString(16); return "0000000".slice(0, 8 - res.length) + res; } @@ -71,9 +68,9 @@ function hnameFromBytesUnchecked(buf: u8[]): ScHname { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableHname { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts index 3cd6044c2a..d7ed73ba9b 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint16.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScInt16Length = 2; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function int16Decode(dec: WasmDecoder): i16 { +export function int16Decode(dec: wasmtypes.WasmDecoder): i16 { return dec.vliDecode(16) as i16; } -export function int16Encode(enc: WasmEncoder, value: i16): void { +export function int16Encode(enc: wasmtypes.WasmEncoder, value: i16): void { enc.vliEncode(value as i64); } @@ -42,9 +41,9 @@ export function int16ToString(value: i16): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableInt16 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts index b4b68c466a..3dd567c865 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint32.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScInt32Length = 4; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function int32Decode(dec: WasmDecoder): i32 { +export function int32Decode(dec: wasmtypes.WasmDecoder): i32 { return dec.vliDecode(32) as i32; } -export function int32Encode(enc: WasmEncoder, value: i32): void { +export function int32Encode(enc: wasmtypes.WasmEncoder, value: i32): void { enc.vliEncode(value as i64); } @@ -46,9 +45,9 @@ export function int32ToString(value: i32): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableInt32 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts index 2d042af751..9b5ffa70e5 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint64.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScInt64Length = 8; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function int64Decode(dec: WasmDecoder): i64 { +export function int64Decode(dec: wasmtypes.WasmDecoder): i64 { return dec.vliDecode(64); } -export function int64Encode(enc: WasmEncoder, value: i64): void { +export function int64Encode(enc: wasmtypes.WasmEncoder, value: i64): void { enc.vliEncode(value); } @@ -54,9 +53,9 @@ export function int64ToString(value: i64): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableInt64 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts index 46702803fe..07705b1bab 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scint8.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScInt8Length = 1; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function int8Decode(dec: WasmDecoder): i8 { +export function int8Decode(dec: wasmtypes.WasmDecoder): i8 { return dec.byte() as i8; } -export function int8Encode(enc: WasmEncoder, value: i8): void { +export function int8Encode(enc: wasmtypes.WasmEncoder, value: i8): void { enc.byte(value as u8); } @@ -38,9 +37,9 @@ export function int8ToString(value: i8): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableInt8 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts index d8cb3e21e5..6f7f726b96 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/screquestid.ts @@ -2,20 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {base58Encode, WasmDecoder, WasmEncoder, zeroes} from "./codec"; -import {Proxy} from "./proxy"; -import {bytesCompare} from "./scbytes"; -import {ScHashLength} from "./schash"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export const ScRequestIDLength = 34; export class ScRequestID { - id: u8[] = zeroes(ScRequestIDLength); + id: u8[] = wasmtypes.zeroes(ScRequestIDLength); public equals(other: ScRequestID): bool { - return bytesCompare(this.id, other.id) == 0; + return wasmtypes.bytesCompare(this.id, other.id) == 0; } // convert to byte array representation @@ -31,11 +28,11 @@ export class ScRequestID { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function requestIDDecode(dec: WasmDecoder): ScRequestID { +export function requestIDDecode(dec: wasmtypes.WasmDecoder): ScRequestID { return requestIDFromBytesUnchecked(dec.fixedBytes(ScRequestIDLength)); } -export function requestIDEncode(enc: WasmEncoder, value: ScRequestID): void { +export function requestIDEncode(enc: wasmtypes.WasmEncoder, value: ScRequestID): void { enc.fixedBytes(value.toBytes(), ScRequestIDLength); } @@ -59,7 +56,7 @@ export function requestIDToBytes(value: ScRequestID): u8[] { export function requestIDToString(value: ScRequestID): string { // TODO standardize human readable string - return base58Encode(value.id); + return wasmtypes.base58Encode(value.id); } function requestIDFromBytesUnchecked(buf: u8[]): ScRequestID { @@ -71,9 +68,9 @@ function requestIDFromBytesUnchecked(buf: u8[]): ScRequestID { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableRequestID { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts index f46e2eb8c7..9d95bc7d87 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scstring.ts @@ -1,16 +1,15 @@ // Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function stringDecode(dec: WasmDecoder): string { +export function stringDecode(dec: wasmtypes.WasmDecoder): string { return stringFromBytes(dec.bytes()); } -export function stringEncode(enc: WasmEncoder, value: string): void { +export function stringEncode(enc: wasmtypes.WasmEncoder, value: string): void { enc.bytes(stringToBytes(value)); } @@ -35,9 +34,9 @@ export function stringToString(value: string): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableString { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts index 79ea80bcd7..737ab37a1a 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint16.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScUint16Length = 2; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function uint16Decode(dec: WasmDecoder): u16 { +export function uint16Decode(dec: wasmtypes.WasmDecoder): u16 { return dec.vluDecode(16) as u16; } -export function uint16Encode(enc: WasmEncoder, value: u16): void { +export function uint16Encode(enc: wasmtypes.WasmEncoder, value: u16): void { enc.vluEncode(value as u64); } @@ -42,9 +41,9 @@ export function uint16ToString(value: u16): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableUint16 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts index da0997d638..c2210014b3 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint32.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScUint32Length = 4; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function uint32Decode(dec: WasmDecoder): u32 { +export function uint32Decode(dec: wasmtypes.WasmDecoder): u32 { return dec.vluDecode(32) as u32; } -export function uint32Encode(enc: WasmEncoder, value: u32): void { +export function uint32Encode(enc: wasmtypes.WasmEncoder, value: u32): void { enc.vluEncode(value as u64); } @@ -46,9 +45,9 @@ export function uint32ToString(value: u32): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableUint32 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts index 95e0e6a483..c1483b857b 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint64.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScUint64Length = 8; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function uint64Decode(dec: WasmDecoder): u64 { +export function uint64Decode(dec: wasmtypes.WasmDecoder): u64 { return dec.vluDecode(64); } -export function uint64Encode(enc: WasmEncoder, value: u64): void { +export function uint64Encode(enc: wasmtypes.WasmEncoder, value: u64): void { enc.vluEncode(value); } @@ -54,9 +53,9 @@ export function uint64ToString(value: u64): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableUint64 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts index 96ec663e77..5384360601 100644 --- a/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts +++ b/packages/wasmvm/wasmlib/ts/wasmlib/wasmtypes/scuint8.ts @@ -2,18 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import {panic} from "../sandbox"; -import {WasmDecoder, WasmEncoder} from "./codec"; -import {Proxy} from "./proxy"; +import * as wasmtypes from "./index"; export const ScUint8Length = 1; // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ -export function uint8Decode(dec: WasmDecoder): u8 { +export function uint8Decode(dec: wasmtypes.WasmDecoder): u8 { return dec.byte(); } -export function uint8Encode(enc: WasmEncoder, value: u8): void { +export function uint8Encode(enc: wasmtypes.WasmEncoder, value: u8): void { enc.byte(value); } @@ -38,9 +37,9 @@ export function uint8ToString(value: u8): string { // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ export class ScImmutableUint8 { - proxy: Proxy; + proxy: wasmtypes.Proxy; - constructor(proxy: Proxy) { + constructor(proxy: wasmtypes.Proxy) { this.proxy = proxy; } diff --git a/packages/wasmvm/wasmsolo/soloagent.go b/packages/wasmvm/wasmsolo/soloagent.go index df12484cc4..f8e1731801 100644 --- a/packages/wasmvm/wasmsolo/soloagent.go +++ b/packages/wasmvm/wasmsolo/soloagent.go @@ -5,7 +5,7 @@ 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" @@ -15,7 +15,7 @@ import ( type SoloAgent struct { Env *solo.Solo - Pair *ed25519.KeyPair + Pair *cryptolib.KeyPair address ledgerstate.Address hname iscp.Hname } diff --git a/packages/wasmvm/wasmsolo/solocontext.go b/packages/wasmvm/wasmsolo/solocontext.go index abbfe1466f..8dd84dfd4e 100644 --- a/packages/wasmvm/wasmsolo/solocontext.go +++ b/packages/wasmvm/wasmsolo/solocontext.go @@ -10,7 +10,7 @@ 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" @@ -30,32 +30,55 @@ const ( // TODO set back to false ) 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 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 *wasmhost.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. @@ -97,11 +130,11 @@ func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, 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,16 +143,16 @@ func NewSoloContextForChain(t *testing.T, chain *solo.Chain, creator *SoloAgent, if len(init) != 0 { params = init[0].Params() } - if *GoDebug { + 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 wasmhost.GoWasmVM = nil } @@ -144,7 +177,7 @@ func NewSoloContextForNative(t *testing.T, chain *solo.Chain, creator *SoloAgent 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") } @@ -181,7 +214,7 @@ func StartChain(t *testing.T, chainName string, env ...*solo.Solo) *solo.Chain { soloEnv = env[0] } if soloEnv == nil { - soloEnv = solo.New(t, SoloDebug, SoloStackTracing) + soloEnv = solo.New(t, SoloDebug, SoloStackTracing, SoloSeed) } return soloEnv.NewChain(nil, chainName) } @@ -254,6 +287,26 @@ 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 } @@ -332,60 +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 - } else { - rsFile := wasmFile - exists, _ = util.ExistsFilePath(rsFile) - wasmFile = rsFile - } - - // try Go Wasm file? - if !exists || *GoWasm { - goFile := "../go/pkg/" + ctx.scName + "_go.wasm" - exists, _ = util.ExistsFilePath(goFile) - if exists { - wasmFile = goFile - } else { - goFile = 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 - } else { - tsFile = 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 index 157eadd96d..8df4fc03c5 100644 --- a/packages/wasmvm/wasmsolo/solosandbox.go +++ b/packages/wasmvm/wasmsolo/solosandbox.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package wasmsolo import ( @@ -166,31 +169,32 @@ func (s *SoloSandbox) fnBlockContext(args []byte) []byte { } func (s *SoloSandbox) fnCall(args []byte) []byte { + ctx := s.ctx req := wasmrequests.NewCallRequestFromBytes(args) contract := s.cvt.IscpHname(req.Contract) - if contract != iscp.Hn(s.ctx.scName) { - s.Panicf("unknown contract: %s vs. %s", contract.String(), s.ctx.scName) + if contract != iscp.Hn(ctx.scName) { + s.Panicf("unknown contract: %s vs. %s", contract.String(), ctx.scName) } function := s.cvt.IscpHname(req.Function) - funcName := s.ctx.wc.FunctionFromCode(uint32(function)) + funcName := ctx.wc.FunctionFromCode(uint32(function)) if funcName == "" { s.Panicf("unknown function: %s", function.String()) } - s.Tracef("CALL c'%s' f'%s'", s.ctx.scName, funcName) + 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(s.ctx.scName, funcName, params, transfer) + return s.postSync(ctx.scName, funcName, params, transfer) } - _ = wasmhost.Connect(s.ctx.wasmHostOld) - res, err := s.ctx.Chain.CallView(s.ctx.scName, funcName, params) - _ = wasmhost.Connect(s.ctx.wc) - s.ctx.Err = err - if err != nil { + _ = 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() @@ -266,13 +270,13 @@ func (s *SoloSandbox) fnPost(args []byte) []byte { if funcName == "" { s.Panicf("unknown function: %s", function.String()) } - s.Tracef("POST c'%s' f'%s'", s.ctx.scName, funcName) + 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 { - s.Panicf("transfer is required for post") + transfer.Add(colored.Color{}, 1) } if req.Delay != 0 { s.Panicf("cannot delay solo post") @@ -292,7 +296,7 @@ func (s *SoloSandbox) fnResults(args []byte) []byte { panic("implement me") } -// transfer tokens to address +// transfer tokens to L1 address func (s *SoloSandbox) fnSend(args []byte) []byte { panic("implement me") } diff --git a/tools/cluster/tests/wasm/inccounter_bg.wasm b/tools/cluster/tests/wasm/inccounter_bg.wasm index 74acb7588e..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/schema/generator/clientbase.go b/tools/schema/generator/clientbase.go index 8a67aa3b8b..b71826abcd 100644 --- a/tools/schema/generator/clientbase.go +++ b/tools/schema/generator/clientbase.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package generator import ( diff --git a/tools/schema/generator/emitter.go b/tools/schema/generator/emitter.go index 47f3e4c0cd..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 ( diff --git a/tools/schema/generator/goclienttemplates/alltemplates.go b/tools/schema/generator/goclienttemplates/alltemplates.go index 3bef0ca64d..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" diff --git a/tools/schema/generator/goclienttemplates/events.go b/tools/schema/generator/goclienttemplates/events.go index efc5279c42..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{ diff --git a/tools/schema/generator/goclienttemplates/service.go b/tools/schema/generator/goclienttemplates/service.go index d75e3cb63d..a889c4f591 100644 --- a/tools/schema/generator/goclienttemplates/service.go +++ b/tools/schema/generator/goclienttemplates/service.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package goclienttemplates var serviceGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/alltemplates.go b/tools/schema/generator/gotemplates/alltemplates.go index 1f99d81295..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" diff --git a/tools/schema/generator/gotemplates/consts.go b/tools/schema/generator/gotemplates/consts.go index 8a092299bd..86ebbfbbcd 100644 --- a/tools/schema/generator/gotemplates/consts.go +++ b/tools/schema/generator/gotemplates/consts.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var constsGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/contract.go b/tools/schema/generator/gotemplates/contract.go index 002b778492..c67816e571 100644 --- a/tools/schema/generator/gotemplates/contract.go +++ b/tools/schema/generator/gotemplates/contract.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var contractGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/events.go b/tools/schema/generator/gotemplates/events.go index 0483037315..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{ 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/lib.go b/tools/schema/generator/gotemplates/lib.go index 94b568b094..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{ diff --git a/tools/schema/generator/gotemplates/main.go b/tools/schema/generator/gotemplates/main.go index 93a36297b3..1f3ad54efa 100644 --- a/tools/schema/generator/gotemplates/main.go +++ b/tools/schema/generator/gotemplates/main.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var mainGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/params.go b/tools/schema/generator/gotemplates/params.go index f23157565f..aa5d1159dd 100644 --- a/tools/schema/generator/gotemplates/params.go +++ b/tools/schema/generator/gotemplates/params.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var paramsGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/proxy.go b/tools/schema/generator/gotemplates/proxy.go index 574af27e25..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{ diff --git a/tools/schema/generator/gotemplates/results.go b/tools/schema/generator/gotemplates/results.go index 345b454bf9..0a2d77d8f3 100644 --- a/tools/schema/generator/gotemplates/results.go +++ b/tools/schema/generator/gotemplates/results.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var resultsGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/state.go b/tools/schema/generator/gotemplates/state.go index faca5700d0..d5891c169e 100644 --- a/tools/schema/generator/gotemplates/state.go +++ b/tools/schema/generator/gotemplates/state.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var stateGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/structs.go b/tools/schema/generator/gotemplates/structs.go index cda808607b..dd459384a5 100644 --- a/tools/schema/generator/gotemplates/structs.go +++ b/tools/schema/generator/gotemplates/structs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var structsGo = map[string]string{ diff --git a/tools/schema/generator/gotemplates/typedefs.go b/tools/schema/generator/gotemplates/typedefs.go index 59a3a57c7a..77c3b1aca7 100644 --- a/tools/schema/generator/gotemplates/typedefs.go +++ b/tools/schema/generator/gotemplates/typedefs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package gotemplates var typedefsGo = map[string]string{ diff --git a/tools/schema/generator/rstemplates/alltemplates.go b/tools/schema/generator/rstemplates/alltemplates.go index 3e69725083..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" 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 bdf4a2b1c4..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{ diff --git a/tools/schema/generator/rstemplates/contract.go b/tools/schema/generator/rstemplates/contract.go index e94f3fcd28..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{ diff --git a/tools/schema/generator/rstemplates/events.go b/tools/schema/generator/rstemplates/events.go index b6251872a7..3db4cac20d 100644 --- a/tools/schema/generator/rstemplates/events.go +++ b/tools/schema/generator/rstemplates/events.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package rstemplates var eventsRs = map[string]string{ diff --git a/tools/schema/generator/rstemplates/funcs.go b/tools/schema/generator/rstemplates/funcs.go index 244e345954..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{ diff --git a/tools/schema/generator/rstemplates/lib.go b/tools/schema/generator/rstemplates/lib.go index de774ac70d..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{ diff --git a/tools/schema/generator/rstemplates/mod.go b/tools/schema/generator/rstemplates/mod.go index 37dace60da..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{ diff --git a/tools/schema/generator/rstemplates/params.go b/tools/schema/generator/rstemplates/params.go index 6da140a2d6..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{ diff --git a/tools/schema/generator/rstemplates/proxy.go b/tools/schema/generator/rstemplates/proxy.go index 9e7baa698d..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{ diff --git a/tools/schema/generator/rstemplates/results.go b/tools/schema/generator/rstemplates/results.go index 2fcdc2951f..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{ diff --git a/tools/schema/generator/rstemplates/state.go b/tools/schema/generator/rstemplates/state.go index b6c83263fe..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{ diff --git a/tools/schema/generator/rstemplates/structs.go b/tools/schema/generator/rstemplates/structs.go index 43128acb5b..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{ diff --git a/tools/schema/generator/rstemplates/typedefs.go b/tools/schema/generator/rstemplates/typedefs.go index a9436db0c1..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{ diff --git a/tools/schema/generator/templates.go b/tools/schema/generator/templates.go index 99e01d0a7f..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" diff --git a/tools/schema/generator/tsclienttemplates/alltemplates.go b/tools/schema/generator/tsclienttemplates/alltemplates.go index 09daa056cf..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" diff --git a/tools/schema/generator/tsclienttemplates/events.go b/tools/schema/generator/tsclienttemplates/events.go index bd0b5b5712..71ed357a8f 100644 --- a/tools/schema/generator/tsclienttemplates/events.go +++ b/tools/schema/generator/tsclienttemplates/events.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var eventsTs = map[string]string{ diff --git a/tools/schema/generator/tsclienttemplates/index.go b/tools/schema/generator/tsclienttemplates/index.go index b3ee09d122..247d99bd9c 100644 --- a/tools/schema/generator/tsclienttemplates/index.go +++ b/tools/schema/generator/tsclienttemplates/index.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var indexTs = map[string]string{ diff --git a/tools/schema/generator/tsclienttemplates/service.go b/tools/schema/generator/tsclienttemplates/service.go index 842cae48b9..88163a688f 100644 --- a/tools/schema/generator/tsclienttemplates/service.go +++ b/tools/schema/generator/tsclienttemplates/service.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tsclienttemplates var serviceTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/alltemplates.go b/tools/schema/generator/tstemplates/alltemplates.go index ef8a9304d3..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" diff --git a/tools/schema/generator/tstemplates/consts.go b/tools/schema/generator/tstemplates/consts.go index 7b9e45e808..b878857f00 100644 --- a/tools/schema/generator/tstemplates/consts.go +++ b/tools/schema/generator/tstemplates/consts.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var constsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/contract.go b/tools/schema/generator/tstemplates/contract.go index f44bc9645b..2488b77b9a 100644 --- a/tools/schema/generator/tstemplates/contract.go +++ b/tools/schema/generator/tstemplates/contract.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var contractTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/events.go b/tools/schema/generator/tstemplates/events.go index 7d9495dc17..afeea9ea59 100644 --- a/tools/schema/generator/tstemplates/events.go +++ b/tools/schema/generator/tstemplates/events.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var eventsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/funcs.go b/tools/schema/generator/tstemplates/funcs.go index d9e8b45fdd..3a9008e1a3 100644 --- a/tools/schema/generator/tstemplates/funcs.go +++ b/tools/schema/generator/tstemplates/funcs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var funcsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/index.go b/tools/schema/generator/tstemplates/index.go index 0b29c496c2..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{ diff --git a/tools/schema/generator/tstemplates/lib.go b/tools/schema/generator/tstemplates/lib.go index bb91892f5f..6ef7f0384c 100644 --- a/tools/schema/generator/tstemplates/lib.go +++ b/tools/schema/generator/tstemplates/lib.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var libTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/params.go b/tools/schema/generator/tstemplates/params.go index b82de4d04f..8cb4ecf985 100644 --- a/tools/schema/generator/tstemplates/params.go +++ b/tools/schema/generator/tstemplates/params.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var paramsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/proxy.go b/tools/schema/generator/tstemplates/proxy.go index d59535d3c4..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{ diff --git a/tools/schema/generator/tstemplates/results.go b/tools/schema/generator/tstemplates/results.go index c517a24222..69aa442ed4 100644 --- a/tools/schema/generator/tstemplates/results.go +++ b/tools/schema/generator/tstemplates/results.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var resultsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/state.go b/tools/schema/generator/tstemplates/state.go index ba9b0db074..d375182afb 100644 --- a/tools/schema/generator/tstemplates/state.go +++ b/tools/schema/generator/tstemplates/state.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var stateTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/structs.go b/tools/schema/generator/tstemplates/structs.go index 4235eaab1c..a79f5ae0f4 100644 --- a/tools/schema/generator/tstemplates/structs.go +++ b/tools/schema/generator/tstemplates/structs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var structsTs = map[string]string{ diff --git a/tools/schema/generator/tstemplates/typedefs.go b/tools/schema/generator/tstemplates/typedefs.go index f683e58edf..1adcd2e45a 100644 --- a/tools/schema/generator/tstemplates/typedefs.go +++ b/tools/schema/generator/tstemplates/typedefs.go @@ -1,3 +1,6 @@ +// Copyright 2020 IOTA Stiftung +// SPDX-License-Identifier: Apache-2.0 + package tstemplates var typedefsTs = map[string]string{ diff --git a/tools/schema/generator/utils.go b/tools/schema/generator/utils.go index 90b548d326..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 (