From 756b06ff413c4e750b41f02fde637332432b6412 Mon Sep 17 00:00:00 2001 From: Stan Nazarenko Date: Tue, 12 Apr 2022 00:16:22 +0100 Subject: [PATCH] Add CI configuration (#4) ... and fix linter errors. --- .github/workflows/ci.yml | 91 +++++++++++++++++++++++++++ .gitignore | 2 +- .golangci.yml | 64 +++++++++++++++++++ README.md | 8 ++- lib/go/iinft/client.go | 2 +- lib/go/iinft/evergreen/cadence.go | 6 +- lib/go/iinft/go.mod | 1 - lib/go/iinft/gwtf/account.go | 1 - lib/go/iinft/gwtf/account_test.go | 1 - lib/go/iinft/gwtf/asserts.go | 25 ++++---- lib/go/iinft/gwtf/cadence.go | 4 +- lib/go/iinft/gwtf/cadence_test.go | 19 +++--- lib/go/iinft/gwtf/event.go | 55 ++++++++-------- lib/go/iinft/gwtf/event_test.go | 1 - lib/go/iinft/gwtf/script.go | 74 +++++++++++----------- lib/go/iinft/gwtf/script_test.go | 3 +- lib/go/iinft/gwtf/setup.go | 21 +++---- lib/go/iinft/gwtf/templates.go | 46 +++++++------- lib/go/iinft/gwtf/transaction.go | 18 +++--- lib/go/iinft/logger.go | 10 +-- lib/go/iinft/scripts/engine.go | 5 +- lib/go/iinft/scripts/helpers.go | 1 - lib/go/iinft/scripts/testing.go | 14 ++++- lib/go/iinft/test/digitalart_test.go | 68 +++++++++++--------- lib/go/iinft/test/fusd_test.go | 4 +- lib/go/iinft/test/marketplace_test.go | 12 ++-- lib/go/iinft/types.go | 5 +- 27 files changed, 364 insertions(+), 197 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .golangci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d2acc55 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,91 @@ +name: ci +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + lint: + runs-on: ubuntu-latest + defaults: + run: + working-directory: lib/go/iinft + steps: + - uses: actions/setup-go@v3 + with: + go-version: '1.16.*' + + - name: Checkout code + uses: actions/checkout@v2 + + - id: go-cache-paths + run: | + echo "::set-output name=go-build::$(go env GOCACHE)" + echo "::set-output name=go-mod::$(go env GOMODCACHE)" + + - name: Go Build Cache + uses: actions/cache@v3 + with: + path: ${{ steps.go-cache-paths.outputs.go-build }} + key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }} + + - name: Go Mod Cache + uses: actions/cache@v3 + with: + path: ${{ steps.go-cache-paths.outputs.go-mod }} + key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }} + + - name: golangci-lint + uses: golangci/golangci-lint-action@v3.1.0 + with: + args: "--out-${NO_FUTURE}format colored-line-number --timeout 5m" + working-directory: lib/go/iinft + skip-pkg-cache: true + skip-build-cache: true + + tidy: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - uses: actions/setup-go@v3 + with: + go-version: '1.16.*' + - uses: actions/cache@v3 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - uses: zencargo/github-action-go-mod-tidy@v1 + with: + path: lib/go/iinft + go-version: 1.16 + + test: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: '1.16.*' + - name: Set up Cache + uses: actions/cache@v3 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: Test + run: make test + + diff --git a/.gitignore b/.gitignore index 4cef54f..aa8c989 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,4 @@ _references lib/go/iinft/bin # Flow emulator -flowdb \ No newline at end of file +flowdb diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..3d26ea4 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,64 @@ +linters-settings: + errcheck: + check-type-assertions: true + goconst: + min-len: 2 + min-occurrences: 3 + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + govet: + check-shadowing: true + nolintlint: + require-explanation: true + require-specific: true + funlen: + lines: 100 + statements: 40 + +linters: + disable-all: true + enable: + - asciicheck + - bodyclose + - contextcheck + - depguard + - dogsled +# - dupl + - errcheck + - errorlint + - exportloopref + - exhaustive + - goconst +# - gocritic + - gofmt + - goimports +# - gomnd + - gocyclo + - gosec + - gosimple + - govet + - importas + - ineffassign + - misspell + - nolintlint + - nakedret + - prealloc + - predeclared + - revive + - staticcheck + - stylecheck + - thelper + - typecheck + - unconvert + - unparam + - unused + - wastedassign + +run: + issues-exit-code: 1 + diff --git a/README.md b/README.md index ced0671..8c97247 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,6 @@ -# sequel-flow-contracts -Flow smart contracts for Sequel +[![ci](https://github.com/piprate/sequel-flow-contracts/actions/workflows/ci.yml/badge.svg)](https://github.com/piprate/sequel-flow-contracts/actions/workflows/ci.yml) + +# Flow contracts for Sequel + +* Flow contracts for Sequel +* Supporting Go framework diff --git a/lib/go/iinft/client.go b/lib/go/iinft/client.go index cd29325..275317b 100644 --- a/lib/go/iinft/client.go +++ b/lib/go/iinft/client.go @@ -34,7 +34,7 @@ func (f *fileLoader) WriteFile(filename string, data []byte, perm os.FileMode) e } // NewGoWithTheFlowFS creates a new local go with the flow client -func NewGoWithTheFlowFS(flowBasePath string, network string, inMemory, enableTxFees bool) (*gwtf.GoWithTheFlow, error) { +func NewGoWithTheFlowFS(flowBasePath, network string, inMemory, enableTxFees bool) (*gwtf.GoWithTheFlow, error) { return NewGoWithTheFlowError(&fileLoader{ baseDir: flowBasePath, fsLoader: &afero.Afero{Fs: afero.NewOsFs()}, diff --git a/lib/go/iinft/evergreen/cadence.go b/lib/go/iinft/evergreen/cadence.go index 6340250..08c9c34 100644 --- a/lib/go/iinft/evergreen/cadence.go +++ b/lib/go/iinft/evergreen/cadence.go @@ -66,14 +66,16 @@ func ProfileFromCadence(val cadence.Value) (*Profile, error) { Roles: []*Role{}, } - rolesArray := valStruct.Fields[1].(cadence.Array) + rolesArray, ok := valStruct.Fields[1].(cadence.Array) + if !ok { + return nil, errors.New("bad Evergreen Profile value") + } for _, roleVal := range rolesArray.Values { role, err := RoleFromCadence(roleVal) if err != nil { return nil, err } res.Roles = append(res.Roles, role) - } return &res, nil diff --git a/lib/go/iinft/go.mod b/lib/go/iinft/go.mod index 4aae532..a402d7a 100644 --- a/lib/go/iinft/go.mod +++ b/lib/go/iinft/go.mod @@ -4,7 +4,6 @@ go 1.16 require ( github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de - github.com/kevinburke/go-bindata v3.22.0+incompatible github.com/onflow/cadence v0.23.2 github.com/onflow/flow-cli v0.33.0 github.com/onflow/flow-emulator v0.31.0 diff --git a/lib/go/iinft/gwtf/account.go b/lib/go/iinft/gwtf/account.go index 30f0275..ba51aa5 100644 --- a/lib/go/iinft/gwtf/account.go +++ b/lib/go/iinft/gwtf/account.go @@ -15,7 +15,6 @@ func (f *GoWithTheFlow) CreateAccounts(saAccountName string) *GoWithTheFlow { } return gwtf - } // CreateAccountsE ensures that all accounts present in the deployment block for the given network is present diff --git a/lib/go/iinft/gwtf/account_test.go b/lib/go/iinft/gwtf/account_test.go index d323e06..3472b4c 100644 --- a/lib/go/iinft/gwtf/account_test.go +++ b/lib/go/iinft/gwtf/account_test.go @@ -28,5 +28,4 @@ func TestErrorsInAccountCreation(t *testing.T) { assert.Error(t, err) assert.Contains(t, err.Error(), "could not find account with address 179b6b1cb6755e3") }) - } diff --git a/lib/go/iinft/gwtf/asserts.go b/lib/go/iinft/gwtf/asserts.go index 5c4876e..201bd02 100644 --- a/lib/go/iinft/gwtf/asserts.go +++ b/lib/go/iinft/gwtf/asserts.go @@ -18,10 +18,10 @@ func (tb FlowTransactionBuilder) Test(t *testing.T) TransactionResult { locale, _ := time.LoadLocation("UTC") time.Local = locale events, err := tb.RunE() - var formattedEvents []*FormatedEvent - for _, event := range events { + formattedEvents := make([]*FormatedEvent, len(events)) + for i, event := range events { ev := ParseEvent(event, uint64(0), time.Unix(0, 0), []string{}) - formattedEvents = append(formattedEvents, ev) + formattedEvents[i] = ev } return TransactionResult{ Err: err, @@ -37,6 +37,7 @@ func (t TransactionResult) AssertFailure(msg string) TransactionResult { } return t } + func (t TransactionResult) AssertSuccess() TransactionResult { assert.NoError(t.Testing, t.Err) return t @@ -45,8 +46,8 @@ func (t TransactionResult) AssertSuccess() TransactionResult { func (t TransactionResult) AssertEventCount(number int) TransactionResult { assert.Equal(t.Testing, number, len(t.Events)) return t - } + func (t TransactionResult) AssertNoEvents() TransactionResult { assert.Empty(t.Testing, t.Events) @@ -58,9 +59,9 @@ func (t TransactionResult) AssertNoEvents() TransactionResult { } func (t TransactionResult) AssertEmitEventName(event ...string) TransactionResult { - var eventNames []string - for _, fe := range t.Events { - eventNames = append(eventNames, fe.Name) + eventNames := make([]string, len(t.Events)) + for i, fe := range t.Events { + eventNames[i] = fe.Name } for _, ev := range event { @@ -74,11 +75,11 @@ func (t TransactionResult) AssertEmitEventName(event ...string) TransactionResul return t } -func (t TransactionResult) AssertEmitEventJson(event ...string) TransactionResult { +func (t TransactionResult) AssertEmitEventJSON(event ...string) TransactionResult { - var jsonEvents []string - for _, fe := range t.Events { - jsonEvents = append(jsonEvents, fe.String()) + jsonEvents := make([]string, len(t.Events)) + for i, fe := range t.Events { + jsonEvents[i] = fe.String() } for _, ev := range event { @@ -96,7 +97,7 @@ func (t TransactionResult) AssertPartialEvent(expected *FormatedEvent) Transacti events := t.Events for index, ev := range events { - //todo do we need more then just name here? + // TODO do we need more then just name here? if ev.Name == expected.Name { for key := range ev.Fields { _, exist := expected.Fields[key] diff --git a/lib/go/iinft/gwtf/cadence.go b/lib/go/iinft/gwtf/cadence.go index 93b791a..ed33495 100644 --- a/lib/go/iinft/gwtf/cadence.go +++ b/lib/go/iinft/gwtf/cadence.go @@ -8,8 +8,8 @@ import ( "github.com/onflow/cadence" ) -// CadenceValueToJsonString converts a cadence.Value into a json pretty printed string -func CadenceValueToJsonString(value cadence.Value) string { +// CadenceValueToJSONString converts a cadence.Value into a json pretty printed string +func CadenceValueToJSONString(value cadence.Value) string { if value == nil { return "{}" } diff --git a/lib/go/iinft/gwtf/cadence_test.go b/lib/go/iinft/gwtf/cadence_test.go index 82a1024..ebd94d6 100644 --- a/lib/go/iinft/gwtf/cadence_test.go +++ b/lib/go/iinft/gwtf/cadence_test.go @@ -7,24 +7,24 @@ import ( "github.com/stretchr/testify/assert" ) -func TestCadenceValueToJsonString(t *testing.T) { +func TestCadenceValueToJSONString(t *testing.T) { t.Parallel() t.Run("Empty value should be empty json object", func(t *testing.T) { - value := CadenceValueToJsonString(nil) + value := CadenceValueToJSONString(nil) assert.Equal(t, "{}", value) }) t.Run("Empty optional should be empty string", func(t *testing.T) { - value := CadenceValueToJsonString(cadence.NewOptional(nil)) + value := CadenceValueToJSONString(cadence.NewOptional(nil)) assert.Equal(t, `""`, value) }) t.Run("Unwrap optional", func(t *testing.T) { - value := CadenceValueToJsonString(cadence.NewOptional(NewCadenceString("foo"))) + value := CadenceValueToJSONString(cadence.NewOptional(NewCadenceString("foo"))) assert.Equal(t, `"foo"`, value) }) t.Run("Array", func(t *testing.T) { - value := CadenceValueToJsonString(cadence.NewArray([]cadence.Value{NewCadenceString("foo"), NewCadenceString("bar")})) + value := CadenceValueToJSONString(cadence.NewArray([]cadence.Value{NewCadenceString("foo"), NewCadenceString("bar")})) assert.Equal(t, `[ "foo", "bar" @@ -33,7 +33,7 @@ func TestCadenceValueToJsonString(t *testing.T) { t.Run("Dictionary", func(t *testing.T) { dict := cadence.NewDictionary([]cadence.KeyValuePair{{Key: NewCadenceString("foo"), Value: NewCadenceString("bar")}}) - value := CadenceValueToJsonString(dict) + value := CadenceValueToJSONString(dict) assert.Equal(t, `{ "foo": "bar" }`, value) @@ -42,7 +42,7 @@ func TestCadenceValueToJsonString(t *testing.T) { t.Run("Dictionary nested", func(t *testing.T) { subDict := cadence.NewDictionary([]cadence.KeyValuePair{{Key: NewCadenceString("foo"), Value: NewCadenceString("bar")}}) dict := cadence.NewDictionary([]cadence.KeyValuePair{{Key: NewCadenceString("foo"), Value: NewCadenceString("bar")}, {Key: NewCadenceString("subdict"), Value: subDict}}) - value := CadenceValueToJsonString(dict) + value := CadenceValueToJSONString(dict) assert.Equal(t, `{ "foo": "bar", "subdict": { @@ -53,7 +53,7 @@ func TestCadenceValueToJsonString(t *testing.T) { t.Run("Dictionary", func(t *testing.T) { dict := cadence.NewDictionary([]cadence.KeyValuePair{{Key: cadence.NewUInt64(1), Value: cadence.NewUInt64(1)}}) - value := CadenceValueToJsonString(dict) + value := CadenceValueToJSONString(dict) assert.Equal(t, `{ "1": "1" }`, value) @@ -69,12 +69,11 @@ func TestCadenceValueToJsonString(t *testing.T) { }}, }, } - value := CadenceValueToJsonString(s) + value := CadenceValueToJSONString(s) assert.Equal(t, `{ "foo": "bar" }`, value) }) - } func NewCadenceString(value string) cadence.String { diff --git a/lib/go/iinft/gwtf/event.go b/lib/go/iinft/gwtf/event.go index 4936f1e..440544c 100644 --- a/lib/go/iinft/gwtf/event.go +++ b/lib/go/iinft/gwtf/event.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "log" "os" "sort" @@ -60,53 +59,53 @@ func (e EventFetcherBuilder) Event(eventName string) EventFetcherBuilder { return e } -//EventIgnoringFields fetch event and ignore the specified fields +// EventIgnoringFields fetch event and ignore the specified fields func (e EventFetcherBuilder) EventIgnoringFields(eventName string, ignoreFields []string) EventFetcherBuilder { e.EventsAndIgnoreFields[eventName] = ignoreFields return e } -//Start specify what blockHeight to fetch starting atm. This can be negative related to end/until +// Start specify what blockHeight to fetch starting atm. This can be negative related to end/until func (e EventFetcherBuilder) Start(blockHeight int64) EventFetcherBuilder { e.FromIndex = blockHeight return e } -//From specify what blockHeight to fetch from. This can be negative related to end. +// From specify what blockHeight to fetch from. This can be negative related to end. func (e EventFetcherBuilder) From(blockHeight int64) EventFetcherBuilder { e.FromIndex = blockHeight return e } -//End specify what index to end at +// End specify what index to end at func (e EventFetcherBuilder) End(blockHeight uint64) EventFetcherBuilder { e.EndIndex = blockHeight e.EndAtCurrentHeight = false return e } -//Last fetch events from the number last blocks +// Last fetch events from the number last blocks func (e EventFetcherBuilder) Last(number uint64) EventFetcherBuilder { e.EndAtCurrentHeight = true e.FromIndex = -int64(number) return e } -//Until specify what index to end at +// Until specify what index to end at func (e EventFetcherBuilder) Until(blockHeight uint64) EventFetcherBuilder { e.EndIndex = blockHeight e.EndAtCurrentHeight = false return e } -//UntilCurrent Specify to fetch events until the current Block +// UntilCurrent Specify to fetch events until the current Block func (e EventFetcherBuilder) UntilCurrent() EventFetcherBuilder { e.EndAtCurrentHeight = true e.EndIndex = 0 return e } -//TrackProgressIn Specify a file to store progress in +// TrackProgressIn Specify a file to store progress in func (e EventFetcherBuilder) TrackProgressIn(fileName string) EventFetcherBuilder { e.ProgressFile = fileName e.EndIndex = 0 @@ -131,18 +130,18 @@ func exists(path string) (bool, error) { func writeProgressToFile(fileName string, blockHeight uint64) error { - err := ioutil.WriteFile(fileName, []byte(fmt.Sprintf("%d", blockHeight)), 0644) + err := os.WriteFile(fileName, []byte(fmt.Sprintf("%d", blockHeight)), 0o0644) //nolint:gosec // inherited from GWTF if err != nil { - return fmt.Errorf("could not create initial progress file %v", err) + return fmt.Errorf("could not create initial progress file %w", err) } return nil } func readProgressFromFile(fileName string) (int64, error) { - dat, err := ioutil.ReadFile(fileName) + dat, err := os.ReadFile(fileName) if err != nil { - return 0, fmt.Errorf("ProgressFile is not valid %v", err) + return 0, fmt.Errorf("ProgressFile is not valid %w", err) } stringValue := strings.TrimSpace(string(dat)) @@ -150,10 +149,10 @@ func readProgressFromFile(fileName string) (int64, error) { return strconv.ParseInt(stringValue, 10, 64) } -//Run runs the eventfetcher returning events or an error +// Run runs the eventfetcher returning events or an error func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { - //if we have a progress file read the value from it and set it as oldHeight + // if we have a progress file read the value from it and set it as oldHeight if e.ProgressFile != "" { present, err := exists(e.ProgressFile) @@ -164,14 +163,14 @@ func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { if !present { err := writeProgressToFile(e.ProgressFile, 0) if err != nil { - return nil, fmt.Errorf("could not create initial progress file %v", err) + return nil, fmt.Errorf("could not create initial progress file %w", err) } e.FromIndex = 0 } else { oldHeight, err := readProgressFromFile(e.ProgressFile) if err != nil { - return nil, fmt.Errorf("could not parse progress file as block height %v", err) + return nil, fmt.Errorf("could not parse progress file as block height %w", err) } e.FromIndex = oldHeight } @@ -187,7 +186,7 @@ func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { } fromIndex := e.FromIndex - //if we have a negative fromIndex is is relative to endIndex + // if we have a negative fromIndex is relative to endIndex if e.FromIndex <= 0 { fromIndex = int64(endIndex) + e.FromIndex } @@ -198,7 +197,7 @@ func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { e.GoWithTheFlow.Logger.Info(fmt.Sprintf("Fetching events from %d to %d", fromIndex, endIndex)) - var events []string + events := make([]string, len(e.EventsAndIgnoreFields)) for key := range e.EventsAndIgnoreFields { events = append(events, key) } @@ -213,7 +212,7 @@ func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { if e.ProgressFile != "" { err := writeProgressToFile(e.ProgressFile, endIndex+1) if err != nil { - return nil, fmt.Errorf("could not write progress to file %v", err) + return nil, fmt.Errorf("could not write progress to file %w", err) } } sort.Slice(formatedEvents, func(i, j int) bool { @@ -221,10 +220,9 @@ func (e EventFetcherBuilder) Run() ([]*FormatedEvent, error) { }) return formatedEvents, nil - } -//PrintEvents prints th events, ignoring fields specified for the given event typeID +// PrintEvents prints th events, ignoring fields specified for the given event typeID func PrintEvents(events []flow.Event, ignoreFields map[string][]string) { if len(events) > 0 { log.Println("EVENTS") @@ -248,7 +246,7 @@ func PrintEvents(events []flow.Event, ignoreFields map[string][]string) { } } -//FormatEvents +// FormatEvents func FormatEvents(blockEvents []client.BlockEvents, ignoreFields map[string][]string) []*FormatedEvent { var events []*FormatedEvent @@ -261,13 +259,12 @@ func FormatEvents(blockEvents []client.BlockEvents, ignoreFields map[string][]st return events } -//ParseEvent parses a flow event into a more terse representation +// ParseEvent parses a flow event into a more terse representation func ParseEvent(event flow.Event, blockHeight uint64, time time.Time, ignoreFields []string) *FormatedEvent { - var fieldNames []string - - for _, eventTypeFields := range event.Value.EventType.Fields { - fieldNames = append(fieldNames, eventTypeFields.Identifier) + fieldNames := make([]string, len(event.Value.EventType.Fields)) + for i, eventTypeFields := range event.Value.EventType.Fields { + fieldNames[i] = eventTypeFields.Identifier } finalFields := map[string]interface{}{} @@ -316,7 +313,7 @@ func NewTestEvent(name string, fields map[string]interface{}) *FormatedEvent { } } -//String pretty print an event as a String +// String pretty print an event as a String func (e FormatedEvent) String() string { j, err := json.MarshalIndent(e, "", " ") if err != nil { diff --git a/lib/go/iinft/gwtf/event_test.go b/lib/go/iinft/gwtf/event_test.go index 9aa3014..251d34e 100644 --- a/lib/go/iinft/gwtf/event_test.go +++ b/lib/go/iinft/gwtf/event_test.go @@ -69,6 +69,5 @@ func TestEvent(t *testing.T) { err = writeProgressToFile("foo", 1) assert.Error(t, err) assert.Contains(t, err.Error(), "foo: is a directory") - }) } diff --git a/lib/go/iinft/gwtf/script.go b/lib/go/iinft/gwtf/script.go index 74533d9..091f00b 100644 --- a/lib/go/iinft/gwtf/script.go +++ b/lib/go/iinft/gwtf/script.go @@ -9,7 +9,7 @@ import ( "github.com/onflow/flow-go-sdk" ) -//FlowScriptBuilder is a struct to hold information for running a script +// FlowScriptBuilder is a struct to hold information for running a script type FlowScriptBuilder struct { GoWithTheFlow *GoWithTheFlow FileName string @@ -17,7 +17,7 @@ type FlowScriptBuilder struct { ScriptAsString string } -//Script start a script builder with the inline script as body +// Script start a script builder with the inline script as body func (f *GoWithTheFlow) Script(content string) FlowScriptBuilder { return FlowScriptBuilder{ GoWithTheFlow: f, @@ -27,7 +27,7 @@ func (f *GoWithTheFlow) Script(content string) FlowScriptBuilder { } } -//ScriptFromFile will start a flow script builder +// ScriptFromFile will start a flow script builder func (f *GoWithTheFlow) ScriptFromFile(filename string) FlowScriptBuilder { return FlowScriptBuilder{ GoWithTheFlow: f, @@ -37,7 +37,7 @@ func (f *GoWithTheFlow) ScriptFromFile(filename string) FlowScriptBuilder { } } -//AccountArgument add an account as an argument +// AccountArgument add an account as an argument func (t FlowScriptBuilder) AccountArgument(key string) FlowScriptBuilder { f := t.GoWithTheFlow @@ -45,7 +45,7 @@ func (t FlowScriptBuilder) AccountArgument(key string) FlowScriptBuilder { return t.Argument(cadence.BytesToAddress(account.Address().Bytes())) } -//RawAccountArgument add an account from a string as an argument +// RawAccountArgument add an account from a string as an argument func (t FlowScriptBuilder) RawAccountArgument(key string) FlowScriptBuilder { account := flow.HexToAddress(key) @@ -53,123 +53,123 @@ func (t FlowScriptBuilder) RawAccountArgument(key string) FlowScriptBuilder { return t.Argument(accountArg) } -//DateStringAsUnixTimestamp sends a dateString parsed in the timezone as a unix timeszone ufix -func (t FlowScriptBuilder) DateStringAsUnixTimestamp(dateString string, timezone string) FlowScriptBuilder { +// DateStringAsUnixTimestamp sends a dateString parsed in the timezone as a unix timeszone ufix +func (t FlowScriptBuilder) DateStringAsUnixTimestamp(dateString, timezone string) FlowScriptBuilder { return t.UFix64Argument(parseTime(dateString, timezone)) } -//Argument add an argument to the transaction +// Argument add an argument to the transaction func (t FlowScriptBuilder) Argument(value cadence.Value) FlowScriptBuilder { t.Arguments = append(t.Arguments, value) return t } -//StringArgument add a String Argument to the transaction +// StringArgument add a String Argument to the transaction func (t FlowScriptBuilder) StringArgument(value string) FlowScriptBuilder { return t.Argument(cadence.String(value)) } -//BooleanArgument add a Boolean Argument to the transaction +// BooleanArgument add a Boolean Argument to the transaction func (t FlowScriptBuilder) BooleanArgument(value bool) FlowScriptBuilder { return t.Argument(cadence.NewBool(value)) } -//BytesArgument add a Bytes Argument to the transaction +// BytesArgument add a Bytes Argument to the transaction func (t FlowScriptBuilder) BytesArgument(value []byte) FlowScriptBuilder { return t.Argument(cadence.NewBytes(value)) } -//IntArgument add an Int Argument to the transaction +// IntArgument add an Int Argument to the transaction func (t FlowScriptBuilder) IntArgument(value int) FlowScriptBuilder { return t.Argument(cadence.NewInt(value)) } -//Int8Argument add an Int8 Argument to the transaction +// Int8Argument add an Int8 Argument to the transaction func (t FlowScriptBuilder) Int8Argument(value int8) FlowScriptBuilder { return t.Argument(cadence.NewInt8(value)) } -//Int16Argument add an Int16 Argument to the transaction +// Int16Argument add an Int16 Argument to the transaction func (t FlowScriptBuilder) Int16Argument(value int16) FlowScriptBuilder { return t.Argument(cadence.NewInt16(value)) } -//Int32Argument add an Int32 Argument to the transaction +// Int32Argument add an Int32 Argument to the transaction func (t FlowScriptBuilder) Int32Argument(value int32) FlowScriptBuilder { return t.Argument(cadence.NewInt32(value)) } -//Int64Argument add an Int64 Argument to the transaction +// Int64Argument add an Int64 Argument to the transaction func (t FlowScriptBuilder) Int64Argument(value int64) FlowScriptBuilder { return t.Argument(cadence.NewInt64(value)) } -//Int128Argument add an Int128 Argument to the transaction +// Int128Argument add an Int128 Argument to the transaction func (t FlowScriptBuilder) Int128Argument(value int) FlowScriptBuilder { return t.Argument(cadence.NewInt128(value)) } -//Int256Argument add an Int256 Argument to the transaction +// Int256Argument add an Int256 Argument to the transaction func (t FlowScriptBuilder) Int256Argument(value int) FlowScriptBuilder { return t.Argument(cadence.NewInt256(value)) } -//UIntArgument add an UInt Argument to the transaction +// UIntArgument add an UInt Argument to the transaction func (t FlowScriptBuilder) UIntArgument(value uint) FlowScriptBuilder { return t.Argument(cadence.NewUInt(value)) } -//UInt8Argument add an UInt8 Argument to the transaction +// UInt8Argument add an UInt8 Argument to the transaction func (t FlowScriptBuilder) UInt8Argument(value uint8) FlowScriptBuilder { return t.Argument(cadence.NewUInt8(value)) } -//UInt16Argument add an UInt16 Argument to the transaction +// UInt16Argument add an UInt16 Argument to the transaction func (t FlowScriptBuilder) UInt16Argument(value uint16) FlowScriptBuilder { return t.Argument(cadence.NewUInt16(value)) } -//UInt32Argument add an UInt32 Argument to the transaction +// UInt32Argument add an UInt32 Argument to the transaction func (t FlowScriptBuilder) UInt32Argument(value uint32) FlowScriptBuilder { return t.Argument(cadence.NewUInt32(value)) } -//UInt64Argument add an UInt64 Argument to the transaction +// UInt64Argument add an UInt64 Argument to the transaction func (t FlowScriptBuilder) UInt64Argument(value uint64) FlowScriptBuilder { return t.Argument(cadence.NewUInt64(value)) } -//UInt128Argument add an UInt128 Argument to the transaction +// UInt128Argument add an UInt128 Argument to the transaction func (t FlowScriptBuilder) UInt128Argument(value uint) FlowScriptBuilder { return t.Argument(cadence.NewUInt128(value)) } -//UInt256Argument add an UInt256 Argument to the transaction +// UInt256Argument add an UInt256 Argument to the transaction func (t FlowScriptBuilder) UInt256Argument(value uint) FlowScriptBuilder { return t.Argument(cadence.NewUInt256(value)) } -//Word8Argument add a Word8 Argument to the transaction +// Word8Argument add a Word8 Argument to the transaction func (t FlowScriptBuilder) Word8Argument(value uint8) FlowScriptBuilder { return t.Argument(cadence.NewWord8(value)) } -//Word16Argument add a Word16 Argument to the transaction +// Word16Argument add a Word16 Argument to the transaction func (t FlowScriptBuilder) Word16Argument(value uint16) FlowScriptBuilder { return t.Argument(cadence.NewWord16(value)) } -//Word32Argument add a Word32 Argument to the transaction +// Word32Argument add a Word32 Argument to the transaction func (t FlowScriptBuilder) Word32Argument(value uint32) FlowScriptBuilder { return t.Argument(cadence.NewWord32(value)) } -//Word64Argument add a Word64 Argument to the transaction +// Word64Argument add a Word64 Argument to the transaction func (t FlowScriptBuilder) Word64Argument(value uint64) FlowScriptBuilder { return t.Argument(cadence.NewWord64(value)) } -//Fix64Argument add a Fix64 Argument to the transaction +// Fix64Argument add a Fix64 Argument to the transaction func (t FlowScriptBuilder) Fix64Argument(value string) FlowScriptBuilder { amount, err := cadence.NewFix64(value) if err != nil { @@ -178,7 +178,7 @@ func (t FlowScriptBuilder) Fix64Argument(value string) FlowScriptBuilder { return t.Argument(amount) } -//UFix64Argument add a UFix64 Argument to the transaction +// UFix64Argument add a UFix64 Argument to the transaction func (t FlowScriptBuilder) UFix64Argument(value string) FlowScriptBuilder { amount, err := cadence.NewUFix64(value) if err != nil { @@ -190,7 +190,7 @@ func (t FlowScriptBuilder) UFix64Argument(value string) FlowScriptBuilder { // Run executes a read only script func (t FlowScriptBuilder) Run() { result := t.RunFailOnError() - log.Printf("Script run from result: %v\n", CadenceValueToJsonString(result)) + log.Printf("Script run from result: %v\n", CadenceValueToJSONString(result)) } // RunReturns executes a read only script @@ -220,6 +220,7 @@ func (t FlowScriptBuilder) RunReturns() (cadence.Value, error) { f.Logger.Debug(fmt.Sprintf("Script run from path %s\n", scriptFilePath)) return result, nil } + func (t FlowScriptBuilder) RunFailOnError() cadence.Value { result, err := t.RunReturns() if err != nil { @@ -227,15 +228,14 @@ func (t FlowScriptBuilder) RunFailOnError() cadence.Value { os.Exit(1) } return result - } -//RunReturnsJsonString runs the script and returns pretty printed json string -func (t FlowScriptBuilder) RunReturnsJsonString() string { - return CadenceValueToJsonString(t.RunFailOnError()) +// RunReturnsJSONString runs the script and returns pretty printed json string +func (t FlowScriptBuilder) RunReturnsJSONString() string { + return CadenceValueToJSONString(t.RunFailOnError()) } -//RunReturnsInterface runs the script and returns interface{} +// RunReturnsInterface runs the script and returns interface{} func (t FlowScriptBuilder) RunReturnsInterface() interface{} { return CadenceValueToInterface(t.RunFailOnError()) } diff --git a/lib/go/iinft/gwtf/script_test.go b/lib/go/iinft/gwtf/script_test.go index 59a2fbe..9ea80c2 100644 --- a/lib/go/iinft/gwtf/script_test.go +++ b/lib/go/iinft/gwtf/script_test.go @@ -14,8 +14,8 @@ func TestSetupFails(t *testing.T) { _, err := g.CreateAccountsE("foobar") assert.Error(t, err) assert.Contains(t, err.Error(), "could not find account with name foobar") - } + func TestScriptArguments(t *testing.T) { g := NewGoWithTheFlow([]string{"../../../../flow.json"}, "emulator", true, output.NoneLog) t.Parallel() @@ -40,7 +40,6 @@ func TestScriptArguments(t *testing.T) { assert.Contains(t, builder.Arguments, ufix) assert.Contains(t, builder.Arguments, NewCadenceString("test")) assert.Contains(t, builder.Arguments, dateFix) - }) t.Run("Word argument test", func(t *testing.T) { diff --git a/lib/go/iinft/gwtf/setup.go b/lib/go/iinft/gwtf/setup.go index 8e407b4..4f5a10a 100644 --- a/lib/go/iinft/gwtf/setup.go +++ b/lib/go/iinft/gwtf/setup.go @@ -21,33 +21,32 @@ type GoWithTheFlow struct { PrependNetworkToAccountNames bool } -//NewGoWithTheFlowInMemoryEmulator this method is used to create an in memory emulator, deploy all contracts for the emulator and create all accounts +// NewGoWithTheFlowInMemoryEmulator this method is used to create an in memory emulator, deploy all contracts for the emulator and create all accounts func NewGoWithTheFlowInMemoryEmulator() *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), "emulator", true, output.InfoLog).InitializeContracts().CreateAccounts("emulator-account") } -//NewTEstingEmulator create new emulator that ignore all log messages +// NewTestingEmulator create new emulator that ignore all log messages func NewTestingEmulator() *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), "emulator", true, output.NoneLog).InitializeContracts().CreateAccounts("emulator-account") } -//NewGoWithTheFlowForNetwork creates a new gwtf client for the provided network +// NewGoWithTheFlowForNetwork creates a new gwtf client for the provided network func NewGoWithTheFlowForNetwork(network string) *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), network, false, output.InfoLog) - } -//NewGoWithTheFlowEmulator create a new client +// NewGoWithTheFlowEmulator create a new client func NewGoWithTheFlowEmulator() *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), "emulator", false, output.InfoLog) } -//NewGoWithTheFlowDevNet creates a new gwtf client for devnet/testnet +// NewGoWithTheFlowDevNet creates a new gwtf client for devnet/testnet func NewGoWithTheFlowDevNet() *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), "testnet", false, output.InfoLog) } -//NewGoWithTheFlowMainNet creates a new gwft client for mainnet +// NewGoWithTheFlowMainNet creates a new gwft client for mainnet func NewGoWithTheFlowMainNet() *GoWithTheFlow { return NewGoWithTheFlow(config.DefaultPaths(), "mainnet", false, output.InfoLog) } @@ -61,13 +60,13 @@ func NewGoWithTheFlow(filenames []string, network string, inMemory bool, logleve return gwtf } -//DoNotPrependNetworkToAccountNames disable the default behavior of prefixing account names with network- +// DoNotPrependNetworkToAccountNames disable the default behavior of prefixing account names with network- func (f *GoWithTheFlow) DoNotPrependNetworkToAccountNames() *GoWithTheFlow { f.PrependNetworkToAccountNames = false return f } -//Account fetch an account from flow.json, prefixing the name with network- as default (can be turned off) +// Account fetch an account from flow.json, prefixing the name with network- as default (can be turned off) func (f *GoWithTheFlow) Account(key string) *flowkit.Account { if f.PrependNetworkToAccountNames { key = fmt.Sprintf("%s-%s", f.Network, key) @@ -79,7 +78,6 @@ func (f *GoWithTheFlow) Account(key string) *flowkit.Account { } return account - } // NewGoWithTheFlowError creates a new local go with the flow client @@ -94,7 +92,7 @@ func NewGoWithTheFlowError(paths []string, network string, inMemory bool, logLev logger := output.NewStdoutLogger(logLevel) var service *services.Services if inMemory { - //YAY we can run it inline in memory! + // YAY, we can run it inline in memory! acc, _ := state.EmulatorServiceAccount() gw := gateway.NewEmulatorGateway(acc) service = services.NewServices(gw, state, logger) @@ -117,5 +115,4 @@ func NewGoWithTheFlowError(paths []string, network string, inMemory bool, logLev Logger: logger, PrependNetworkToAccountNames: true, }, nil - } diff --git a/lib/go/iinft/gwtf/templates.go b/lib/go/iinft/gwtf/templates.go index 63b88b3..8034423 100644 --- a/lib/go/iinft/gwtf/templates.go +++ b/lib/go/iinft/gwtf/templates.go @@ -4,7 +4,7 @@ import ( "bufio" "encoding/base64" "fmt" - "io/ioutil" + "io" "math" "net/http" "os" @@ -15,7 +15,7 @@ func splitByWidthMake(str string, size int) []string { splitedLength := int(math.Ceil(float64(strLength) / float64(size))) splited := make([]string, splitedLength) var start, stop int - for i := 0; i < splitedLength; i += 1 { + for i := 0; i < splitedLength; i++ { start = i * size stop = start + size if stop > strLength { @@ -33,15 +33,15 @@ func fileAsImageData(path string) (string, error) { // Read entire JPG into byte slice. reader := bufio.NewReader(f) - content, err := ioutil.ReadAll(reader) + content, err := io.ReadAll(reader) if err != nil { return "", fmt.Errorf("could not read imageFile %s, %w", path, err) } - return contentAsImageDataUrl(content), nil + return contentAsImageDataURL(content), nil } -func contentAsImageDataUrl(content []byte) string { +func contentAsImageDataURL(content []byte) string { contentType := http.DetectContentType(content) // Encode as base64. @@ -57,7 +57,7 @@ func fileAsBase64(path string) (string, error) { // Read entire JPG into byte slice. reader := bufio.NewReader(f) - content, err := ioutil.ReadAll(reader) + content, err := io.ReadAll(reader) if err != nil { return "", fmt.Errorf("could not read file %s, %w", path, err) } @@ -68,8 +68,8 @@ func fileAsBase64(path string) (string, error) { return encoded, nil } -//UploadFile reads a file, base64 encodes it and chunk upload to /storage/upload -func (f *GoWithTheFlow) UploadFile(filename string, accountName string) error { +// UploadFile reads a file, base64 encodes it and chunk upload to /storage/upload +func (f *GoWithTheFlow) UploadFile(filename, accountName string) error { content, err := fileAsBase64(filename) if err != nil { return err @@ -78,20 +78,20 @@ func (f *GoWithTheFlow) UploadFile(filename string, accountName string) error { return f.UploadString(content, accountName) } -func getUrl(url string) ([]byte, error) { - resp, err := http.Get(url) +func getURL(url string) ([]byte, error) { + resp, err := http.Get(url) //nolint:gosec // inherited from GWTF if err != nil { return nil, err } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } -//DownloadAndUploadFile reads a file, base64 encodes it and chunk upload to /storage/upload -func (f *GoWithTheFlow) DownloadAndUploadFile(url string, accountName string) error { - body, err := getUrl(url) +// DownloadAndUploadFile reads a file, base64 encodes it and chunk upload to /storage/upload +func (f *GoWithTheFlow) DownloadAndUploadFile(url, accountName string) error { + body, err := getURL(url) if err != nil { return err } @@ -100,19 +100,19 @@ func (f *GoWithTheFlow) DownloadAndUploadFile(url string, accountName string) er return f.UploadString(encoded, accountName) } -//DownloadImageAndUploadAsDataUrl download an image and upload as data url -func (f *GoWithTheFlow) DownloadImageAndUploadAsDataUrl(url, accountName string) error { - body, err := getUrl(url) +// DownloadImageAndUploadAsDataURL download an image and upload as data url +func (f *GoWithTheFlow) DownloadImageAndUploadAsDataURL(url, accountName string) error { + body, err := getURL(url) if err != nil { return err } - content := contentAsImageDataUrl(body) + content := contentAsImageDataURL(body) return f.UploadString(content, accountName) } -//UploadImageAsDataUrl will upload a image file from the filesystem into /storage/upload of the given account -func (f *GoWithTheFlow) UploadImageAsDataUrl(filename string, accountName string) error { +// UploadImageAsDataURL will upload a image file from the filesystem into /storage/upload of the given account +func (f *GoWithTheFlow) UploadImageAsDataURL(filename, accountName string) error { content, err := fileAsImageData(filename) if err != nil { return err @@ -121,9 +121,9 @@ func (f *GoWithTheFlow) UploadImageAsDataUrl(filename string, accountName string return f.UploadString(content, accountName) } -//UploadString will upload the given string data in 1mb chunkts to /storage/upload of the given account -func (f *GoWithTheFlow) UploadString(content string, accountName string) error { - //unload previous content if any. +// UploadString will upload the given string data in 1mb chunkts to /storage/upload of the given account +func (f *GoWithTheFlow) UploadString(content, accountName string) error { + // unload previous content if any. if _, err := f.Transaction(` transaction { prepare(signer: AuthAccount) { diff --git a/lib/go/iinft/gwtf/transaction.go b/lib/go/iinft/gwtf/transaction.go index 80a56d6..2dc0acc 100644 --- a/lib/go/iinft/gwtf/transaction.go +++ b/lib/go/iinft/gwtf/transaction.go @@ -204,12 +204,12 @@ func (tb FlowTransactionBuilder) Fix64Argument(value string) FlowTransactionBuil return tb.Argument(amount) } -// DateStringAsUnixTimestamp sends a dateString parsed in the timezone as a unix timeszone ufix +// DateStringAsUnixTimestamp sends a dateString parsed in the timezone as a unix timezone ufix func (tb FlowTransactionBuilder) DateStringAsUnixTimestamp(dateString string, timezone string) FlowTransactionBuilder { return tb.UFix64Argument(parseTime(dateString, timezone)) } -func parseTime(timeString string, location string) string { +func parseTime(timeString, location string) string { loc, err := time.LoadLocation(location) if err != nil { panic(err) @@ -241,13 +241,13 @@ func (tb FlowTransactionBuilder) Argument(value cadence.Value) FlowTransactionBu // StringArrayArgument add a string array argument to the transaction func (tb FlowTransactionBuilder) StringArrayArgument(value ...string) FlowTransactionBuilder { - var array []cadence.Value - for _, val := range value { - value, err := cadence.NewString(val) + array := make([]cadence.Value, len(value)) + for i, val := range value { + v, err := cadence.NewString(val) if err != nil { panic(err) } - array = append(array, value) + array[i] = v } tb.Arguments = append(tb.Arguments, cadence.NewArray(array)) return tb @@ -302,10 +302,10 @@ func (tb FlowTransactionBuilder) RunE() ([]flow.Event, error) { authorizerAccounts = append(authorizerAccounts, tb.MainSigner) } - var authorizers []flow.Address + authorizers := make([]flow.Address, len(authorizerAccounts)) var signers []*flowkit.Account - for _, signer := range authorizerAccounts { - authorizers = append(authorizers, signer.Address()) + for i, signer := range authorizerAccounts { + authorizers[i] = signer.Address() if signer.Name() != tb.Payer.Name() { signers = append(signers, signer) } diff --git a/lib/go/iinft/logger.go b/lib/go/iinft/logger.go index f8e6bcf..fd02b68 100644 --- a/lib/go/iinft/logger.go +++ b/lib/go/iinft/logger.go @@ -24,23 +24,23 @@ func NewFlowKitLogger() output.Logger { } } -func (l logger) Debug(s string) { +func (l *logger) Debug(s string) { log.Debug().Msg(stripLineBreaks(s)) } -func (l logger) Info(s string) { +func (l *logger) Info(s string) { log.Info().Msg(stripLineBreaks(s)) } -func (l logger) Error(s string) { +func (l *logger) Error(s string) { log.Error().Msg(stripLineBreaks(s)) } -func (l logger) StartProgress(s string) { +func (l *logger) StartProgress(s string) { log.Debug().Msg(stripLineBreaks(s)) } -func (l logger) StopProgress() { +func (l *logger) StopProgress() { // do nothing } diff --git a/lib/go/iinft/scripts/engine.go b/lib/go/iinft/scripts/engine.go index 1fcdbd0..c80394b 100644 --- a/lib/go/iinft/scripts/engine.go +++ b/lib/go/iinft/scripts/engine.go @@ -109,9 +109,8 @@ func (e *Engine) GetStandardScript(scriptID string) string { panic(err) } - s = string(buf.Bytes()) + s = buf.String() e.preloadedTemplates[scriptID] = s - } return s @@ -129,7 +128,7 @@ func (e *Engine) GetCustomScript(scriptID string, params interface{}) string { panic(err) } - return string(buf.Bytes()) + return buf.String() } func (e *Engine) NewTransaction(scriptID string) gwtf.FlowTransactionBuilder { diff --git a/lib/go/iinft/scripts/helpers.go b/lib/go/iinft/scripts/helpers.go index 9708fde..2fed966 100644 --- a/lib/go/iinft/scripts/helpers.go +++ b/lib/go/iinft/scripts/helpers.go @@ -1,7 +1,6 @@ package scripts import ( - _ "github.com/kevinburke/go-bindata" "github.com/onflow/flow-go-sdk" "github.com/piprate/sequel-flow-contracts/lib/go/iinft" "github.com/piprate/sequel-flow-contracts/lib/go/iinft/evergreen" diff --git a/lib/go/iinft/scripts/testing.go b/lib/go/iinft/scripts/testing.go index 6dcce75..c4b633f 100644 --- a/lib/go/iinft/scripts/testing.go +++ b/lib/go/iinft/scripts/testing.go @@ -14,6 +14,8 @@ import ( ) func ConfigureInMemoryEmulator(t *testing.T, client *gwtf.GoWithTheFlow, adminFlowDeposit string) { + t.Helper() + _, err := client.DoNotPrependNetworkToAccountNames().CreateAccountsE("emulator-account") require.NoError(t, err) @@ -26,6 +28,8 @@ func ConfigureInMemoryEmulator(t *testing.T, client *gwtf.GoWithTheFlow, adminFl } func FundAccountWithFlow(t *testing.T, client *gwtf.GoWithTheFlow, receiverAddress flow.Address, amount string) { + t.Helper() + contracts := client.State.Contracts().ByNetwork(client.Network) addrMap := make(map[string]string) for _, contract := range contracts { @@ -39,7 +43,7 @@ func FundAccountWithFlow(t *testing.T, client *gwtf.GoWithTheFlow, receiverAddre panic(err) } - script := string(buf.Bytes()) + script := buf.String() _ = client.Transaction(script). Argument(cadence.NewAddress(receiverAddress)). @@ -50,6 +54,8 @@ func FundAccountWithFlow(t *testing.T, client *gwtf.GoWithTheFlow, receiverAddre } func GetFlowBalance(t *testing.T, se *Engine, address flow.Address) float64 { + t.Helper() + v, err := se.NewScript("account_balance_flow"). Argument(cadence.NewAddress(address)). RunReturns() @@ -59,6 +65,8 @@ func GetFlowBalance(t *testing.T, se *Engine, address flow.Address) float64 { } func PrepareFUSDMinter(t *testing.T, se *Engine, minterAddress flow.Address) { + t.Helper() + _ = se.NewTransaction("service_setup_fusd_minter"). SignProposeAndPayAsService(). Test(t). @@ -72,6 +80,8 @@ func PrepareFUSDMinter(t *testing.T, se *Engine, minterAddress flow.Address) { } func FundAccountWithFUSD(t *testing.T, se *Engine, receiverAddress flow.Address, amount string) { + t.Helper() + _ = se.NewTransaction("account_fund_fusd"). Argument(cadence.NewAddress(receiverAddress)). UFix64Argument(amount). @@ -81,6 +91,8 @@ func FundAccountWithFUSD(t *testing.T, se *Engine, receiverAddress flow.Address, } func GetFUSDBalance(t *testing.T, se *Engine, address flow.Address) float64 { + t.Helper() + v, err := se.NewScript("account_balance_fusd"). Argument(cadence.NewAddress(address)). RunReturns() diff --git a/lib/go/iinft/test/digitalart_test.go b/lib/go/iinft/test/digitalart_test.go index c3f9d70..ab9d52f 100644 --- a/lib/go/iinft/test/digitalart_test.go +++ b/lib/go/iinft/test/digitalart_test.go @@ -17,8 +17,12 @@ import ( ) const ( - adminAccount = "emulator-sequel-admin" - initialFlowBalance = 0.001 + adminAccountName = "emulator-sequel-admin" + platformAccountName = "emulator-sequel-platform" + user1AccountName = "emulator-user1" + user2AccountName = "emulator-user2" + user3AccountName = "emulator-user3" + initialFlowBalance = 0.001 ) func init() { @@ -34,7 +38,7 @@ func TestSealDigitalArtMaster(t *testing.T) { se, err := scripts.NewEngine(client, false) require.NoError(t, err) - userAcct := client.Account("emulator-user1") + userAcct := client.Account(user1AccountName) sampleMetadata := &iinft.DigitalArtMetadata{ MetadataURI: "ipfs://QmMetadata", @@ -66,7 +70,7 @@ func TestSealDigitalArtMaster(t *testing.T) { t.Run("Should be able to seal new digital art master", func(t *testing.T) { _ = scripts.CreateSealDigitalArtTx(se, client, sampleMetadata, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() }) @@ -79,13 +83,13 @@ func TestSealDigitalArtMaster(t *testing.T) { // Seal the master _ = scripts.CreateSealDigitalArtTx(se, client, &sampleMetadata2, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() // try again _ = scripts.CreateSealDigitalArtTx(se, client, &sampleMetadata2, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertFailure("master already sealed") }) @@ -100,12 +104,12 @@ func TestMintDigitalArtEditions(t *testing.T) { se, err := scripts.NewEngine(client, false) require.NoError(t, err) - userAcct := client.Account("emulator-user1") + userAcct := client.Account(user1AccountName) scripts.FundAccountWithFlow(t, client, userAcct.Address(), "10.0") _ = se.NewTransaction("account_setup"). - SignProposeAndPayAs("emulator-user1"). + SignProposeAndPayAs(user1AccountName). Test(t). AssertSuccess() @@ -140,14 +144,14 @@ func TestMintDigitalArtEditions(t *testing.T) { } _ = scripts.CreateSealDigitalArtTx(se, client, metadata, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() t.Run("Should be able to mint a token", func(t *testing.T) { _ = client.Transaction(se.GetStandardScript("digitalart_mint_edition")). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). Argument(cadence.Address(userAcct.Address())). @@ -250,7 +254,7 @@ pub fun main(address:Address, tokenID:UInt64) : DigitalArt.Metadata? { t.Run("Editions should have different metadata", func(t *testing.T) { _ = client.Transaction(se.GetStandardScript("digitalart_mint_edition")). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). Argument(cadence.Address(userAcct.Address())). @@ -310,16 +314,15 @@ func TestMintDigitalArtEditionsOnDemandFUSD(t *testing.T) { // set up platform account - platformAcctName := "emulator-sequel-platform" - platformAcct := client.Account(platformAcctName) + platformAcct := client.Account(platformAccountName) scripts.FundAccountWithFlow(t, client, platformAcct.Address(), "10.0") - _ = se.NewTransaction("account_setup_fusd").SignProposeAndPayAs(platformAcctName).Test(t).AssertSuccess() + _ = se.NewTransaction("account_setup_fusd").SignProposeAndPayAs(platformAccountName).Test(t).AssertSuccess() // set up green account - greenAcctName := "emulator-user3" + greenAcctName := user3AccountName greenAcct := client.Account(greenAcctName) scripts.FundAccountWithFlow(t, client, greenAcct.Address(), "10.0") @@ -328,7 +331,7 @@ func TestMintDigitalArtEditionsOnDemandFUSD(t *testing.T) { // set up artist account - artistAcctName := "emulator-user1" + artistAcctName := user1AccountName artistAcct := client.Account(artistAcctName) scripts.FundAccountWithFlow(t, client, artistAcct.Address(), "10.0") @@ -337,7 +340,7 @@ func TestMintDigitalArtEditionsOnDemandFUSD(t *testing.T) { // set up buyer account - buyerAcctName := "emulator-user2" + buyerAcctName := user2AccountName buyerAcct := client.Account(buyerAcctName) scripts.FundAccountWithFlow(t, client, buyerAcct.Address(), "10.0") @@ -396,7 +399,7 @@ The End.`, Profile: profile, })). PayloadSigner(buyerAcctName). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). UFix64Argument("100.0"). @@ -449,7 +452,7 @@ The End.`, Profile: profile, })). PayloadSigner(buyerAcctName). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). UFix64Argument("100.0"). @@ -507,22 +510,21 @@ func TestMintDigitalArtEditionsOnDemandFlow(t *testing.T) { // set up platform account - platformAcctName := "emulator-sequel-platform" - platformAcct := client.Account(platformAcctName) + platformAcct := client.Account(platformAccountName) // set up green account - greenAcctName := "emulator-user3" + greenAcctName := user3AccountName greenAcct := client.Account(greenAcctName) // set up artist account - artistAcctName := "emulator-user1" + artistAcctName := user1AccountName artistAcct := client.Account(artistAcctName) // set up buyer account - buyerAcctName := "emulator-user2" + buyerAcctName := user2AccountName buyerAcct := client.Account(buyerAcctName) scripts.FundAccountWithFlow(t, client, buyerAcct.Address(), "1000.0") @@ -579,7 +581,7 @@ The End.`, Profile: profile, })). PayloadSigner(buyerAcctName). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). UFix64Argument("100.0"). @@ -632,7 +634,7 @@ The End.`, Profile: profile, })). PayloadSigner(buyerAcctName). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). UFix64Argument("100.0"). @@ -688,12 +690,12 @@ func TestTransferDigitalArt(t *testing.T) { se, err := scripts.NewEngine(client, false) require.NoError(t, err) - senderAcctName := "emulator-user1" + senderAcctName := user1AccountName senderAcct := client.Account(senderAcctName) scripts.FundAccountWithFlow(t, client, senderAcct.Address(), "10.0") - receiverAcctName := "emulator-user2" + receiverAcctName := user2AccountName receiverAcct := client.Account(receiverAcctName) scripts.FundAccountWithFlow(t, client, receiverAcct.Address(), "10.0") @@ -731,12 +733,12 @@ func TestTransferDigitalArt(t *testing.T) { } _ = scripts.CreateSealDigitalArtTx(se, client, metadata, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() _ = client.Transaction(se.GetStandardScript("digitalart_mint_edition")). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). Argument(cadence.Address(senderAcct.Address())). @@ -795,6 +797,8 @@ func TestTransferDigitalArt(t *testing.T) { } func checkDigitalArtNFTSupply(t *testing.T, se *scripts.Engine, expectedSupply int) { + t.Helper() + _, err := se.NewInlineScript( inspectNFTSupplyScript(se.WellKnownAddresses(), "DigitalArt", expectedSupply), ).RunReturns() @@ -802,6 +806,8 @@ func checkDigitalArtNFTSupply(t *testing.T, se *scripts.Engine, expectedSupply i } func checkTokenInDigitalArtCollection(t *testing.T, se *scripts.Engine, userAddr string, nftID uint64) { + t.Helper() + _, err := se.NewInlineScript( inspectCollectionScript(se.WellKnownAddresses(), userAddr, "DigitalArt", "DigitalArt.CollectionPublicPath", nftID), ).RunReturns() @@ -809,6 +815,8 @@ func checkTokenInDigitalArtCollection(t *testing.T, se *scripts.Engine, userAddr } func checkDigitalArtCollectionLen(t *testing.T, se *scripts.Engine, userAddr string, length int) { + t.Helper() + _, err := se.NewInlineScript( inspectCollectionLenScript(se.WellKnownAddresses(), userAddr, "DigitalArt", "DigitalArt.CollectionPublicPath", length), ).RunReturns() diff --git a/lib/go/iinft/test/fusd_test.go b/lib/go/iinft/test/fusd_test.go index 239ca9c..a7c38d7 100644 --- a/lib/go/iinft/test/fusd_test.go +++ b/lib/go/iinft/test/fusd_test.go @@ -20,7 +20,7 @@ func TestGetFUSDBalance(t *testing.T) { scripts.PrepareFUSDMinter(t, se, client.Account("emulator-account").Address()) - artistAcctName := "emulator-user1" + artistAcctName := user1AccountName artistAcct := client.Account(artistAcctName) assert.Equal(t, 0.0, scripts.GetFUSDBalance(t, se, artistAcct.Address())) @@ -54,7 +54,7 @@ func TestSetUpFUSDAccount(t *testing.T) { scripts.FundAccountWithFlow(t, client, platformAcct.Address(), "10.0") - artistAcctName := "emulator-user1" + artistAcctName := user1AccountName _ = se.NewTransaction("account_setup_fusd"). ProposeAs(artistAcctName). diff --git a/lib/go/iinft/test/marketplace_test.go b/lib/go/iinft/test/marketplace_test.go index e444258..3099013 100644 --- a/lib/go/iinft/test/marketplace_test.go +++ b/lib/go/iinft/test/marketplace_test.go @@ -77,19 +77,19 @@ func TestMarketplace_ListAndBuyWithFlow(t *testing.T) { metadata := buildTestMetadata(1) _ = scripts.CreateSealDigitalArtTx(se, client, metadata, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() _ = client.Transaction(se.GetStandardScript("digitalart_mint_edition")). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). Argument(cadence.Address(sellerAcct.Address())). Test(t). AssertSuccess() - var nftID uint64 = 0 + var nftID uint64 // Assert that the account's collection is correct checkTokenInDigitalArtCollection(t, se, sellerAcct.Address().String(), nftID) @@ -207,19 +207,19 @@ func TestMarketplace_ListAndBuyWithFUSD(t *testing.T) { metadata := buildTestMetadata(1) _ = scripts.CreateSealDigitalArtTx(se, client, metadata, profile). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). Test(t). AssertSuccess() _ = client.Transaction(se.GetStandardScript("digitalart_mint_edition")). - SignProposeAndPayAs(adminAccount). + SignProposeAndPayAs(adminAccountName). StringArgument(metadata.Asset). UInt64Argument(1). Argument(cadence.Address(sellerAcct.Address())). Test(t). AssertSuccess() - var nftID uint64 = 0 + var nftID uint64 // Assert that the account's collection is correct checkTokenInDigitalArtCollection(t, se, sellerAcct.Address().String(), nftID) diff --git a/lib/go/iinft/types.go b/lib/go/iinft/types.go index 11d7ffc..9e8e27d 100644 --- a/lib/go/iinft/types.go +++ b/lib/go/iinft/types.go @@ -122,12 +122,11 @@ func ToFloat64(value cadence.Value) float64 { func UFix64ToString(v float64) string { vStr := strconv.FormatFloat(v, 'f', -1, 64) - if strings.Index(vStr, ".") != -1 { + if strings.Contains(vStr, ".") { return vStr - } else { - return vStr + ".0" } + return vStr + ".0" } func UFix64FromFloat64(v float64) cadence.Value {