How to use Error method of types Package

Best Ginkgo code snippet using types.Error

handler_test.go

Source:handler_test.go Github

copy

Full Screen

...22// When a network actor has not been saved before, it creates one with default params23// and sets the permissions.24func TestHandler_MsgWhitelistPermissions_ActorDoesNotExist(t *testing.T) {25 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")26 require.NoError(t, err)27 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")28 require.NoError(t, err)29 tests := []struct {30 name string31 msg sdk.Msg32 checkWhitelisted bool33 }{34 {35 "Msg Whitelist Permissions",36 &types.MsgWhitelistPermissions{37 Proposer: proposerAddr,38 Address: addr,39 Permission: uint32(types.PermClaimValidator),40 },41 true,42 },43 {44 "Msg Blacklist Permissions",45 &types.MsgBlacklistPermissions{46 Proposer: proposerAddr,47 Address: addr,48 Permission: uint32(types.PermClaimValidator),49 },50 false,51 },52 }53 for _, tt := range tests {54 tt := tt55 t.Run(tt.name, func(t *testing.T) {56 app := simapp.Setup(false)57 ctx := app.NewContext(false, tmproto.Header{})58 err := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermSetPermissions)59 require.NoError(t, err)60 handler := gov.NewHandler(app.CustomGovKeeper)61 _, err = handler(ctx, tt.msg)62 require.NoError(t, err)63 actor, found := app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)64 require.True(t, found)65 if tt.checkWhitelisted {66 require.True(t, actor.Permissions.IsWhitelisted(types.PermClaimValidator))67 } else {68 require.True(t, actor.Permissions.IsBlacklisted(types.PermClaimValidator))69 }70 })71 }72}73// When a network actor has already permissions it just appends the permission.74func TestNewHandler_SetPermissions_ActorWithPerms(t *testing.T) {75 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")76 require.NoError(t, err)77 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")78 require.NoError(t, err)79 tests := []struct {80 name string81 msg sdk.Msg82 checkWhitelisted bool83 }{84 {85 name: "actor with Whitelist Permissions",86 msg: &types.MsgWhitelistPermissions{87 Proposer: proposerAddr,88 Address: addr,89 Permission: uint32(types.PermClaimValidator),90 },91 checkWhitelisted: true,92 },93 {94 name: "actor with Blacklist Permissions",95 msg: &types.MsgBlacklistPermissions{96 Proposer: proposerAddr,97 Address: addr,98 Permission: uint32(types.PermClaimValidator),99 },100 checkWhitelisted: false,101 },102 }103 for _, tt := range tests {104 tt := tt105 t.Run(tt.name, func(t *testing.T) {106 app := simapp.Setup(false)107 ctx := app.NewContext(false, tmproto.Header{})108 err := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermSetPermissions)109 require.NoError(t, err)110 // Add some perms before to the actor.111 actor := types.NewDefaultActor(addr)112 if tt.checkWhitelisted {113 err = actor.Permissions.AddToWhitelist(types.PermSetPermissions)114 } else {115 err = actor.Permissions.AddToBlacklist(types.PermSetPermissions)116 }117 require.NoError(t, err)118 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)119 // Call the handler to add some permissions.120 handler := gov.NewHandler(app.CustomGovKeeper)121 _, err = handler(ctx, tt.msg)122 require.NoError(t, err)123 actor, found := app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)124 require.True(t, found)125 if tt.checkWhitelisted {126 require.True(t, actor.Permissions.IsWhitelisted(types.PermClaimValidator))127 require.True(t, actor.Permissions.IsWhitelisted(types.PermSetPermissions)) // This permission was already set before callid add permission.128 } else {129 require.True(t, actor.Permissions.IsBlacklisted(types.PermClaimValidator))130 require.True(t, actor.Permissions.IsBlacklisted(types.PermSetPermissions)) // This permission was already set before callid add permission.131 }132 })133 }134}135func TestNewHandler_SetPermissionsWithoutSetPermissions(t *testing.T) {136 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")137 require.NoError(t, err)138 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")139 require.NoError(t, err)140 tests := []struct {141 name string142 msg sdk.Msg143 }{144 {145 name: "MsgWhitelist",146 msg: &types.MsgWhitelistPermissions{147 Proposer: proposerAddr,148 Address: addr,149 Permission: uint32(types.PermClaimValidator),150 },151 },152 {153 name: "MsgBlacklist",154 msg: &types.MsgBlacklistPermissions{155 Proposer: proposerAddr,156 Address: addr,157 Permission: uint32(types.PermClaimValidator),158 },159 },160 }161 for _, tt := range tests {162 tt := tt163 t.Run(tt.name, func(t *testing.T) {164 app := simapp.Setup(false)165 ctx := app.NewContext(false, tmproto.Header{})166 handler := gov.NewHandler(app.CustomGovKeeper)167 _, err = handler(ctx, tt.msg)168 require.EqualError(t, err, "PermSetPermissions || (ClaimValidatorPermission && ClaimValidatorPermMsg): not enough permissions")169 })170 }171}172func TestNewHandler_SetPermissions_ProposerHasRoleSudo(t *testing.T) {173 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")174 require.NoError(t, err)175 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")176 require.NoError(t, err)177 tests := []struct {178 name string179 msg sdk.Msg180 checkWhitelist bool181 }{182 {183 name: "MsgWhitelist",184 msg: &types.MsgWhitelistPermissions{185 Proposer: proposerAddr,186 Address: addr,187 Permission: uint32(types.PermClaimValidator),188 },189 checkWhitelist: true,190 },191 {192 name: "MsgBlacklist",193 msg: &types.MsgBlacklistPermissions{194 Proposer: proposerAddr,195 Address: addr,196 Permission: uint32(types.PermClaimValidator),197 },198 checkWhitelist: false,199 },200 }201 for _, tt := range tests {202 tt := tt203 t.Run(tt.name, func(t *testing.T) {204 app := simapp.Setup(false)205 ctx := app.NewContext(false, tmproto.Header{})206 // First we set Role Sudo to proposer Actor207 proposerActor := types.NewDefaultActor(proposerAddr)208 proposerActor.SetRole(types.RoleSudo)209 require.NoError(t, err)210 app.CustomGovKeeper.SaveNetworkActor(ctx, proposerActor)211 handler := gov.NewHandler(app.CustomGovKeeper)212 _, err = handler(ctx, tt.msg)213 require.NoError(t, err)214 actor, found := app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)215 require.True(t, found)216 if tt.checkWhitelist {217 require.True(t, actor.Permissions.IsWhitelisted(types.PermClaimValidator))218 } else {219 require.True(t, actor.Permissions.IsBlacklisted(types.PermClaimValidator))220 }221 })222 }223}224func TestNewHandler_SetNetworkProperties(t *testing.T) {225 changeFeeAddr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")226 require.NoError(t, err)227 sudoAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")228 require.NoError(t, err)229 tests := []struct {230 name string231 msg sdk.Msg232 desiredErr string233 }{234 {235 name: "Success run with ChangeTxFee permission",236 msg: &types.MsgSetNetworkProperties{237 NetworkProperties: &types.NetworkProperties{238 MinTxFee: 100,239 MaxTxFee: 1000,240 },241 Proposer: changeFeeAddr,242 },243 desiredErr: "",244 },245 {246 name: "Failure run without ChangeTxFee permission",247 msg: &types.MsgSetNetworkProperties{248 NetworkProperties: &types.NetworkProperties{249 MinTxFee: 100,250 MaxTxFee: 1000,251 },252 Proposer: sudoAddr,253 },254 desiredErr: "not enough permissions",255 },256 }257 for _, tt := range tests {258 tt := tt259 t.Run(tt.name, func(t *testing.T) {260 app := simapp.Setup(false)261 ctx := app.NewContext(false, tmproto.Header{})262 // First we set Role Sudo to proposer Actor263 proposerActor := types.NewDefaultActor(sudoAddr)264 proposerActor.SetRole(types.RoleSudo)265 require.NoError(t, err)266 app.CustomGovKeeper.SaveNetworkActor(ctx, proposerActor)267 handler := gov.NewHandler(app.CustomGovKeeper)268 // set change fee permission to addr269 _, err = handler(ctx, &types.MsgWhitelistPermissions{270 Proposer: sudoAddr,271 Address: changeFeeAddr,272 Permission: uint32(types.PermChangeTxFee),273 })274 require.NoError(t, err)275 _, err = handler(ctx, tt.msg)276 if tt.desiredErr == "" {277 require.NoError(t, err)278 } else {279 require.Error(t, err)280 require.Contains(t, err.Error(), tt.desiredErr)281 }282 })283 }284}285func TestNewHandler_SetExecutionFee(t *testing.T) {286 execFeeSetAddr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")287 require.NoError(t, err)288 sudoAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")289 require.NoError(t, err)290 tests := []struct {291 name string292 msg types.MsgSetExecutionFee293 desiredErr string294 }{295 {296 name: "Success run with ChangeTxFee permission",297 msg: types.MsgSetExecutionFee{298 Name: "network-properties",299 TransactionType: "network-properties",300 ExecutionFee: 10000,301 FailureFee: 1000,302 Timeout: 1,303 DefaultParameters: 2,304 Proposer: execFeeSetAddr,305 },306 desiredErr: "",307 },308 {309 name: "Success run without ChangeTxFee permission",310 msg: types.MsgSetExecutionFee{311 Name: "network-properties-2",312 TransactionType: "network-properties-2",313 ExecutionFee: 10000,314 FailureFee: 1000,315 Timeout: 1,316 DefaultParameters: 2,317 Proposer: sudoAddr,318 },319 desiredErr: "PermChangeTxFee: not enough permissions",320 },321 }322 for _, tt := range tests {323 tt := tt324 t.Run(tt.name, func(t *testing.T) {325 app := simapp.Setup(false)326 ctx := app.NewContext(false, tmproto.Header{})327 // First we set Role Sudo to proposer Actor328 proposerActor := types.NewDefaultActor(sudoAddr)329 proposerActor.SetRole(types.RoleSudo)330 require.NoError(t, err)331 app.CustomGovKeeper.SaveNetworkActor(ctx, proposerActor)332 handler := gov.NewHandler(app.CustomGovKeeper)333 // set change fee permission to addr334 _, err = handler(ctx, &types.MsgWhitelistPermissions{335 Proposer: sudoAddr,336 Address: execFeeSetAddr,337 Permission: uint32(types.PermChangeTxFee),338 })339 require.NoError(t, err)340 _, err = handler(ctx, &tt.msg)341 if tt.desiredErr == "" {342 require.NoError(t, err)343 execFee := app.CustomGovKeeper.GetExecutionFee(ctx, tt.msg.TransactionType)344 require.Equal(t, tt.msg.Name, execFee.Name)345 require.Equal(t, tt.msg.TransactionType, execFee.TransactionType)346 require.Equal(t, tt.msg.ExecutionFee, execFee.ExecutionFee)347 require.Equal(t, tt.msg.FailureFee, execFee.FailureFee)348 require.Equal(t, tt.msg.Timeout, execFee.Timeout)349 require.Equal(t, tt.msg.DefaultParameters, execFee.DefaultParameters)350 } else {351 require.Error(t, err)352 require.Contains(t, err.Error(), tt.desiredErr)353 }354 })355 }356}357func TestHandler_ClaimCouncilor_Fails(t *testing.T) {358 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")359 require.NoError(t, err)360 tests := []struct {361 name string362 msg sdk.Msg363 expectedErr error364 }{365 {366 name: "not enough permissions",367 msg: &types.MsgClaimCouncilor{368 Moniker: "",369 Address: addr,370 },371 expectedErr: fmt.Errorf("PermClaimCouncilor: not enough permissions"),372 },373 }374 for _, tt := range tests {375 tt := tt376 t.Run(tt.name, func(t *testing.T) {377 app := simapp.Setup(false)378 ctx := app.NewContext(false, tmproto.Header{})379 handler := gov.NewHandler(app.CustomGovKeeper)380 _, err := handler(ctx, tt.msg)381 require.EqualError(t, err, tt.expectedErr.Error())382 })383 }384}385func TestHandler_ClaimCouncilor_HappyPath(t *testing.T) {386 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")387 require.NoError(t, err)388 tests := []struct {389 name string390 msg *types.MsgClaimCouncilor391 }{392 {393 name: "all correct",394 msg: &types.MsgClaimCouncilor{395 Moniker: "TheMoniker",396 Address: addr,397 },398 },399 }400 for _, tt := range tests {401 tt := tt402 t.Run(tt.name, func(t *testing.T) {403 app := simapp.Setup(false)404 ctx := app.NewContext(false, tmproto.Header{})405 err = setPermissionToAddr(t, app, ctx, addr, types.PermClaimCouncilor)406 require.NoError(t, err)407 handler := gov.NewHandler(app.CustomGovKeeper)408 _, err := handler(ctx, tt.msg)409 require.NoError(t, err)410 expectedCouncilor := types.NewCouncilor(411 tt.msg.Moniker,412 tt.msg.Address,413 )414 councilor, found := app.CustomGovKeeper.GetCouncilor(ctx, addr)415 require.True(t, found)416 require.Equal(t, expectedCouncilor, councilor)417 })418 }419}420func TestHandler_WhitelistRolePermissions_Errors(t *testing.T) {421 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")422 require.NoError(t, err)423 tests := []struct {424 name string425 msg *types.MsgWhitelistRolePermission426 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)427 expectedErr error428 }{429 {430 name: "address without SetPermissions perm",431 msg: types.NewMsgWhitelistRolePermission(432 addr,433 uint32(types.RoleValidator),434 uint32(types.PermSetPermissions),435 ),436 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {437 return438 },439 expectedErr: fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),440 },441 {442 name: "role does not exist",443 msg: types.NewMsgWhitelistRolePermission(444 addr,445 10000,446 1,447 ),448 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {449 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)450 require.NoError(t, err2)451 },452 expectedErr: fmt.Errorf("role does not exist"),453 },454 {455 name: "permission is blacklisted",456 msg: types.NewMsgWhitelistRolePermission(457 addr,458 uint32(types.RoleValidator),459 uint32(types.PermSetPermissions),460 ),461 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {462 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)463 require.NoError(t, err2)464 _, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)465 require.True(t, found)466 err2 = app.CustomGovKeeper.BlacklistRolePermission(ctx, types.RoleValidator, types.PermSetPermissions)467 require.NoError(t, err2)468 },469 expectedErr: fmt.Errorf("permission is already blacklisted"),470 },471 }472 for _, tt := range tests {473 tt := tt474 t.Run(tt.name, func(t *testing.T) {475 app := simapp.Setup(false)476 ctx := app.NewContext(false, tmproto.Header{})477 tt.preparePerms(t, app, ctx)478 handler := gov.NewHandler(app.CustomGovKeeper)479 _, err := handler(ctx, tt.msg)480 require.EqualError(t, err, tt.expectedErr.Error())481 })482 }483}484func TestHandler_WhitelistRolePermissions(t *testing.T) {485 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")486 require.NoError(t, err)487 app := simapp.Setup(false)488 ctx := app.NewContext(false, tmproto.Header{})489 err = setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)490 require.NoError(t, err)491 perms, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)492 require.True(t, found)493 require.False(t, perms.IsWhitelisted(types.PermSetPermissions))494 msg := types.NewMsgWhitelistRolePermission(495 addr,496 uint32(types.RoleValidator),497 uint32(types.PermSetPermissions),498 )499 handler := gov.NewHandler(app.CustomGovKeeper)500 _, err = handler(ctx, msg)501 require.NoError(t, err)502 perms, found = app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)503 require.True(t, found)504 require.True(t, perms.IsWhitelisted(types.PermSetPermissions))505}506func TestHandler_BlacklistRolePermissions_Errors(t *testing.T) {507 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")508 require.NoError(t, err)509 tests := []struct {510 name string511 msg *types.MsgBlacklistRolePermission512 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)513 expectedErr error514 }{515 {516 name: "address without SetPermissions perm",517 msg: types.NewMsgBlacklistRolePermission(518 addr,519 uint32(types.RoleValidator),520 uint32(types.PermSetPermissions),521 ),522 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},523 expectedErr: fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),524 },525 {526 name: "role does not exist",527 msg: types.NewMsgBlacklistRolePermission(528 addr,529 10000,530 1,531 ),532 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {533 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)534 require.NoError(t, err2)535 },536 expectedErr: fmt.Errorf("role does not exist"),537 },538 {539 name: "permission is whitelisted",540 msg: types.NewMsgBlacklistRolePermission(541 addr,542 uint32(types.RoleValidator),543 uint32(types.PermSetPermissions),544 ),545 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {546 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)547 require.NoError(t, err2)548 _, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)549 require.True(t, found)550 err2 = app.CustomGovKeeper.WhitelistRolePermission(ctx, types.RoleValidator, types.PermSetPermissions)551 require.NoError(t, err2)552 },553 expectedErr: fmt.Errorf("permission is already whitelisted"),554 },555 }556 for _, tt := range tests {557 tt := tt558 t.Run(tt.name, func(t *testing.T) {559 app := simapp.Setup(false)560 ctx := app.NewContext(false, tmproto.Header{})561 tt.preparePerms(t, app, ctx)562 handler := gov.NewHandler(app.CustomGovKeeper)563 _, err := handler(ctx, tt.msg)564 require.EqualError(t, err, tt.expectedErr.Error())565 })566 }567}568func TestHandler_BlacklistRolePermissions(t *testing.T) {569 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")570 require.NoError(t, err)571 app := simapp.Setup(false)572 ctx := app.NewContext(false, tmproto.Header{})573 err = setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)574 require.NoError(t, err)575 perms, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)576 require.True(t, found)577 require.False(t, perms.IsBlacklisted(types.PermSetPermissions))578 msg := types.NewMsgBlacklistRolePermission(579 addr,580 uint32(types.RoleValidator),581 uint32(types.PermSetPermissions),582 )583 handler := gov.NewHandler(app.CustomGovKeeper)584 _, err = handler(ctx, msg)585 require.NoError(t, err)586 perms, found = app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)587 require.True(t, found)588 require.True(t, perms.IsBlacklisted(types.PermSetPermissions))589}590func TestHandler_RemoveWhitelistRolePermissions_Errors(t *testing.T) {591 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")592 require.NoError(t, err)593 tests := []struct {594 name string595 msg *types.MsgRemoveWhitelistRolePermission596 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)597 expectedErr error598 }{599 {600 name: "address without SetPermissions perm",601 msg: types.NewMsgRemoveWhitelistRolePermission(602 addr,603 uint32(types.RoleValidator),604 uint32(types.PermSetPermissions),605 ),606 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},607 expectedErr: fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),608 },609 {610 name: "role does not exist",611 msg: types.NewMsgRemoveWhitelistRolePermission(612 addr,613 10000,614 1,615 ),616 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {617 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)618 require.NoError(t, err2)619 },620 expectedErr: fmt.Errorf("role does not exist"),621 },622 }623 for _, tt := range tests {624 tt := tt625 t.Run(tt.name, func(t *testing.T) {626 app := simapp.Setup(false)627 ctx := app.NewContext(false, tmproto.Header{})628 tt.preparePerms(t, app, ctx)629 handler := gov.NewHandler(app.CustomGovKeeper)630 _, err := handler(ctx, tt.msg)631 require.EqualError(t, err, tt.expectedErr.Error())632 })633 }634}635func TestHandler_RemoveWhitelistRolePermissions(t *testing.T) {636 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")637 require.NoError(t, err)638 app := simapp.Setup(false)639 ctx := app.NewContext(false, tmproto.Header{})640 err = setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)641 require.NoError(t, err)642 perms, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)643 require.True(t, found)644 require.True(t, perms.IsWhitelisted(types.PermClaimValidator))645 msg := types.NewMsgRemoveWhitelistRolePermission(646 addr,647 uint32(types.RoleValidator),648 uint32(types.PermClaimValidator),649 )650 handler := gov.NewHandler(app.CustomGovKeeper)651 _, err = handler(ctx, msg)652 require.NoError(t, err)653 perms, found = app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)654 require.True(t, found)655 require.False(t, perms.IsWhitelisted(types.PermClaimValidator))656}657func TestHandler_RemoveBlacklistRolePermissions_Errors(t *testing.T) {658 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")659 require.NoError(t, err)660 tests := []struct {661 name string662 msg *types.MsgRemoveBlacklistRolePermission663 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)664 expectedErr error665 }{666 {667 name: "address without SetPermissions perm",668 msg: types.NewMsgRemoveBlacklistRolePermission(669 addr,670 uint32(types.RoleValidator),671 uint32(types.PermSetPermissions),672 ),673 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},674 expectedErr: fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),675 },676 {677 name: "role does not exist",678 msg: types.NewMsgRemoveBlacklistRolePermission(679 addr,680 10000,681 1,682 ),683 preparePerms: func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {684 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)685 require.NoError(t, err2)686 },687 expectedErr: fmt.Errorf("role does not exist"),688 },689 }690 for _, tt := range tests {691 tt := tt692 t.Run(tt.name, func(t *testing.T) {693 app := simapp.Setup(false)694 ctx := app.NewContext(false, tmproto.Header{})695 tt.preparePerms(t, app, ctx)696 handler := gov.NewHandler(app.CustomGovKeeper)697 _, err := handler(ctx, tt.msg)698 require.EqualError(t, err, tt.expectedErr.Error())699 })700 }701}702func TestHandler_RemoveBlacklistRolePermissions(t *testing.T) {703 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")704 require.NoError(t, err)705 app := simapp.Setup(false)706 ctx := app.NewContext(false, tmproto.Header{})707 err = setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)708 require.NoError(t, err)709 _, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)710 require.True(t, found)711 // Set some blacklist value712 err = app.CustomGovKeeper.BlacklistRolePermission(ctx, types.RoleValidator, types.PermClaimCouncilor)713 require.NoError(t, err)714 // Check if it is blacklisted.715 perms, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)716 require.True(t, found)717 require.True(t, perms.IsBlacklisted(types.PermClaimCouncilor))718 msg := types.NewMsgRemoveBlacklistRolePermission(719 addr,720 uint32(types.RoleValidator),721 uint32(types.PermClaimCouncilor),722 )723 handler := gov.NewHandler(app.CustomGovKeeper)724 _, err = handler(ctx, msg)725 require.NoError(t, err)726 perms, found = app.CustomGovKeeper.GetPermissionsForRole(ctx, types.RoleValidator)727 require.True(t, found)728 require.False(t, perms.IsBlacklisted(types.PermClaimCouncilor))729}730func TestHandler_CreateRole_Errors(t *testing.T) {731 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")732 require.NoError(t, err)733 tests := []struct {734 name string735 msg *types.MsgCreateRole736 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)737 expectedErr error738 }{739 {740 "fails when no perms",741 types.NewMsgCreateRole(742 addr,743 10,744 ),745 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},746 fmt.Errorf("PermUpsertRole: not enough permissions"),747 },748 {749 "fails when role already exists",750 types.NewMsgCreateRole(751 addr,752 1234,753 ),754 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {755 err2 := setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)756 require.NoError(t, err2)757 app.CustomGovKeeper.CreateRole(ctx, types.Role(1234))758 },759 fmt.Errorf("role already exist"),760 },761 }762 for _, tt := range tests {763 app := simapp.Setup(false)764 ctx := app.NewContext(false, tmproto.Header{})765 tt.preparePerms(t, app, ctx)766 handler := gov.NewHandler(app.CustomGovKeeper)767 _, err := handler(ctx, tt.msg)768 require.EqualError(t, err, tt.expectedErr.Error())769 }770}771func TestHandler_CreateRole(t *testing.T) {772 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")773 require.NoError(t, err)774 app := simapp.Setup(false)775 ctx := app.NewContext(false, tmproto.Header{})776 err = setPermissionToAddr(t, app, ctx, addr, types.PermUpsertRole)777 require.NoError(t, err)778 _, found := app.CustomGovKeeper.GetPermissionsForRole(ctx, 1234)779 require.False(t, found)780 handler := gov.NewHandler(app.CustomGovKeeper)781 _, err = handler(ctx, types.NewMsgCreateRole(782 addr,783 1234,784 ))785 require.NoError(t, err)786 _, found = app.CustomGovKeeper.GetPermissionsForRole(ctx, 1234)787 require.True(t, found)788}789func TestHandler_AssignRole_Errors(t *testing.T) {790 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")791 require.NoError(t, err)792 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")793 require.NoError(t, err)794 tests := []struct {795 name string796 msg *types.MsgAssignRole797 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)798 expectedErr error799 }{800 {801 "fails when no perms",802 types.NewMsgAssignRole(803 proposerAddr, addr, 3,804 ),805 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},806 fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),807 },808 {809 "fails when role does not exist",810 types.NewMsgAssignRole(811 proposerAddr, addr, 3,812 ),813 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {814 err2 := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)815 require.NoError(t, err2)816 },817 types.ErrRoleDoesNotExist,818 },819 {820 "role already assigned",821 types.NewMsgAssignRole(822 proposerAddr, addr, 3,823 ),824 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {825 err2 := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)826 require.NoError(t, err2)827 app.CustomGovKeeper.CreateRole(ctx, types.Role(3))828 err2 = app.CustomGovKeeper.WhitelistRolePermission(ctx, types.Role(3), types.PermClaimValidator)829 require.NoError(t, err2)830 networkActor := types.NewDefaultActor(addr)831 app.CustomGovKeeper.AssignRoleToActor(ctx, networkActor, types.Role(3))832 },833 types.ErrRoleAlreadyAssigned,834 },835 }836 for _, tt := range tests {837 app := simapp.Setup(false)838 ctx := app.NewContext(false, tmproto.Header{})839 tt.preparePerms(t, app, ctx)840 handler := gov.NewHandler(app.CustomGovKeeper)841 _, err := handler(ctx, tt.msg)842 require.EqualError(t, err, tt.expectedErr.Error())843 }844}845func TestHandler_AssignRole(t *testing.T) {846 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")847 require.NoError(t, err)848 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")849 require.NoError(t, err)850 app := simapp.Setup(false)851 ctx := app.NewContext(false, tmproto.Header{})852 // Set permissions to proposer.853 err = setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)854 require.NoError(t, err)855 // Create role856 app.CustomGovKeeper.CreateRole(ctx, types.Role(3))857 err = app.CustomGovKeeper.WhitelistRolePermission(ctx, types.Role(3), types.PermSetPermissions)858 require.NoError(t, err)859 msg := types.NewMsgAssignRole(proposerAddr, addr, 3)860 handler := gov.NewHandler(app.CustomGovKeeper)861 _, err = handler(ctx, msg)862 require.NoError(t, err)863 actor, found := app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)864 require.True(t, found)865 require.True(t, actor.HasRole(types.Role(3)))866}867func TestHandler_RemoveRole_Errors(t *testing.T) {868 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")869 require.NoError(t, err)870 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")871 require.NoError(t, err)872 tests := []struct {873 name string874 msg *types.MsgRemoveRole875 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)876 expectedErr error877 }{878 {879 "fails when no perms",880 types.NewMsgRemoveRole(881 proposerAddr, addr, 3,882 ),883 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},884 fmt.Errorf("%s: not enough permissions", types.PermUpsertRole.String()),885 },886 {887 "fails when role does not exist",888 types.NewMsgRemoveRole(889 proposerAddr, addr, 3,890 ),891 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {892 err2 := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)893 require.NoError(t, err2)894 },895 types.ErrRoleDoesNotExist,896 },897 {898 "role not assigned",899 types.NewMsgRemoveRole(900 proposerAddr, addr, 3,901 ),902 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {903 err2 := setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)904 require.NoError(t, err2)905 app.CustomGovKeeper.CreateRole(ctx, types.Role(3))906 err2 = app.CustomGovKeeper.WhitelistRolePermission(ctx, types.Role(3), types.PermClaimValidator)907 require.NoError(t, err2)908 networkActor := types.NewDefaultActor(addr)909 app.CustomGovKeeper.SaveNetworkActor(ctx, networkActor)910 },911 types.ErrRoleNotAssigned,912 },913 }914 for _, tt := range tests {915 app := simapp.Setup(false)916 ctx := app.NewContext(false, tmproto.Header{})917 tt.preparePerms(t, app, ctx)918 handler := gov.NewHandler(app.CustomGovKeeper)919 _, err := handler(ctx, tt.msg)920 require.EqualError(t, err, tt.expectedErr.Error())921 }922}923func TestHandler_RemoveRoles(t *testing.T) {924 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")925 require.NoError(t, err)926 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")927 require.NoError(t, err)928 app := simapp.Setup(false)929 ctx := app.NewContext(false, tmproto.Header{})930 // Set permissions to proposer.931 err = setPermissionToAddr(t, app, ctx, proposerAddr, types.PermUpsertRole)932 require.NoError(t, err)933 // Set new role and set permission to actor.934 app.CustomGovKeeper.CreateRole(ctx, types.Role(3))935 err = app.CustomGovKeeper.WhitelistRolePermission(ctx, types.Role(3), types.PermSetPermissions)936 require.NoError(t, err)937 actor := types.NewDefaultActor(addr)938 app.CustomGovKeeper.AssignRoleToActor(ctx, actor, types.Role(3))939 actor, found := app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)940 require.True(t, found)941 require.True(t, actor.HasRole(3))942 msg := types.NewMsgRemoveRole(proposerAddr, addr, 3)943 handler := gov.NewHandler(app.CustomGovKeeper)944 _, err = handler(ctx, msg)945 require.NoError(t, err)946 actor, found = app.CustomGovKeeper.GetNetworkActorByAddress(ctx, addr)947 require.True(t, found)948 require.False(t, actor.HasRole(3))949}950func TestHandler_CreateProposalAssignPermission_Errors(t *testing.T) {951 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")952 require.NoError(t, err)953 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")954 require.NoError(t, err)955 tests := []struct {956 name string957 content types.Content958 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)959 expectedErr error960 }{961 {962 "Proposer does not have Perm",963 types.NewAssignPermissionProposal(964 addr, types.PermClaimValidator,965 ),966 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},967 errors.Wrap(types.ErrNotEnoughPermissions, "PERMISSION_CREATE_SET_PERMISSIONS_PROPOSAL"),968 },969 {970 "address already has that permission",971 types.NewAssignPermissionProposal(972 addr, types.PermClaimValidator,973 ),974 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {975 proposerActor := types.NewDefaultActor(proposerAddr)976 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, types.PermCreateSetPermissionsProposal)977 require.NoError(t, err2)978 actor := types.NewDefaultActor(addr)979 err2 = app.CustomGovKeeper.AddWhitelistPermission(ctx, actor, types.PermClaimValidator)980 require.NoError(t, err2)981 },982 fmt.Errorf("permission already whitelisted: error adding to whitelist"),983 },984 }985 for _, tt := range tests {986 tt := tt987 t.Run(tt.name, func(t *testing.T) {988 app := simapp.Setup(false)989 ctx := app.NewContext(false, tmproto.Header{})990 tt.preparePerms(t, app, ctx)991 handler := gov.NewHandler(app.CustomGovKeeper)992 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", tt.content)993 require.NoError(t, err)994 _, err = handler(ctx, msg)995 require.EqualError(t, err, tt.expectedErr.Error())996 })997 }998}999func TestHandler_ProposalAssignPermission(t *testing.T) {1000 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1001 require.NoError(t, err)1002 addr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")1003 require.NoError(t, err)1004 app := simapp.Setup(false)1005 ctx := app.NewContext(false, tmproto.Header{1006 Time: time.Now(),1007 })1008 // Set proposer Permissions1009 proposerActor := types.NewDefaultActor(proposerAddr)1010 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, types.PermCreateSetPermissionsProposal)1011 require.NoError(t, err2)1012 properties := app.CustomGovKeeper.GetNetworkProperties(ctx)1013 properties.ProposalEndTime = 600 // Seconds, 10 mints1014 app.CustomGovKeeper.SetNetworkProperties(ctx, properties)1015 handler := gov.NewHandler(app.CustomGovKeeper)1016 proposal := types.NewAssignPermissionProposal(addr, types.PermValue(1))1017 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", proposal)1018 require.NoError(t, err)1019 res, err := handler(1020 ctx,1021 msg,1022 )1023 require.NoError(t, err)1024 expData, _ := proto.Marshal(&types.MsgSubmitProposalResponse{ProposalID: 1})1025 require.Equal(t, expData, res.Data)1026 savedProposal, found := app.CustomGovKeeper.GetProposal(ctx, 1)1027 require.True(t, found)1028 expectedSavedProposal, err := types.NewProposal(1029 1,1030 "title",1031 "some desc",1032 types.NewAssignPermissionProposal(1033 addr,1034 types.PermValue(1),1035 ),1036 ctx.BlockTime(),1037 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEndTime)),1038 ctx.BlockTime().Add((time.Second*time.Duration(properties.ProposalEndTime))+(time.Second*time.Duration(properties.ProposalEnactmentTime))),1039 ctx.BlockHeight()+2,1040 ctx.BlockHeight()+3,1041 )1042 require.NoError(t, err)1043 require.Equal(t, expectedSavedProposal, savedProposal)1044 // Next proposal ID is increased.1045 id := app.CustomGovKeeper.GetNextProposalID(ctx)1046 require.Equal(t, uint64(2), id)1047 // Is not on finished active proposals.1048 iterator := app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1049 require.False(t, iterator.Valid())1050 ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute * 10))1051 iterator = app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1052 require.True(t, iterator.Valid())1053}1054func TestHandler_CreateProposalUpsertDataRegistry_Errors(t *testing.T) {1055 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1056 require.NoError(t, err)1057 tests := []struct {1058 name string1059 content types.Content1060 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)1061 expectedErr error1062 }{1063 {1064 "Proposer does not have Perm",1065 types.NewUpsertDataRegistryProposal(1066 "theKey",1067 "theHash",1068 "theReference",1069 "theEncoding",1070 1234,1071 ),1072 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},1073 errors.Wrap(types.ErrNotEnoughPermissions, types.PermCreateUpsertDataRegistryProposal.String()),1074 },1075 }1076 for _, tt := range tests {1077 tt := tt1078 t.Run(tt.name, func(t *testing.T) {1079 app := simapp.Setup(false)1080 ctx := app.NewContext(false, tmproto.Header{})1081 tt.preparePerms(t, app, ctx)1082 handler := gov.NewHandler(app.CustomGovKeeper)1083 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", tt.content)1084 require.NoError(t, err)1085 _, err = handler(ctx, msg)1086 require.EqualError(t, err, tt.expectedErr.Error())1087 })1088 }1089}1090func TestHandler_ProposalUpsertDataRegistry(t *testing.T) {1091 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1092 require.NoError(t, err)1093 app := simapp.Setup(false)1094 ctx := app.NewContext(false, tmproto.Header{1095 Time: time.Now(),1096 })1097 // Set proposer Permissions1098 proposerActor := types.NewDefaultActor(proposerAddr)1099 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, types.PermCreateUpsertDataRegistryProposal)1100 require.NoError(t, err2)1101 properties := app.CustomGovKeeper.GetNetworkProperties(ctx)1102 properties.ProposalEndTime = 101103 app.CustomGovKeeper.SetNetworkProperties(ctx, properties)1104 handler := gov.NewHandler(app.CustomGovKeeper)1105 proposal := types.NewUpsertDataRegistryProposal(1106 "theKey",1107 "theHash",1108 "theReference",1109 "theEncoding",1110 1234,1111 )1112 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", proposal)1113 require.NoError(t, err)1114 res, err := handler(1115 ctx, msg,1116 )1117 require.NoError(t, err)1118 expData, _ := proto.Marshal(&types.MsgSubmitProposalResponse{ProposalID: 1})1119 require.Equal(t, expData, res.Data)1120 savedProposal, found := app.CustomGovKeeper.GetProposal(ctx, 1)1121 require.True(t, found)1122 expectedSavedProposal, err := types.NewProposal(1123 1,1124 "title",1125 "some desc",1126 types.NewUpsertDataRegistryProposal(1127 "theKey",1128 "theHash",1129 "theReference",1130 "theEncoding",1131 1234,1132 ),1133 ctx.BlockTime(),1134 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEndTime)),1135 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEnactmentTime)+time.Second*time.Duration(properties.ProposalEndTime)),1136 ctx.BlockHeight()+2,1137 ctx.BlockHeight()+3,1138 )1139 require.NoError(t, err)1140 require.Equal(t, expectedSavedProposal, savedProposal)1141 // Next proposal ID is increased.1142 id := app.CustomGovKeeper.GetNextProposalID(ctx)1143 require.Equal(t, uint64(2), id)1144 // Is not on finished active proposals.1145 iterator := app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1146 require.False(t, iterator.Valid())1147 ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute * 10))1148 iterator = app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1149 require.True(t, iterator.Valid())1150}1151func TestHandler_VoteProposal_Errors(t *testing.T) {1152 voterAddr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")1153 require.NoError(t, err)1154 tests := []struct {1155 name string1156 msg *types.MsgVoteProposal1157 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)1158 expectedErr error1159 }{1160 {1161 "voting time has finished",1162 types.NewMsgVoteProposal(1163 1, voterAddr, types.OptionAbstain,1164 ),1165 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1166 actor := types.NewNetworkActor(1167 voterAddr,1168 types.Roles{},1169 types.Active,1170 []types.VoteOption{},1171 types.NewPermissions(nil, nil),1172 1,1173 )1174 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1175 err = app.CustomGovKeeper.AddWhitelistPermission(ctx, actor, types.PermVoteSetPermissionProposal)1176 require.NoError(t, err)1177 // Create proposal1178 proposal, err := types.NewProposal(1179 1,1180 "title",1181 "some desc",1182 types.NewAssignPermissionProposal(1183 voterAddr,1184 types.PermClaimCouncilor,1185 ),1186 ctx.BlockTime(),1187 ctx.BlockTime().Add(time.Second*9),1188 ctx.BlockTime().Add(time.Second*20),1189 ctx.BlockHeight()+2,1190 ctx.BlockHeight()+3,1191 )1192 require.NoError(t, err)1193 app.CustomGovKeeper.SaveProposal(ctx, proposal)1194 },1195 types.ErrVotingTimeEnded,1196 },1197 {1198 "Voter does not have permission to vote this proposal: Assign Permission",1199 types.NewMsgVoteProposal(1200 1, voterAddr, types.OptionAbstain,1201 ),1202 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1203 actor := types.NewNetworkActor(1204 voterAddr,1205 types.Roles{},1206 types.Active,1207 []types.VoteOption{},1208 types.NewPermissions(nil, nil),1209 1,1210 )1211 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1212 // Create proposal1213 proposal, err := types.NewProposal(1214 1,1215 "title",1216 "some desc",1217 types.NewAssignPermissionProposal(1218 voterAddr,1219 types.PermClaimCouncilor,1220 ),1221 ctx.BlockTime(),1222 ctx.BlockTime().Add(time.Second*20),1223 ctx.BlockTime().Add(time.Second*30),1224 ctx.BlockHeight()+2,1225 ctx.BlockHeight()+3,1226 )1227 require.NoError(t, err)1228 app.CustomGovKeeper.SaveProposal(ctx, proposal)1229 },1230 fmt.Errorf("%s: not enough permissions", types.PermVoteSetPermissionProposal.String()),1231 },1232 {1233 "Voter does not have permission to vote this proposal: Change Data Registry",1234 types.NewMsgVoteProposal(1235 1, voterAddr, types.OptionAbstain,1236 ),1237 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1238 actor := types.NewNetworkActor(1239 voterAddr,1240 types.Roles{},1241 types.Active,1242 []types.VoteOption{},1243 types.NewPermissions(nil, nil),1244 1,1245 )1246 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1247 // Create proposal1248 proposal, err := types.NewProposal(1249 1,1250 "title",1251 "some desc",1252 types.NewUpsertDataRegistryProposal(1253 "theKey",1254 "theHash",1255 "theReference",1256 "theEncoding",1257 1234,1258 ),1259 ctx.BlockTime(),1260 ctx.BlockTime().Add(time.Second*20),1261 ctx.BlockTime().Add(time.Second*30),1262 ctx.BlockHeight()+2,1263 ctx.BlockHeight()+3,1264 )1265 require.NoError(t, err)1266 app.CustomGovKeeper.SaveProposal(ctx, proposal)1267 },1268 fmt.Errorf("%s: not enough permissions", types.PermVoteUpsertDataRegistryProposal.String()),1269 },1270 {1271 "Proposal does not exist",1272 types.NewMsgVoteProposal(1273 1, voterAddr, types.OptionAbstain,1274 ),1275 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1276 actor := types.NewNetworkActor(1277 voterAddr,1278 types.Roles{},1279 types.Active,1280 []types.VoteOption{},1281 types.NewPermissions(nil, nil),1282 1,1283 )1284 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1285 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, actor, types.PermVoteSetPermissionProposal)1286 require.NoError(t, err2)1287 },1288 types.ErrProposalDoesNotExist,1289 },1290 {1291 "Voter is not active",1292 types.NewMsgVoteProposal(1293 1, voterAddr, types.OptionAbstain,1294 ),1295 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1296 actor := types.NewDefaultActor(voterAddr)1297 actor.Deactivate()1298 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1299 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, actor, types.PermVoteSetPermissionProposal)1300 require.NoError(t, err2)1301 },1302 types.ErrActorIsNotActive,1303 },1304 {1305 "Voter does not have permission to vote this proposal: Change Network Property",1306 types.NewMsgVoteProposal(1307 1, voterAddr, types.OptionAbstain,1308 ),1309 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1310 actor := types.NewNetworkActor(1311 voterAddr,1312 types.Roles{},1313 types.Active,1314 []types.VoteOption{},1315 types.NewPermissions(nil, nil),1316 1,1317 )1318 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1319 // Create proposal1320 proposal, err := types.NewProposal(1321 1,1322 "title",1323 "some desc",1324 types.NewSetNetworkPropertyProposal(1325 types.MinTxFee,1326 types.NetworkPropertyValue{Value: 1234},1327 ),1328 ctx.BlockTime(),1329 ctx.BlockTime().Add(time.Second*20),1330 ctx.BlockTime().Add(time.Second*30),1331 ctx.BlockHeight()+2,1332 ctx.BlockHeight()+3,1333 )1334 require.NoError(t, err)1335 app.CustomGovKeeper.SaveProposal(ctx, proposal)1336 },1337 fmt.Errorf("%s: not enough permissions", types.PermVoteSetNetworkPropertyProposal.String()),1338 },1339 {1340 "Voter does not have permission to vote this proposal: UpsertTokenAlias",1341 types.NewMsgVoteProposal(1342 1, voterAddr, types.OptionAbstain,1343 ),1344 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1345 actor := types.NewNetworkActor(1346 voterAddr,1347 types.Roles{},1348 types.Active,1349 []types.VoteOption{},1350 types.NewPermissions(nil, nil),1351 1,1352 )1353 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1354 // Create proposal1355 proposal, err := types.NewProposal(1356 1,1357 "title",1358 "some desc",1359 tokenstypes.NewUpsertTokenAliasProposal(1360 "eur",1361 "Euro",1362 "theIcon",1363 12,1364 []string{},1365 ),1366 ctx.BlockTime(),1367 ctx.BlockTime().Add(time.Second*20),1368 ctx.BlockTime().Add(time.Second*30),1369 ctx.BlockHeight()+2,1370 ctx.BlockHeight()+3,1371 )1372 require.NoError(t, err)1373 app.CustomGovKeeper.SaveProposal(ctx, proposal)1374 },1375 fmt.Errorf("%s: not enough permissions", types.PermVoteUpsertTokenAliasProposal.String()),1376 },1377 }1378 for _, tt := range tests {1379 tt := tt1380 t.Run(tt.name, func(t *testing.T) {1381 app := simapp.Setup(false)1382 ctx := app.NewContext(false, tmproto.Header{}).WithBlockTime(time.Now())1383 tt.preparePerms(t, app, ctx)1384 // Add some BlockTime.1385 ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Second * 10))1386 handler := gov.NewHandler(app.CustomGovKeeper)1387 _, err := handler(ctx, tt.msg)1388 require.EqualError(t, err, tt.expectedErr.Error())1389 })1390 }1391}1392func TestHandler_VoteProposal(t *testing.T) {1393 voterAddr, err := sdk.AccAddressFromBech32("kira15ky9du8a2wlstz6fpx3p4mqpjyrm5cgqzp4f3d")1394 require.NoError(t, err)1395 app := simapp.Setup(false)1396 ctx := app.NewContext(false, tmproto.Header{})1397 // Create Voter as active actor.1398 actor := types.NewNetworkActor(1399 voterAddr,1400 types.Roles{},1401 types.Active,1402 []types.VoteOption{},1403 types.NewPermissions(nil, nil),1404 1,1405 )1406 app.CustomGovKeeper.SaveNetworkActor(ctx, actor)1407 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, actor, types.PermVoteSetPermissionProposal)1408 require.NoError(t, err2)1409 // Create proposal1410 proposal, err := types.NewProposal(1411 1,1412 "title",1413 "some desc",1414 types.NewAssignPermissionProposal(1415 voterAddr,1416 types.PermClaimCouncilor,1417 ),1418 ctx.BlockTime(),1419 ctx.BlockTime().Add(time.Second*1),1420 ctx.BlockTime().Add(time.Second*10),1421 ctx.BlockHeight()+2,1422 ctx.BlockHeight()+3,1423 )1424 require.NoError(t, err)1425 app.CustomGovKeeper.SaveProposal(ctx, proposal)1426 msg := types.NewMsgVoteProposal(proposal.ProposalId, voterAddr, types.OptionAbstain)1427 handler := gov.NewHandler(app.CustomGovKeeper)1428 _, err = handler(ctx, msg)1429 require.NoError(t, err)1430 vote, found := app.CustomGovKeeper.GetVote(ctx, proposal.ProposalId, voterAddr)1431 require.True(t, found)1432 require.Equal(t, types.NewVote(proposal.ProposalId, voterAddr, types.OptionAbstain), vote)1433}1434func setPermissionToAddr(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context, addr sdk.AccAddress, perm types.PermValue) error {1435 proposerActor := types.NewDefaultActor(addr)1436 err := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, perm)1437 require.NoError(t, err)1438 return nil1439}1440func TestHandler_CreateProposalSetNetworkProperty_Errors(t *testing.T) {1441 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1442 require.NoError(t, err)1443 tests := []struct {1444 name string1445 content types.Content1446 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)1447 expectedErr error1448 }{1449 {1450 "Proposer does not have Perm",1451 types.NewSetNetworkPropertyProposal(1452 types.MaxTxFee,1453 types.NetworkPropertyValue{Value: 100000},1454 ),1455 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},1456 errors.Wrap(types.ErrNotEnoughPermissions, types.PermCreateSetNetworkPropertyProposal.String()),1457 },1458 }1459 for _, tt := range tests {1460 tt := tt1461 t.Run(tt.name, func(t *testing.T) {1462 app := simapp.Setup(false)1463 ctx := app.NewContext(false, tmproto.Header{})1464 tt.preparePerms(t, app, ctx)1465 handler := gov.NewHandler(app.CustomGovKeeper)1466 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", tt.content)1467 require.NoError(t, err)1468 _, err = handler(ctx, msg)1469 require.EqualError(t, err, tt.expectedErr.Error())1470 })1471 }1472}1473func TestHandler_ProposalSetNetworkProperty(t *testing.T) {1474 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1475 require.NoError(t, err)1476 app := simapp.Setup(false)1477 ctx := app.NewContext(false, tmproto.Header{1478 Time: time.Now(),1479 })1480 // Set proposer Permissions1481 proposerActor := types.NewDefaultActor(proposerAddr)1482 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, types.PermCreateSetNetworkPropertyProposal)1483 require.NoError(t, err2)1484 properties := app.CustomGovKeeper.GetNetworkProperties(ctx)1485 properties.ProposalEndTime = 101486 app.CustomGovKeeper.SetNetworkProperties(ctx, properties)1487 handler := gov.NewHandler(app.CustomGovKeeper)1488 proposal := types.NewSetNetworkPropertyProposal(1489 types.MinTxFee,1490 types.NetworkPropertyValue{Value: 1234},1491 )1492 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", proposal)1493 require.NoError(t, err)1494 res, err := handler(1495 ctx,1496 msg,1497 )1498 require.NoError(t, err)1499 expData, _ := proto.Marshal(&types.MsgSubmitProposalResponse{ProposalID: 1})1500 require.Equal(t, expData, res.Data)1501 savedProposal, found := app.CustomGovKeeper.GetProposal(ctx, 1)1502 require.True(t, found)1503 expectedSavedProposal, err := types.NewProposal(1504 1,1505 "title",1506 "some desc",1507 types.NewSetNetworkPropertyProposal(1508 types.MinTxFee,1509 types.NetworkPropertyValue{Value: 1234},1510 ),1511 ctx.BlockTime(),1512 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEndTime)),1513 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEnactmentTime)+time.Second*time.Duration(properties.ProposalEndTime)),1514 ctx.BlockHeight()+2,1515 ctx.BlockHeight()+3,1516 )1517 require.NoError(t, err)1518 require.Equal(t, expectedSavedProposal, savedProposal)1519 // Next proposal ID is increased.1520 id := app.CustomGovKeeper.GetNextProposalID(ctx)1521 require.Equal(t, uint64(2), id)1522 // Is not on finished active proposals.1523 iterator := app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1524 require.False(t, iterator.Valid())1525 ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute * 10))1526 iterator = app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1527 require.True(t, iterator.Valid())1528}1529func TestHandler_CreateProposalCreateRole_Errors(t *testing.T) {1530 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1531 require.NoError(t, err)1532 tests := []struct {1533 name string1534 content types.Content1535 preparePerms func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context)1536 expectedErr error1537 }{1538 {1539 "Proposer does not have Perm",1540 types.NewCreateRoleProposal(1541 types.Role(1),1542 []types.PermValue{},1543 []types.PermValue{types.PermClaimValidator},1544 ),1545 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {},1546 errors.Wrap(types.ErrNotEnoughPermissions, types.PermCreateRoleProposal.String()),1547 },1548 {1549 "role already exist",1550 types.NewCreateRoleProposal(1551 types.Role(1),1552 []types.PermValue{types.PermClaimCouncilor},1553 []types.PermValue{},1554 ),1555 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1556 proposerActor := types.NewDefaultActor(proposerAddr)1557 err := app.CustomGovKeeper.AddWhitelistPermission(1558 ctx,1559 proposerActor,1560 types.PermCreateRoleProposal,1561 )1562 require.NoError(t, err)1563 app.CustomGovKeeper.CreateRole(ctx, types.Role(1))1564 },1565 types.ErrRoleExist,1566 },1567 {1568 "permissions are empty",1569 types.NewCreateRoleProposal(1570 types.Role(1000),1571 []types.PermValue{},1572 []types.PermValue{},1573 ),1574 func(t *testing.T, app *simapp.SekaiApp, ctx sdk.Context) {1575 proposerActor := types.NewDefaultActor(proposerAddr)1576 err := app.CustomGovKeeper.AddWhitelistPermission(1577 ctx,1578 proposerActor,1579 types.PermCreateRoleProposal,1580 )1581 require.NoError(t, err)1582 },1583 types.ErrEmptyPermissions,1584 },1585 }1586 for _, tt := range tests {1587 tt := tt1588 t.Run(tt.name, func(t *testing.T) {1589 app := simapp.Setup(false)1590 ctx := app.NewContext(false, tmproto.Header{})1591 tt.preparePerms(t, app, ctx)1592 handler := gov.NewHandler(app.CustomGovKeeper)1593 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", tt.content)1594 require.NoError(t, err)1595 _, err = handler(ctx, msg)1596 require.EqualError(t, err, tt.expectedErr.Error())1597 })1598 }1599}1600func TestHandler_ProposalCreateRole(t *testing.T) {1601 proposerAddr, err := sdk.AccAddressFromBech32("kira1alzyfq40zjsveat87jlg8jxetwqmr0a29sgd0f")1602 require.NoError(t, err)1603 app := simapp.Setup(false)1604 ctx := app.NewContext(false, tmproto.Header{1605 Time: time.Now(),1606 })1607 // Set proposer Permissions1608 proposerActor := types.NewDefaultActor(proposerAddr)1609 err2 := app.CustomGovKeeper.AddWhitelistPermission(ctx, proposerActor, types.PermCreateRoleProposal)1610 require.NoError(t, err2)1611 properties := app.CustomGovKeeper.GetNetworkProperties(ctx)1612 properties.ProposalEndTime = 101613 app.CustomGovKeeper.SetNetworkProperties(ctx, properties)1614 handler := gov.NewHandler(app.CustomGovKeeper)1615 proposal := types.NewCreateRoleProposal(1616 types.Role(1000),1617 []types.PermValue{1618 types.PermClaimValidator,1619 },1620 []types.PermValue{1621 types.PermChangeTxFee,1622 },1623 )1624 msg, err := types.NewMsgSubmitProposal(proposerAddr, "title", "some desc", proposal)1625 require.NoError(t, err)1626 res, err := handler(1627 ctx,1628 msg,1629 )1630 require.NoError(t, err)1631 expData, _ := proto.Marshal(&types.MsgSubmitProposalResponse{ProposalID: 1})1632 require.Equal(t, expData, res.Data)1633 savedProposal, found := app.CustomGovKeeper.GetProposal(ctx, 1)1634 require.True(t, found)1635 expectedSavedProposal, err := types.NewProposal(1636 1,1637 "title",1638 "some desc",1639 types.NewCreateRoleProposal(1640 types.Role(1000),1641 []types.PermValue{1642 types.PermClaimValidator,1643 },1644 []types.PermValue{1645 types.PermChangeTxFee,1646 },1647 ),1648 ctx.BlockTime(),1649 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEndTime)),1650 ctx.BlockTime().Add(time.Second*time.Duration(properties.ProposalEnactmentTime)+time.Second*time.Duration(properties.ProposalEndTime)),1651 ctx.BlockHeight()+2,1652 ctx.BlockHeight()+3,1653 )1654 require.NoError(t, err)1655 require.Equal(t, expectedSavedProposal, savedProposal)1656 // Next proposal ID is increased.1657 id := app.CustomGovKeeper.GetNextProposalID(ctx)1658 require.Equal(t, uint64(2), id)1659 // Is not on finished active proposals.1660 iterator := app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1661 require.False(t, iterator.Valid())1662 ctx = ctx.WithBlockTime(ctx.BlockTime().Add(time.Minute * 10))1663 iterator = app.CustomGovKeeper.GetActiveProposalsWithFinishedVotingEndTimeIterator(ctx, ctx.BlockTime())1664 require.True(t, iterator.Valid())1665}...

