github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/smartcontract/doc_test.go (about)

     1  package smartcontract_test
     2  
     3  import (
     4  	"context"
     5  	"encoding/hex"
     6  
     7  	"github.com/nspcc-dev/neo-go/pkg/rpcclient"
     8  	"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
     9  	"github.com/nspcc-dev/neo-go/pkg/rpcclient/gas"
    10  	"github.com/nspcc-dev/neo-go/pkg/rpcclient/neo"
    11  	"github.com/nspcc-dev/neo-go/pkg/smartcontract"
    12  	"github.com/nspcc-dev/neo-go/pkg/util"
    13  	"github.com/nspcc-dev/neo-go/pkg/wallet"
    14  )
    15  
    16  func ExampleBuilder() {
    17  	// No error checking done at all, intentionally.
    18  	w, _ := wallet.NewWalletFromFile("somewhere")
    19  	defer w.Close()
    20  
    21  	c, _ := rpcclient.New(context.Background(), "url", rpcclient.Options{})
    22  
    23  	// Assuming there is one Account inside.
    24  	a, _ := actor.NewSimple(c, w.Accounts[0])
    25  
    26  	pKey, _ := hex.DecodeString("03d9e8b16bd9b22d3345d6d4cde31be1c3e1d161532e3d0ccecb95ece2eb58336e") // Public key.
    27  
    28  	b := smartcontract.NewBuilder()
    29  	// Transfer + vote in a single script with each action leaving return value on the stack.
    30  	b.InvokeMethod(neo.Hash, "transfer", a.Sender(), util.Uint160{0xff}, 1, nil)
    31  	b.InvokeMethod(neo.Hash, "vote", pKey)
    32  	script, _ := b.Script()
    33  
    34  	// Actor has an Invoker inside, so we can perform test invocation using the script.
    35  	res, _ := a.Run(script)
    36  	if res.State != "HALT" || len(res.Stack) != 2 {
    37  		panic("failed") // The script failed completely or didn't return proper number of return values.
    38  	}
    39  
    40  	transferResult, _ := res.Stack[0].TryBool()
    41  	voteResult, _ := res.Stack[1].TryBool()
    42  
    43  	if !transferResult {
    44  		panic("transfer failed")
    45  	}
    46  	if !voteResult {
    47  		panic("vote failed")
    48  	}
    49  
    50  	b.Reset() // Copy the old script above if you need it!
    51  
    52  	// Multiple transfers of different tokens in a single script. If any of
    53  	// them fails whole script fails.
    54  	b.InvokeWithAssert(neo.Hash, "transfer", a.Sender(), util.Uint160{0x70}, 1, nil)
    55  	b.InvokeWithAssert(gas.Hash, "transfer", a.Sender(), util.Uint160{0x71}, 100000, []byte("data"))
    56  	b.InvokeWithAssert(neo.Hash, "transfer", a.Sender(), util.Uint160{0x72}, 1, nil)
    57  	script, _ = b.Script()
    58  
    59  	// Now send a transaction with this script via an RPC node.
    60  	txid, vub, _ := a.SendRun(script)
    61  	_ = txid
    62  	_ = vub
    63  }