Full Screen

Full Screen

interfaces.go

Source:interfaces.go Github

copy

Full Screen

1package interfaces2import (3 "context"4 "math/big"5 "net/http"6 "time"7 "github.com/ethereum/go-ethereum"8 "github.com/ethereum/go-ethereum/accounts/abi/bind"9 "github.com/ethereum/go-ethereum/common"10 eth "github.com/ethereum/go-ethereum/core/types"11 "github.com/globalsign/mgo"12 "github.com/globalsign/mgo/bson"13 "github.com/tomochain/tomox-sdk/rabbitmq"14 "github.com/tomochain/tomox-sdk/relayer"15 "github.com/tomochain/tomox-sdk/types"16 "github.com/tomochain/tomox-sdk/ws"17)18type OrderDao interface {19 GetCollection() *mgo.Collection20 Create(o *types.Order) error21 Watch() (*mgo.ChangeStream, *mgo.Session, error)22 Update(id bson.ObjectId, o *types.Order) error23 Upsert(id bson.ObjectId, o *types.Order) error24 Delete(orders ...*types.Order) error25 DeleteByHashes(hashes ...common.Hash) error26 UpdateAllByHash(h common.Hash, o *types.Order) error27 UpdateByHash(h common.Hash, o *types.Order) error28 UpsertByHash(h common.Hash, o *types.Order) error29 GetOrderCountByUserAddress(addr common.Address) (int, error)30 GetByID(id bson.ObjectId) (*types.Order, error)31 GetByHash(h common.Hash) (*types.Order, error)32 GetByHashes(hashes []common.Hash) ([]*types.Order, error)33 GetByUserAddress(addr, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Order, error)34 GetOpenOrdersByUserAddress(addr common.Address) ([]*types.Order, error)35 GetCurrentByUserAddress(a common.Address, limit ...int) ([]*types.Order, error)36 GetHistoryByUserAddress(a, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Order, error)37 UpdateOrderFilledAmount(h common.Hash, value *big.Int) error38 UpdateOrderFilledAmounts(h []common.Hash, values []*big.Int) ([]*types.Order, error)39 UpdateOrderStatusesByHashes(status string, hashes ...common.Hash) ([]*types.Order, error)40 GetUserLockedBalance(account common.Address, token common.Address, pairs []*types.Pair) (*big.Int, error)41 UpdateOrderStatus(h common.Hash, status string) error42 GetRawOrderBook(*types.Pair) ([]*types.Order, error)43 GetOrderBook(*types.Pair) ([]map[string]string, []map[string]string, error)44 GetOrderBookInDb(*types.Pair) ([]map[string]string, []map[string]string, error)45 GetSideOrderBook(p *types.Pair, side string, sort int, limit ...int) ([]map[string]string, error)46 GetOrderBookPricePoint(p *types.Pair, pp *big.Int, side string) (*big.Int, error)47 FindAndModify(h common.Hash, o *types.Order) (*types.Order, error)48 Drop() error49 Aggregate(q []bson.M) ([]*types.OrderData, error)50 AddNewOrder(o *types.Order, topic string) error51 CancelOrder(o *types.Order, topic string) error52 GetOrders(orderSpec types.OrderSpec, sort []string, offset int, size int) (*types.OrderRes, error)53 GetOrderNonce(addr common.Address) (interface{}, error)54 GetOpenOrders() ([]*types.Order, error)55 GetBestBid(baseToken, quouteToken common.Address) (*types.PriceVolume, error)56 GetBestAsk(baseToken, quouteToken common.Address) (*types.PriceVolume, error)57}58type StopOrderDao interface {59 Create(so *types.StopOrder) error60 Update(id bson.ObjectId, so *types.StopOrder) error61 UpdateByHash(h common.Hash, so *types.StopOrder) error62 Upsert(id bson.ObjectId, so *types.StopOrder) error63 UpsertByHash(h common.Hash, so *types.StopOrder) error64 UpdateAllByHash(h common.Hash, so *types.StopOrder) error65 GetByHash(h common.Hash) (*types.StopOrder, error)66 FindAndModify(h common.Hash, so *types.StopOrder) (*types.StopOrder, error)67 GetTriggeredStopOrders(baseToken, quoteToken common.Address, lastPrice *big.Int) ([]*types.StopOrder, error)68 Drop() error69}70type AccountDao interface {71 Create(account *types.Account) (err error)72 GetAll() (res []types.Account, err error)73 GetByID(id bson.ObjectId) (*types.Account, error)74 GetByAddress(owner common.Address) (response *types.Account, err error)75 GetTokenBalances(owner common.Address) (map[common.Address]*types.TokenBalance, error)76 GetTokenBalance(owner common.Address, token common.Address) (*types.TokenBalance, error)77 UpdateTokenBalance(owner common.Address, token common.Address, tokenBalance *types.TokenBalance) (err error)78 UpdateBalance(owner common.Address, token common.Address, balance *big.Int) (err error)79 FindOrCreate(addr common.Address) (*types.Account, error)80 Transfer(token common.Address, fromAddress common.Address, toAddress common.Address, amount *big.Int) error81 Drop()82 GetFavoriteTokens(owner common.Address) (map[common.Address]bool, error)83 AddFavoriteToken(owner, token common.Address) error84 DeleteFavoriteToken(owner, token common.Address) error85}86type RelayerDao interface {87 Create(relayer *types.Relayer) (err error)88 GetAll() (res []types.Relayer, err error)89 GetByHost(host string) (relayer *types.Relayer, err error)90 GetByAddress(addr common.Address) (relayer *types.Relayer, err error)91 DeleteByAddress(addr common.Address) error92 UpdateByAddress(addr common.Address, relayer *types.Relayer) error93 UpdateNameByAddress(addr common.Address, name string, url string) error94}95type ConfigDao interface {96 GetSchemaVersion() uint6497 GetAddressIndex(chain types.Chain) (uint64, error)98 IncrementAddressIndex(chain types.Chain) error99 ResetBlockCounters() error100 GetBlockToProcess(chain types.Chain) (uint64, error)101 SaveLastProcessedBlock(chain types.Chain, block uint64) error102 Drop()103}104type AssociationDao interface {105 GetAssociationByChainAddress(chain types.Chain, address common.Address) (*types.AddressAssociationRecord, error)106 GetAssociationByChainAssociatedAddress(chain types.Chain, associatedAddress common.Address) (*types.AddressAssociationRecord, error)107 // save mean if there is no item then insert, otherwise update108 SaveAssociation(record *types.AddressAssociationRecord) error109 SaveDepositTransaction(chain types.Chain, sourceAccount common.Address, txEnvelope string) error110 SaveAssociationStatus(chain types.Chain, sourceAccount common.Address, status string) error111}112type WalletDao interface {113 Create(wallet *types.Wallet) error114 GetAll() ([]types.Wallet, error)115 GetByID(id bson.ObjectId) (*types.Wallet, error)116 GetByAddress(addr common.Address) (*types.Wallet, error)117 GetDefaultAdminWallet() (*types.Wallet, error)118 GetOperatorWallets() ([]*types.Wallet, error)119}120type PairDao interface {121 Create(o *types.Pair) error122 GetAll() ([]types.Pair, error)123 GetAllByCoinbase(addr common.Address) ([]types.Pair, error)124 GetActivePairs() ([]*types.Pair, error)125 GetActivePairsByCoinbase(addr common.Address) ([]*types.Pair, error)126 GetByID(id bson.ObjectId) (*types.Pair, error)127 GetByName(name string) (*types.Pair, error)128 GetByTokenSymbols(baseTokenSymbol, quoteTokenSymbol string) (*types.Pair, error)129 GetByTokenAddress(baseToken, quoteToken common.Address) (*types.Pair, error)130 DeleteByToken(baseAddress common.Address, quoteAddress common.Address) error131 DeleteByTokenAndCoinbase(baseAddress common.Address, quoteAddress common.Address, addr common.Address) error132}133type TradeDao interface {134 GetCollection() *mgo.Collection135 Create(o ...*types.Trade) error136 Watch() (*mgo.ChangeStream, *mgo.Session, error)137 Update(t *types.Trade) error138 UpdateByHash(h common.Hash, t *types.Trade) error139 GetAll() ([]types.Trade, error)140 Aggregate(q []bson.M) ([]*types.Tick, error)141 GetByPairName(name string) ([]*types.Trade, error)142 GetByHash(h common.Hash) (*types.Trade, error)143 GetByMakerOrderHash(h common.Hash) ([]*types.Trade, error)144 GetByTakerOrderHash(h common.Hash) ([]*types.Trade, error)145 GetByOrderHashes(hashes []common.Hash) ([]*types.Trade, error)146 GetSortedTrades(bt, qt common.Address, from, to int64, n int) ([]*types.Trade, error)147 GetSortedTradesByUserAddress(a, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Trade, error)148 GetNTradesByPairAddress(bt, qt common.Address, n int) ([]*types.Trade, error)149 GetTradesByPairAddress(bt, qt common.Address, n int) ([]*types.Trade, error)150 GetAllTradesByPairAddress(bt, qt common.Address) ([]*types.Trade, error)151 FindAndModify(h common.Hash, t *types.Trade) (*types.Trade, error)152 GetByUserAddress(a common.Address) ([]*types.Trade, error)153 GetLatestTrade(bt, qt common.Address) (*types.Trade, error)154 UpdateTradeStatus(h common.Hash, status string) error155 UpdateTradeStatuses(status string, hashes ...common.Hash) ([]*types.Trade, error)156 UpdateTradeStatusesByOrderHashes(status string, hashes ...common.Hash) ([]*types.Trade, error)157 Drop()158 GetTrades(tradeSpec *types.TradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.TradeRes, error)159 GetTradesUserHistory(a common.Address, tradeSpec *types.TradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.TradeRes, error)160 GetTradeByTime(dateFrom, dateTo int64, pageOffset int, pageSize int) ([]*types.Trade, error)161}162type TokenDao interface {163 Create(token *types.Token) error164 UpdateByToken(contractAddress common.Address, token *types.Token) error165 UpdateByTokenAndCoinbase(contractAddress common.Address, addr common.Address, token *types.Token) error166 GetAll() ([]types.Token, error)167 GetAllByCoinbase(addr common.Address) ([]types.Token, error)168 GetByID(id bson.ObjectId) (*types.Token, error)169 GetByAddress(addr common.Address) (*types.Token, error)170 GetBySymbol(symbol string) (*types.Token, error)171 GetQuoteTokens() ([]types.Token, error)172 GetBaseTokens() ([]types.Token, error)173 UpdateFiatPriceBySymbol(symbol string, price float64) error174 Drop() error175 DeleteByToken(contractAddress common.Address) error176 DeleteByTokenAndCoinbase(contractAddress common.Address, addr common.Address) error177}178type NotificationDao interface {179 Create(notifications ...*types.Notification) ([]*types.Notification, error)180 GetAll() ([]types.Notification, error)181 GetByUserAddress(addr common.Address, limit int, offset int) ([]*types.Notification, error)182 GetSortDecByUserAddress(addr common.Address, limit int, offset int) ([]*types.Notification, error)183 GetByID(id bson.ObjectId) (*types.Notification, error)184 FindAndModify(id bson.ObjectId, n *types.Notification) (*types.Notification, error)185 Update(n *types.Notification) error186 Upsert(id bson.ObjectId, n *types.Notification) error187 Delete(notifications ...*types.Notification) error188 DeleteByIds(ids ...bson.ObjectId) error189 Aggregate(q []bson.M) ([]*types.Notification, error)190 Drop()191 MarkRead(id bson.ObjectId) error192 MarkUnRead(id bson.ObjectId) error193 MarkAllRead(addr common.Address) error194}195type Engine interface {196 HandleOrders(msg *rabbitmq.Message) error197 // RecoverOrders(matches types.Matches) error198 // CancelOrder(order *types.Order) (*types.EngineResponse, error)199 // DeleteOrder(o *types.Order) error200 Provider() EthereumProvider201}202type WalletService interface {203 CreateAdminWallet(a common.Address) (*types.Wallet, error)204 GetDefaultAdminWallet() (*types.Wallet, error)205 GetOperatorWallets() ([]*types.Wallet, error)206 GetOperatorAddresses() ([]common.Address, error)207 GetAll() ([]types.Wallet, error)208 GetByAddress(addr common.Address) (*types.Wallet, error)209}210type OHLCVService interface {211 Unsubscribe(c *ws.Client)212 UnsubscribeChannel(c *ws.Client, p *types.SubscriptionPayload)213 Subscribe(c *ws.Client, p *types.SubscriptionPayload)214 GetOHLCV(p []types.PairAddresses, duration int64, unit string, timeInterval ...int64) ([]*types.Tick, error)215 Get24hTick(baseToken, quoteToken common.Address) *types.Tick216 GetFiatPriceChart() (map[string][]*types.FiatPriceItem, error)217 GetLastPriceCurrentByTime(symbol string, createAt time.Time) (*big.Float, error)218 GetAllTokenPairData() ([]*types.PairData, error)219 GetAllTokenPairDataByCoinbase(addr common.Address) ([]*types.PairData, error)220 GetTokenPairData(baseToken common.Address, quoteToken common.Address) *types.PairData221 GetVolumeByUsdt(token common.Address, volume *big.Int) *big.Int222 GetVolumeByCoinbase(addr common.Address, years, month, days int) (*big.Int, *big.Int, error)223}224type EthereumService interface {225 WaitMined(hash common.Hash) (*eth.Receipt, error)226 GetPendingNonceAt(a common.Address) (uint64, error)227 GetBalanceAt(a common.Address) (*big.Int, error)228}229type OrderService interface {230 GetOrdersLockedBalanceByUserAddress(addr common.Address) (map[string]*big.Int, error)231 GetOrderCountByUserAddress(addr common.Address) (int, error)232 GetByID(id bson.ObjectId) (*types.Order, error)233 GetByHash(h common.Hash) (*types.Order, error)234 GetByHashes(hashes []common.Hash) ([]*types.Order, error)235 // GetTokenByAddress(a common.Address) (*types.Token, error)236 GetByUserAddress(a, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Order, error)237 GetCurrentByUserAddress(a common.Address, limit ...int) ([]*types.Order, error)238 GetHistoryByUserAddress(a, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Order, error)239 NewOrder(o *types.Order) error240 CancelOrder(oc *types.OrderCancel) error241 CancelAllOrder(a common.Address) error242 HandleEngineResponse(res *types.EngineResponse) error243 GetOrders(orderSpec types.OrderSpec, sort []string, offset int, size int) (*types.OrderRes, error)244 GetOrderNonceByUserAddress(addr common.Address) (interface{}, error)245 GetBestBid(baseToken, quouteToken common.Address) (*types.PriceVolume, error)246 GetBestAsk(baseToken, quouteToken common.Address) (*types.PriceVolume, error)247}248type OrderBookService interface {249 GetOrderBook(bt, qt common.Address) (*types.OrderBook, error)250 GetDbOrderBook(bt, qt common.Address) (*types.OrderBook, error)251 GetRawOrderBook(bt, qt common.Address) (*types.RawOrderBook, error)252 SubscribeOrderBook(c *ws.Client, bt, qt common.Address)253 UnsubscribeOrderBook(c *ws.Client)254 UnsubscribeOrderBookChannel(c *ws.Client, bt, qt common.Address)255 SubscribeRawOrderBook(c *ws.Client, bt, qt common.Address)256 UnsubscribeRawOrderBook(c *ws.Client)257 UnsubscribeRawOrderBookChannel(c *ws.Client, bt, qt common.Address)258}259type PairService interface {260 Create(pair *types.Pair) error261 CreatePairs(token common.Address) ([]*types.Pair, error)262 GetByID(id bson.ObjectId) (*types.Pair, error)263 GetByTokenAddress(bt, qt common.Address) (*types.Pair, error)264 GetTokenPairData(bt, qt common.Address) (*types.PairData, error)265 GetAllTokenPairData() ([]*types.PairData, error)266 GetAllTokenPairDataByCoinbase(addr common.Address) ([]*types.PairData, error)267 GetAll() ([]types.Pair, error)268 GetAllByCoinbase(addr common.Address) ([]types.Pair, error)269}270type TokenService interface {271 Create(token *types.Token) error272 GetByID(id bson.ObjectId) (*types.Token, error)273 GetByAddress(a common.Address) (*types.Token, error)274 GetAll() ([]types.Token, error)275 GetAllByCoinbase(addr common.Address) ([]types.Token, error)276 GetQuoteTokens() ([]types.Token, error)277 GetBaseTokens() ([]types.Token, error)278}279type TradeService interface {280 GetByPairName(p string) ([]*types.Trade, error)281 GetAllTradesByPairAddress(bt, qt common.Address) ([]*types.Trade, error)282 GetSortedTrades(bt, qt common.Address, from, to int64, n int) ([]*types.Trade, error)283 GetSortedTradesByUserAddress(a, bt, qt common.Address, from, to int64, limit ...int) ([]*types.Trade, error)284 GetByUserAddress(a common.Address) ([]*types.Trade, error)285 GetByHash(h common.Hash) (*types.Trade, error)286 GetByOrderHashes(h []common.Hash) ([]*types.Trade, error)287 GetByMakerOrderHash(h common.Hash) ([]*types.Trade, error)288 GetByTakerOrderHash(h common.Hash) ([]*types.Trade, error)289 Subscribe(c *ws.Client, bt, qt common.Address)290 UnsubscribeChannel(c *ws.Client, bt, qt common.Address)291 Unsubscribe(c *ws.Client)292 GetTrades(tradeSpec *types.TradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.TradeRes, error)293 GetTradesUserHistory(a common.Address, tradeSpec *types.TradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.TradeRes, error)294}295type PriceBoardService interface {296 Subscribe(c *ws.Client, bt, qt common.Address)297 UnsubscribeChannel(c *ws.Client, bt, qt common.Address)298 Unsubscribe(c *ws.Client)299}300type MarketsService interface {301 Subscribe(c *ws.Client)302 UnsubscribeChannel(c *ws.Client)303 Unsubscribe(c *ws.Client)304}305type NotificationService interface {306 Create(n *types.Notification) ([]*types.Notification, error)307 GetAll() ([]types.Notification, error)308 GetByUserAddress(a common.Address, limit int, offset int) ([]*types.Notification, error)309 GetSortDecByUserAddress(addr common.Address, limit int, offset int) ([]*types.Notification, error)310 GetByID(id bson.ObjectId) (*types.Notification, error)311 Update(n *types.Notification) (*types.Notification, error)312 MarkRead(id bson.ObjectId) error313 MarkUnRead(id bson.ObjectId) error314 MarkAllRead(addr common.Address) error315}316type TxService interface {317 GetTxCallOptions() *bind.CallOpts318 GetTxSendOptions() (*bind.TransactOpts, error)319 GetTxDefaultSendOptions() (*bind.TransactOpts, error)320 SetTxSender(w *types.Wallet)321 GetCustomTxSendOptions(w *types.Wallet) *bind.TransactOpts322}323type AccountService interface {324 GetAll() ([]types.Account, error)325 Create(account *types.Account) error326 GetByID(id bson.ObjectId) (*types.Account, error)327 GetByAddress(a common.Address) (*types.Account, error)328 FindOrCreate(a common.Address) (*types.Account, error)329 GetTokenBalance(owner common.Address, token common.Address) (*types.TokenBalance, error)330 GetTokenBalances(owner common.Address) (map[common.Address]*types.TokenBalance, error)331 Transfer(token common.Address, fromAddress common.Address, toAddress common.Address, amount *big.Int) error332 GetFavoriteTokens(account common.Address) (map[common.Address]bool, error)333 AddFavoriteToken(account, token common.Address) error334 DeleteFavoriteToken(account, token common.Address) error335 GetTokenBalanceProvidor(owner common.Address, token common.Address) (*types.TokenBalance, error)336}337type ValidatorService interface {338 ValidateAvailablExchangeBalance(o *types.Order) error339 ValidateAvailablLendingBalance(o *types.LendingOrder) error340}341type EthereumConfig interface {342 GetURL() string343 ExchangeAddress() common.Address344}345type EthereumClient interface {346 CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error)347 CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)348 PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)349 PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error)350 TransactionReceipt(ctx context.Context, txHash common.Hash) (*eth.Receipt, error)351 EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error)352 SendTransaction(ctx context.Context, tx *eth.Transaction) error353 PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)354 BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error)355 FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]eth.Log, error)356 SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- eth.Log) (ethereum.Subscription, error)357 SuggestGasPrice(ctx context.Context) (*big.Int, error)358}359type EthereumProvider interface {360 WaitMined(h common.Hash) (*eth.Receipt, error)361 GetBalanceAt(a common.Address) (*big.Int, error)362 GetPendingNonceAt(a common.Address) (uint64, error)363 BalanceOf(owner common.Address, token common.Address) (*big.Int, error)364 Decimals(token common.Address) (uint8, error)365 Symbol(token common.Address) (string, error)366 Balance(owner common.Address, token common.Address) (*big.Int, error)367}368// RelayerService interface for relayer369type RelayerService interface {370 UpdateRelayer(addr common.Address) error371 UpdateRelayers() error372 UpdateNameByAddress(addr common.Address, name string, url string) error373 GetRelayerAddress(r *http.Request) common.Address374 GetByAddress(addr common.Address) (*types.Relayer, error)375 GetAll() ([]types.Relayer, error)376}377// Relayer interface for relayer378type Relayer interface {379 GetRelayer(addr common.Address) (*relayer.RInfo, error)380 GetLending() (*relayer.LendingRInfo, error)381 GetRelayers() ([]*relayer.RInfo, error)382 GetLendings() ([]*relayer.LendingRInfo, error)383}384// LendingOrderService for lending385type LendingOrderService interface {386 NewLendingOrder(o *types.LendingOrder) error387 CancelLendingOrder(oc *types.LendingOrder) error388 GetLendingNonceByUserAddress(addr common.Address) (uint64, error)389 GetByHash(h common.Hash) (*types.LendingOrder, error)390 RepayLendingOrder(o *types.LendingOrder) error391 TopupLendingOrder(o *types.LendingOrder) error392 GetLendingOrders(lendingSpec types.LendingSpec, sort []string, offset int, size int) (*types.LendingRes, error)393 GetTopup(topupSpec types.TopupSpec, sort []string, offset int, size int) (*types.LendingRes, error)394 GetRepay(repaySpec types.RepaySpec, sort []string, offset int, size int) (*types.LendingRes, error)395 GetRecall(recall types.RecallSpec, sort []string, offset int, size int) (*types.LendingRes, error)396 EstimateCollateral(collateralToken common.Address, lendingToken common.Address, lendingAmount *big.Float) (*big.Float, *big.Float, error)397}398// LendingOrderDao dao399type LendingOrderDao interface {400 GetByHash(h common.Hash) (*types.LendingOrder, error)401 Watch() (*mgo.ChangeStream, *mgo.Session, error)402 GetLendingNonce(addr common.Address) (uint64, error)403 AddNewLendingOrder(o *types.LendingOrder) error404 CancelLendingOrder(o *types.LendingOrder) error405 GetLendingOrderBook(term uint64, lendingToken common.Address) ([]map[string]string, []map[string]string, error)406 GetLendingOrderBookInDb(term uint64, lendingToken common.Address) ([]map[string]string, []map[string]string, error)407 GetLendingOrderBookInterest(term uint64, lendingToken common.Address, interest uint64, side string) (*big.Int, error)408 RepayLendingOrder(o *types.LendingOrder) error409 TopupLendingOrder(o *types.LendingOrder) error410 GetLendingOrders(lendingSpec types.LendingSpec, sort []string, offset int, size int) (*types.LendingRes, error)411 GetLastTokenPrice(bToken common.Address, qToken common.Address, d1, d2 int) (*big.Int, error)412 GetUserLockedBalance(account common.Address, token common.Address, tokens []types.Token) (*big.Int, error)413}414// LendingOrderBookService interface for lending order book415type LendingOrderBookService interface {416 GetLendingOrderBook(term uint64, lendingToken common.Address) (*types.LendingOrderBook, error)417 GetLendingOrderBookInDb(term uint64, lendingToken common.Address) (*types.LendingOrderBook, error)418 SubscribeLendingOrderBook(c *ws.Client, term uint64, lendingToken common.Address)419 UnsubscribeLendingOrderBook(c *ws.Client)420 UnsubscribeLendingOrderBookChannel(c *ws.Client, term uint64, lendingToken common.Address)421}422// LendingTradeService interface for lending service423type LendingTradeService interface {424 Subscribe(c *ws.Client, term uint64, lendingToken common.Address)425 UnsubscribeChannel(c *ws.Client, term uint64, lendingToken common.Address)426 Unsubscribe(c *ws.Client)427 GetLendingTradesUserHistory(a common.Address, lendingtradeSpec *types.LendingTradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.LendingTradeRes, error)428 GetLendingTrades(lendingtradeSpec *types.LendingTradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.LendingTradeRes, error)429 RegisterNotify(fn func(*types.LendingTrade))430 GetLendingTradeByTime(dateFrom, dateTo int64, pageOffset int, pageSize int) ([]*types.LendingTrade, error)431}432// LendingTradeDao interface for lending dao433type LendingTradeDao interface {434 GetLendingTradeByOrderBook(tern uint64, lendingToken common.Address, from, to int64, n int) ([]*types.LendingTrade, error)435 Watch() (*mgo.ChangeStream, *mgo.Session, error)436 GetLendingTradeByTime(dateFrom, dateTo int64, pageOffset int, pageSize int) ([]*types.LendingTrade, error)437 GetLendingTradesUserHistory(a common.Address, lendingtradeSpec *types.LendingTradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.LendingTradeRes, error)438 GetLendingTrades(lendingtradeSpec *types.LendingTradeSpec, sortedBy []string, pageOffset int, pageSize int) (*types.LendingTradeRes, error)439 GetByHash(hash common.Hash) (*types.LendingTrade, error)440}441// LendingOhlcvService interface for lending service442type LendingOhlcvService interface {443 GetOHLCV(term uint64, lendingToken common.Address, duration int64, unit string, timeInterval ...int64) ([]*types.LendingTick, error)444 Subscribe(conn *ws.Client, p *types.SubscriptionPayload)445 Unsubscribe(conn *ws.Client)446 GetAllTokenPairData() ([]*types.LendingTick, error)447 GetTokenPairData(term uint64, lendingToken common.Address) *types.LendingTick448 GetLendingVolumeByCoinbase(addr common.Address, years, months, days int) (*big.Int, *big.Int, error)449}450// LendingPairDao interface for lending pair by term/lendingtoken451type LendingPairDao interface {452 Create(o *types.LendingPair) error453 GetAll() ([]types.LendingPair, error)454 GetAllByCoinbase(addr common.Address) ([]types.LendingPair, error)455 DeleteByLendingKey(term uint64, lendingAddress common.Address) error456 DeleteByLendingKeyAndCoinbase(term uint64, lendingAddress common.Address, addr common.Address) error457 GetByLendingID(term uint64, lendingToken common.Address) (*types.LendingPair, error)458}459//LendingPairService imp lending460type LendingPairService interface {461 GetAll() ([]types.LendingPair, error)462 GetAllByCoinbase(addr common.Address) ([]types.LendingPair, error)463 GetByLendingID(term uint64, lendingAddress common.Address) (*types.LendingPair, error)464}465// LendingMarketsService lending service interface466type LendingMarketsService interface {467 Subscribe(c *ws.Client)468 UnsubscribeChannel(c *ws.Client)469 Unsubscribe(c *ws.Client)470}471// LendingPriceBoardService lending price board service472type LendingPriceBoardService interface {473 Subscribe(c *ws.Client, term uint64, lendingToken common.Address)474 UnsubscribeChannel(c *ws.Client, term uint64, lendingToken common.Address)475 Unsubscribe(c *ws.Client)476}...

Full Screen

Full Screen

grpc_query.go

Source:grpc_query.go Github

copy

Full Screen

...94// Proposals query proposals by querying params with pagination95func (k Keeper) Proposals(goCtx context.Context, request *types.QueryProposalsRequest) (*types.QueryProposalsResponse, error) {96 c := sdk.UnwrapSDKContext(goCtx)97 if request == nil {98 err := status.Error(codes.InvalidArgument, "empty request")99 return nil, sdkerrors.Wrap(types.ErrGettingProposals, fmt.Sprintf("error getting proposals: %s", err.Error()))100 }101 store := c.KVStore(k.storeKey)102 var proposals []types.Proposal103 var pageRes *query.PageResponse104 var err error105 proposalsStore := prefix.NewStore(store, ProposalsPrefix)106 onResult := func(key []byte, value []byte, accumulate bool) (bool, error) {107 var proposal types.Proposal108 err := k.cdc.Unmarshal(value, &proposal)109 if err != nil {110 return false, err111 }112 if accumulate {113 proposals = append(proposals, proposal)114 }115 return true, nil116 }117 // we set maximum limit for safety of iteration118 if request.Pagination != nil && request.Pagination.Limit > kiratypes.PageIterationLimit {119 request.Pagination.Limit = kiratypes.PageIterationLimit120 }121 pageRes, err = query.FilteredPaginate(proposalsStore, request.Pagination, onResult)122 if err != nil {123 return nil, sdkerrors.Wrap(types.ErrGettingProposals, fmt.Sprintf("error getting proposals: %s", err.Error()))124 }125 res := types.QueryProposalsResponse{126 Proposals: proposals,127 Pagination: pageRes,128 }129 return &res, nil130}131// WhitelistedProposalVoters returns whitelisted voters for a proposal for tracking132func (k Keeper) WhitelistedProposalVoters(goCtx context.Context, request *types.QueryWhitelistedProposalVotersRequest) (*types.QueryWhitelistedProposalVotersResponse, error) {133 ctx := sdk.UnwrapSDKContext(goCtx)134 proposal, found := k.GetProposal(ctx, request.ProposalId)135 if !found {136 return nil, sdkerrors.Wrap(types.ErrGettingProposals, fmt.Sprintf("proposal does not exist for %d", request.ProposalId))137 }138 actors := k.GetNetworkActorsByAbsoluteWhitelistPermission(ctx, proposal.GetContent().VotePermission())139 return &types.QueryWhitelistedProposalVotersResponse{Voters: actors}, nil140}141// Vote queries voted information based on proposalID, voterAddr.142func (k Keeper) Vote(goCtx context.Context, request *types.QueryVoteRequest) (*types.QueryVoteResponse, error) {143 ctx := sdk.UnwrapSDKContext(goCtx)144 vote, found := k.GetVote(ctx, request.ProposalId, request.Voter)145 if !found {146 return &types.QueryVoteResponse{Vote: vote}, sdkerrors.Wrap(types.ErrGettingProposalVotes, fmt.Sprintf("error getting votes for proposal %d, voter %s", request.ProposalId, request.Voter.String()))147 }148 return &types.QueryVoteResponse{Vote: vote}, nil149}150// Votes queries votes of a given proposal.151func (k Keeper) Votes(goCtx context.Context, request *types.QueryVotesRequest) (*types.QueryVotesResponse, error) {152 ctx := sdk.UnwrapSDKContext(goCtx)153 votes := k.GetProposalVotes(ctx, request.ProposalId)154 return &types.QueryVotesResponse{Votes: votes}, nil155}156// AllDataReferenceKeys queries all data reference keys with pagination157func (k Keeper) AllDataReferenceKeys(goCtx context.Context, request *types.QueryDataReferenceKeysRequest) (*types.QueryDataReferenceKeysResponse, error) {158 ctx := sdk.UnwrapSDKContext(goCtx)159 if request == nil {160 return nil, status.Error(codes.InvalidArgument, "empty request")161 }162 var keys []string163 store := ctx.KVStore(k.storeKey)164 dataReferenceStore := prefix.NewStore(store, DataRegistryPrefix)165 pageRes, err := query.Paginate(dataReferenceStore, request.Pagination, func(key []byte, value []byte) error {166 keys = append(keys, string(key))167 return nil168 })169 if err != nil {170 return &types.QueryDataReferenceKeysResponse{}, err171 }172 res := types.QueryDataReferenceKeysResponse{173 Keys: keys,174 Pagination: pageRes,175 }176 return &res, nil177}178// DataReferenceByKey queries data reference by key179func (k Keeper) DataReferenceByKey(goCtx context.Context, request *types.QueryDataReferenceRequest) (*types.QueryDataReferenceResponse, error) {180 ctx := sdk.UnwrapSDKContext(goCtx)181 if request == nil {182 return nil, status.Error(codes.InvalidArgument, "empty request")183 }184 dataReference, ok := k.GetDataRegistryEntry(ctx, request.GetKey())185 if !ok {186 return nil, status.Error(codes.NotFound, "not found")187 }188 res := types.QueryDataReferenceResponse{189 Data: &dataReference,190 }191 return &res, nil192}193// IdentityRecord query identity record by id194func (k Keeper) IdentityRecord(goCtx context.Context, request *types.QueryIdentityRecordRequest) (*types.QueryIdentityRecordResponse, error) {195 ctx := sdk.UnwrapSDKContext(goCtx)196 if request == nil {197 return nil, status.Error(codes.InvalidArgument, "empty request")198 }199 res := types.QueryIdentityRecordResponse{200 Record: k.GetIdentityRecordById(ctx, request.Id),201 }202 return &res, nil203}204// IdentityRecordsByAddress query identity records by creator and keys205func (k Keeper) IdentityRecordsByAddress(goCtx context.Context, request *types.QueryIdentityRecordsByAddressRequest) (*types.QueryIdentityRecordsByAddressResponse, error) {206 ctx := sdk.UnwrapSDKContext(goCtx)207 if request == nil {208 return nil, status.Error(codes.InvalidArgument, "empty request")209 }210 records, err := k.GetIdRecordsByAddressAndKeys(ctx, request.Creator, request.Keys)211 return &types.QueryIdentityRecordsByAddressResponse{212 Records: records,213 }, err214}215// AllIdentityRecords query all identity records216func (k Keeper) AllIdentityRecords(goCtx context.Context, request *types.QueryAllIdentityRecordsRequest) (*types.QueryAllIdentityRecordsResponse, error) {217 ctx := sdk.UnwrapSDKContext(goCtx)218 if request == nil {219 return nil, status.Error(codes.InvalidArgument, "empty request")220 }221 store := ctx.KVStore(k.storeKey)222 recordStore := prefix.NewStore(store, types.KeyPrefixIdentityRecord)223 records := []types.IdentityRecord{}224 onResult := func(key []byte, value []byte, accumulate bool) (bool, error) {225 var record types.IdentityRecord226 err := k.cdc.Unmarshal(value, &record)227 if err != nil {228 return false, err229 }230 if accumulate {231 records = append(records, record)232 }233 return true, nil234 }235 // we set maximum limit for safety of iteration236 if request.Pagination != nil && request.Pagination.Limit > kiratypes.PageIterationLimit {237 request.Pagination.Limit = kiratypes.PageIterationLimit238 }239 pageRes, err := query.FilteredPaginate(recordStore, request.Pagination, onResult)240 if err != nil {241 return nil, err242 }243 res := types.QueryAllIdentityRecordsResponse{244 Records: records,245 Pagination: pageRes,246 }247 return &res, nil248}249// IdentityRecordVerifyRequest query identity record verify request by id250func (k Keeper) IdentityRecordVerifyRequest(goCtx context.Context, request *types.QueryIdentityVerifyRecordRequest) (*types.QueryIdentityVerifyRecordResponse, error) {251 ctx := sdk.UnwrapSDKContext(goCtx)252 if request == nil {253 return nil, status.Error(codes.InvalidArgument, "empty request")254 }255 res := types.QueryIdentityVerifyRecordResponse{256 VerifyRecord: k.GetIdRecordsVerifyRequest(ctx, request.RequestId),257 }258 return &res, nil259}260// IdentityRecordVerifyRequestsByRequester query identity record verify requests by requester261func (k Keeper) IdentityRecordVerifyRequestsByRequester(goCtx context.Context, request *types.QueryIdentityRecordVerifyRequestsByRequester) (*types.QueryIdentityRecordVerifyRequestsByRequesterResponse, error) {262 ctx := sdk.UnwrapSDKContext(goCtx)263 if request == nil {264 return nil, status.Error(codes.InvalidArgument, "empty request")265 }266 requests := []types.IdentityRecordsVerify{}267 store := ctx.KVStore(k.storeKey)268 requestByRequesterStore := prefix.NewStore(store, types.IdRecordVerifyRequestByRequesterPrefix(request.Requester.String()))269 onResult := func(key []byte, value []byte, accumulate bool) (bool, error) {270 requestId := sdk.BigEndianToUint64(value)271 request := k.GetIdRecordsVerifyRequest(ctx, requestId)272 if request == nil {273 return false, fmt.Errorf("invalid id available on requests: %d", requestId)274 }275 if accumulate {276 requests = append(requests, *request)277 }278 return true, nil279 }280 // we set maximum limit for safety of iteration281 if request.Pagination != nil && request.Pagination.Limit > kiratypes.PageIterationLimit {282 request.Pagination.Limit = kiratypes.PageIterationLimit283 }284 pageRes, err := query.FilteredPaginate(requestByRequesterStore, request.Pagination, onResult)285 if err != nil {286 return nil, err287 }288 res := types.QueryIdentityRecordVerifyRequestsByRequesterResponse{289 VerifyRecords: requests,290 Pagination: pageRes,291 }292 return &res, nil293}294// IdentityRecordVerifyRequestsByApprover query identity records verify requests by approver295func (k Keeper) IdentityRecordVerifyRequestsByApprover(goCtx context.Context, request *types.QueryIdentityRecordVerifyRequestsByApprover) (*types.QueryIdentityRecordVerifyRequestsByApproverResponse, error) {296 ctx := sdk.UnwrapSDKContext(goCtx)297 if request == nil {298 return nil, status.Error(codes.InvalidArgument, "empty request")299 }300 requests := []types.IdentityRecordsVerify{}301 store := ctx.KVStore(k.storeKey)302 requestByApproverStore := prefix.NewStore(store, types.IdRecordVerifyRequestByApproverPrefix(request.Approver.String()))303 onResult := func(key []byte, value []byte, accumulate bool) (bool, error) {304 requestId := sdk.BigEndianToUint64(value)305 request := k.GetIdRecordsVerifyRequest(ctx, requestId)306 if request == nil {307 return false, fmt.Errorf("invalid id available on requests: %d", requestId)308 }309 if accumulate {310 requests = append(requests, *request)311 }312 return true, nil313 }314 // we set maximum limit for safety of iteration315 if request.Pagination != nil && request.Pagination.Limit > kiratypes.PageIterationLimit {316 request.Pagination.Limit = kiratypes.PageIterationLimit317 }318 pageRes, err := query.FilteredPaginate(requestByApproverStore, request.Pagination, onResult)319 if err != nil {320 return nil, err321 }322 res := types.QueryIdentityRecordVerifyRequestsByApproverResponse{323 VerifyRecords: requests,324 Pagination: pageRes,325 }326 return &res, nil327}328// AllIdentityRecordVerifyRequests query all identity records verify requests329func (k Keeper) AllIdentityRecordVerifyRequests(goCtx context.Context, request *types.QueryAllIdentityRecordVerifyRequests) (*types.QueryAllIdentityRecordVerifyRequestsResponse, error) {330 ctx := sdk.UnwrapSDKContext(goCtx)331 if request == nil {332 return nil, status.Error(codes.InvalidArgument, "empty request")333 }334 requests := []types.IdentityRecordsVerify{}335 store := ctx.KVStore(k.storeKey)336 requestStore := prefix.NewStore(store, types.KeyPrefixIdRecordVerifyRequest)337 onResult := func(key []byte, value []byte, accumulate bool) (bool, error) {338 request := types.IdentityRecordsVerify{}339 k.cdc.MustUnmarshal(value, &request)340 if accumulate {341 requests = append(requests, request)342 }343 return true, nil344 }345 // we set maximum limit for safety of iteration346 if request.Pagination != nil && request.Pagination.Limit > kiratypes.PageIterationLimit {347 request.Pagination.Limit = kiratypes.PageIterationLimit348 }349 pageRes, err := query.FilteredPaginate(requestStore, request.Pagination, onResult)350 if err != nil {351 return nil, err352 }353 res := types.QueryAllIdentityRecordVerifyRequestsResponse{354 VerifyRecords: requests,355 Pagination: pageRes,356 }357 return &res, nil358}359// GetAllDataReferenceKeys implements the Query all data reference keys gRPC method360func (k Keeper) GetAllDataReferenceKeys(sdkCtx sdk.Context, req *types.QueryDataReferenceKeysRequest) (*types.QueryDataReferenceKeysResponse, error) {361 if req == nil {362 return nil, status.Error(codes.InvalidArgument, "empty request")363 }364 var keys []string365 store := sdkCtx.KVStore(k.storeKey)366 dataReferenceStore := prefix.NewStore(store, DataRegistryPrefix)367 pageRes, err := query.Paginate(dataReferenceStore, req.Pagination, func(key []byte, value []byte) error {368 keys = append(keys, string(key))369 return nil370 })371 if err != nil {372 return &types.QueryDataReferenceKeysResponse{}, err373 }374 res := types.QueryDataReferenceKeysResponse{375 Keys: keys,376 Pagination: pageRes,377 }378 return &res, nil379}380// GetDataReferenceByKey implements the Query data reference by key gRPC method381func (k Keeper) GetDataReferenceByKey(sdkCtx sdk.Context, req *types.QueryDataReferenceRequest) (*types.QueryDataReferenceResponse, error) {382 if req == nil {383 return nil, status.Error(codes.InvalidArgument, "empty request")384 }385 dataReference, ok := k.GetDataRegistryEntry(sdkCtx, req.GetKey())386 if !ok {387 return nil, status.Error(codes.NotFound, "not found")388 }389 res := types.QueryDataReferenceResponse{390 Data: &dataReference,391 }392 return &res, nil393}...

Full Screen

Full Screen

issue9370.go

Source:issue9370.go Github

copy

Full Screen

1// errorcheck2// Copyright 2014 The Go Authors. All rights reserved.3// Use of this source code is governed by a BSD-style4// license that can be found in the LICENSE file.5// Verify that concrete/interface comparisons are6// typechecked correctly by the compiler.7package main8type I interface {9 Method()10}11type C int12func (C) Method() {}13type G func()14func (G) Method() {}15var (16 e interface{}17 i I18 c C19 n int20 f func()21 g G22)23var (24 _ = e == c25 _ = e != c26 _ = e >= c // ERROR "invalid operation.*not defined|invalid comparison"27 _ = c == e28 _ = c != e29 _ = c >= e // ERROR "invalid operation.*not defined|invalid comparison"30 _ = i == c31 _ = i != c32 _ = i >= c // ERROR "invalid operation.*not defined|invalid comparison"33 _ = c == i34 _ = c != i35 _ = c >= i // ERROR "invalid operation.*not defined|invalid comparison"36 _ = e == n37 _ = e != n38 _ = e >= n // ERROR "invalid operation.*not defined|invalid comparison"39 _ = n == e40 _ = n != e41 _ = n >= e // ERROR "invalid operation.*not defined|invalid comparison"42 // i and n are not assignable to each other43 _ = i == n // ERROR "invalid operation.*mismatched types|incompatible types"44 _ = i != n // ERROR "invalid operation.*mismatched types|incompatible types"45 _ = i >= n // ERROR "invalid operation.*mismatched types|incompatible types"46 _ = n == i // ERROR "invalid operation.*mismatched types|incompatible types"47 _ = n != i // ERROR "invalid operation.*mismatched types|incompatible types"48 _ = n >= i // ERROR "invalid operation.*mismatched types|incompatible types"49 _ = e == 150 _ = e != 151 _ = e >= 1 // ERROR "invalid operation.*not defined|invalid comparison"52 _ = 1 == e53 _ = 1 != e54 _ = 1 >= e // ERROR "invalid operation.*not defined|invalid comparison"55 _ = i == 1 // ERROR "invalid operation.*mismatched types|incompatible types"56 _ = i != 1 // ERROR "invalid operation.*mismatched types|incompatible types"57 _ = i >= 1 // ERROR "invalid operation.*mismatched types|incompatible types"58 _ = 1 == i // ERROR "invalid operation.*mismatched types|incompatible types"59 _ = 1 != i // ERROR "invalid operation.*mismatched types|incompatible types"60 _ = 1 >= i // ERROR "invalid operation.*mismatched types|incompatible types"61 _ = e == f // ERROR "invalid operation.*not defined|invalid operation"62 _ = e != f // ERROR "invalid operation.*not defined|invalid operation"63 _ = e >= f // ERROR "invalid operation.*not defined|invalid comparison"64 _ = f == e // ERROR "invalid operation.*not defined|invalid operation"65 _ = f != e // ERROR "invalid operation.*not defined|invalid operation"66 _ = f >= e // ERROR "invalid operation.*not defined|invalid comparison"67 _ = i == f // ERROR "invalid operation.*mismatched types|incompatible types"68 _ = i != f // ERROR "invalid operation.*mismatched types|incompatible types"69 _ = i >= f // ERROR "invalid operation.*mismatched types|incompatible types"70 _ = f == i // ERROR "invalid operation.*mismatched types|incompatible types"71 _ = f != i // ERROR "invalid operation.*mismatched types|incompatible types"72 _ = f >= i // ERROR "invalid operation.*mismatched types|incompatible types"73 _ = e == g // ERROR "invalid operation.*not defined|invalid operation"74 _ = e != g // ERROR "invalid operation.*not defined|invalid operation"75 _ = e >= g // ERROR "invalid operation.*not defined|invalid comparison"76 _ = g == e // ERROR "invalid operation.*not defined|invalid operation"77 _ = g != e // ERROR "invalid operation.*not defined|invalid operation"78 _ = g >= e // ERROR "invalid operation.*not defined|invalid comparison"79 _ = i == g // ERROR "invalid operation.*not defined|invalid operation"80 _ = i != g // ERROR "invalid operation.*not defined|invalid operation"81 _ = i >= g // ERROR "invalid operation.*not defined|invalid comparison"82 _ = g == i // ERROR "invalid operation.*not defined|invalid operation"83 _ = g != i // ERROR "invalid operation.*not defined|invalid operation"84 _ = g >= i // ERROR "invalid operation.*not defined|invalid comparison"85 _ = _ == e // ERROR "cannot use .*_.* as value"86 _ = _ == i // ERROR "cannot use .*_.* as value"87 _ = _ == c // ERROR "cannot use .*_.* as value"88 _ = _ == n // ERROR "cannot use .*_.* as value"89 _ = _ == f // ERROR "cannot use .*_.* as value"90 _ = _ == g // ERROR "cannot use .*_.* as value"91 _ = e == _ // ERROR "cannot use .*_.* as value"92 _ = i == _ // ERROR "cannot use .*_.* as value"93 _ = c == _ // ERROR "cannot use .*_.* as value"94 _ = n == _ // ERROR "cannot use .*_.* as value"95 _ = f == _ // ERROR "cannot use .*_.* as value"96 _ = g == _ // ERROR "cannot use .*_.* as value"97 _ = _ == _ // ERROR "cannot use .*_.* as value"98 _ = e ^ c // ERROR "invalid operation.*mismatched types|incompatible types"99 _ = c ^ e // ERROR "invalid operation.*mismatched types|incompatible types"100 _ = 1 ^ e // ERROR "invalid operation.*mismatched types|incompatible types"101 _ = e ^ 1 // ERROR "invalid operation.*mismatched types|incompatible types"102 _ = 1 ^ c103 _ = c ^ 1104)...

Full Screen

Full Screen

app_conn.go

Source:app_conn.go Github

copy

Full Screen

...6//----------------------------------------------------------------------------------------7// Enforce which abci msgs can be sent on a connection at the type level8type AppConnConsensus interface {9 SetResponseCallback(abcicli.Callback)10 Error() error11 InitChainSync(types.RequestInitChain) (*types.ResponseInitChain, error)12 BeginBlockSync(types.RequestBeginBlock) (*types.ResponseBeginBlock, error)13 DeliverTxAsync(tx []byte) *abcicli.ReqRes14 EndBlockSync(types.RequestEndBlock) (*types.ResponseEndBlock, error)15 CommitSync() (*types.ResponseCommit, error)16}17type AppConnMempool interface {18 SetResponseCallback(abcicli.Callback)19 Error() error20 CheckTxAsync(tx []byte) *abcicli.ReqRes21 FlushAsync() *abcicli.ReqRes22 FlushSync() error23}24type AppConnQuery interface {25 Error() error26 EchoSync(string) (*types.ResponseEcho, error)27 InfoSync(types.RequestInfo) (*types.ResponseInfo, error)28 QuerySync(types.RequestQuery) (*types.ResponseQuery, error)29 // SetOptionSync(key string, value string) (res types.Result)30}31//-----------------------------------------------------------------------------------------32// Implements AppConnConsensus (subset of abcicli.Client)33type appConnConsensus struct {34 appConn abcicli.Client35}36func NewAppConnConsensus(appConn abcicli.Client) *appConnConsensus {37 return &appConnConsensus{38 appConn: appConn,39 }40}41func (app *appConnConsensus) SetResponseCallback(cb abcicli.Callback) {42 app.appConn.SetResponseCallback(cb)43}44func (app *appConnConsensus) Error() error {45 return app.appConn.Error()46}47func (app *appConnConsensus) InitChainSync(req types.RequestInitChain) (*types.ResponseInitChain, error) {48 return app.appConn.InitChainSync(req)49}50func (app *appConnConsensus) BeginBlockSync(req types.RequestBeginBlock) (*types.ResponseBeginBlock, error) {51 return app.appConn.BeginBlockSync(req)52}53func (app *appConnConsensus) DeliverTxAsync(tx []byte) *abcicli.ReqRes {54 return app.appConn.DeliverTxAsync(tx)55}56func (app *appConnConsensus) EndBlockSync(req types.RequestEndBlock) (*types.ResponseEndBlock, error) {57 return app.appConn.EndBlockSync(req)58}59func (app *appConnConsensus) CommitSync() (*types.ResponseCommit, error) {60 return app.appConn.CommitSync()61}62//------------------------------------------------63// Implements AppConnMempool (subset of abcicli.Client)64type appConnMempool struct {65 appConn abcicli.Client66}67func NewAppConnMempool(appConn abcicli.Client) *appConnMempool {68 return &appConnMempool{69 appConn: appConn,70 }71}72func (app *appConnMempool) SetResponseCallback(cb abcicli.Callback) {73 app.appConn.SetResponseCallback(cb)74}75func (app *appConnMempool) Error() error {76 return app.appConn.Error()77}78func (app *appConnMempool) FlushAsync() *abcicli.ReqRes {79 return app.appConn.FlushAsync()80}81func (app *appConnMempool) FlushSync() error {82 return app.appConn.FlushSync()83}84func (app *appConnMempool) CheckTxAsync(tx []byte) *abcicli.ReqRes {85 return app.appConn.CheckTxAsync(tx)86}87//------------------------------------------------88// Implements AppConnQuery (subset of abcicli.Client)89type appConnQuery struct {90 appConn abcicli.Client91}92func NewAppConnQuery(appConn abcicli.Client) *appConnQuery {93 return &appConnQuery{94 appConn: appConn,95 }96}97func (app *appConnQuery) Error() error {98 return app.appConn.Error()99}100func (app *appConnQuery) EchoSync(msg string) (*types.ResponseEcho, error) {101 return app.appConn.EchoSync(msg)102}103func (app *appConnQuery) InfoSync(req types.RequestInfo) (*types.ResponseInfo, error) {104 return app.appConn.InfoSync(req)105}106func (app *appConnQuery) QuerySync(reqQuery types.RequestQuery) (*types.ResponseQuery, error) {107 return app.appConn.QuerySync(reqQuery)108}...

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import "fmt"2type ErrorString struct {3}4func (e *ErrorString) Error() string {5}6func New(text string) error {7 return &ErrorString{text}8}9func main() {10 err := New("emit macho dwarf: elf header corrupted")11 if err != nil {12 fmt.Println(err)13 }14}15import (16type MyError struct {17}18func (e *MyError) Error() string {19 return fmt.Sprintf("at %v, %s", e.When, e.What)20}21func run() error {22 return &MyError{23 time.Now(),24 }25}26func main() {27 if err := run(); err != nil {28 fmt.Println(err)29 }30}31In the main function, we use type assertion to get the custom error type back from the error interface value. This technique is applied throughout the standard library; for example, the os.IsNotExist function uses type assertion to get the

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := errors.New("emit macho dwarf: elf header corrupted")4 if err != nil {5 fmt.Print(err)6 }7}8func Errorf(format string, a ...interface{}) error9import (10func main() {11 err := fmt.Errorf("emit macho dwarf: %s", "elf header corrupted")12 if err != nil {13 fmt.Print(err)14 }15}16func (e *Error) Error() string17import (18func main() {19 err := errors.New("emit macho dwarf: elf header corrupted")20 if err != nil {21 fmt.Print(err.Error())22 }23}24func Wrap(err error, msg string) error25import (26func main() {27 err := errors.Wrap(errors.New("emit macho dwarf: elf header corrupted"), "my error")28 if err != nil {29 fmt.Print(err)30 }31}32func Wrapf(err error, format string, a ...interface{}) error33import (34func main() {35 err := errors.Wrapf(errors.New("emit macho dwarf: elf header corrupted"), "my error %s", "with additional info")36 if err != nil {

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Open("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(file)8}9import (10func main() {11 file, err := os.Open("test.txt")12 if err != nil {13 fmt.Println(err.Error())14 }15 fmt.Println(file)16}17import (18func main() {19 file, err := os.Open("test.txt")20 if err != nil {21 fmt.Println(err.Error())22 }23 fmt.Println(file)24}25import (26func main() {27 file, err := os.Open("test.txt")28 if err != nil {29 fmt.Println(err.Error())30 }31 fmt.Println(file)32}33import (34func main() {35 file, err := os.Open("test.txt")36 if err != nil {37 fmt.Println(err.Error())38 }39 fmt.Println(file)40}41import (42func main() {43 file, err := os.Open("test.txt")44 if err != nil {45 fmt.Println(err.Error())46 }47 fmt.Println(file)48}49import (50func main() {51 file, err := os.Open("test.txt")52 if err != nil {53 fmt.Println(err.Error())54 }55 fmt.Println(file)56}57import (58func main() {59 file, err := os.Open("test.txt")

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err = fmt.Errorf("This is an error")4 fmt.Println(err)5 err = fmt.Errorf("This is an error %d", 1)6 fmt.Println(err)7 err = fmt.Errorf("This is an error %s", "one")8 fmt.Println(err)9 err = fmt.Errorf("This is an error %f", 1.1)10 fmt.Println(err)11 err = fmt.Errorf("This is an error %t", true)12 fmt.Println(err)13 err = fmt.Errorf("This is an error %v", 1)14 fmt.Println(err)15 err = fmt.Errorf("This is an error %v", "one")16 fmt.Println(err)17 err = fmt.Errorf("This is an error %v", 1.1)18 fmt.Println(err)19 err = fmt.Errorf("This is an error %v", true)20 fmt.Println(err)21 err = fmt.Errorf("This is an error %T", 1)22 fmt.Println(err)23 err = fmt.Errorf("This is an error %T", "one")24 fmt.Println(err)25 err = fmt.Errorf("This is an error %T", 1.1)26 fmt.Println(err)27 err = fmt.Errorf("This is an error %T", true)28 fmt.Println(err)29 err = fmt.Errorf("This is an error %q", 1)30 fmt.Println(err)31 err = fmt.Errorf("This is an error %q", "one")32 fmt.Println(err)33 err = fmt.Errorf("This is an error %q", 1.1)34 fmt.Println(err)35 err = fmt.Errorf("This is an error %q", true)36 fmt.Println(err)37 err = fmt.Errorf("This is an error %x", 1)38 fmt.Println(err)39 err = fmt.Errorf("This is an error %x", "one")40 fmt.Println(err)41 err = fmt.Errorf("This is an error %x", 1.1)42 fmt.Println(err)43 err = fmt.Errorf("This is an error %x", true)44 fmt.Println(err)45}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := errors.New("Error: Something went wrong")4 fmt.Println(err)5}6Errorf() method7import (8func main() {9 err := errors.Errorf("Error: %s", "Something went wrong")10 fmt.Println(err)11}12Wrap() method13import (14func main() {15 err := errors.New("Something went wrong")16 fmt.Println(errors.Wrap(err, "Error:"))17}18Wrapf() method19import (20func main() {21 err := errors.New("Something went wrong")22 fmt.Println(errors.Wrapf(err, "Error: %s", "Something went wrong"))23}24Unwrap() method25import (26func main() {27 err := errors.New("Something went wrong")28 fmt.Println(errors.Unwrap(err))29}30Is() method

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 e1 := errors.New("Error 1")4 fmt.Println(e1)5}6import (7func main() {8 e1 := errors.New("Error 1")9 fmt.Println(e1)10 panic("Terminating the program")11}12import (13func main() {14 e1 := errors.New("Error 1")15 fmt.Println(e1)16 log.Fatal("Terminating the program")17}18Using the panic() method19Using the fatal() method20type error interface {21 Error() string22}23The Error() method is used to return the error message. It has the following syntax:24func (e *MyError) Error() string {25}26import (27type MyError struct {28}29func (

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := errors.New("New error")4 fmt.Println(err)5}6Errors.New() method7func New(text string) error8import (9func main() {10 err := errors.New("New error")11 fmt.Println(err)12}13Errorf() method14func Errorf(format string, a ...interface{}) error15import (16func main() {17 err := errors.Errorf("New error")18 fmt.Println(err)19}20Wrap() method21func Wrap(err error, message string) error22import (23func main() {24 err := errors.Wrap("New error")25 fmt.Println(err)26}27Wrapf() method28func Wrapf(err error, format string, a ...interface{}) error29import (30func main() {31 err := errors.Wrapf("New error")32 fmt.Println(err)33}34Unwrap() method35func Unwrap(err error) error36import (37func main() {38 err := errors.Wrap("New error")

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Ginkgo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful