How to use getAddress method in Cypress

Best JavaScript code snippet using cypress

OneToOne.js

Source:OneToOne.js Github

copy

Full Screen

...324 id: 101325 }326 });327 expect(user.get('address')).toBeUndefined();328 expect(user.getAddress().getId()).toBe(101);329 });330 it("should delete the key holder from the data collection", function() {331 var address = Address.load(101);332 complete({333 id: 101,334 user: {335 id: 1336 }337 });338 expect(address.get('user')).toBeUndefined();339 expect(address.getUser().getId()).toBe(1);340 });341 describe("key inference", function() {342 describe("without session", function() {343 it("should infer the key from the parent", function() {344 var user = User.load(1);345 complete({346 id: 1,347 address: {348 id: 101349 }350 });351 expect(user.getAddress().getId()).toBe(101);352 expect(user.get('addressId')).toBe(101);353 expect(user.dirty).toBe(false);354 });355 });356 describe("with session", function() {357 var session;358 beforeEach(function() {359 session = new Ext.data.Session();360 });361 afterEach(function() {362 session.destroy();363 session = null;364 });365 it("should favour an existing reference", function() {366 var user = session.createRecord('User', {367 id: 1,368 addressId: 201369 });370 user.load();371 complete({372 id: 1,373 address: {374 id: 101375 }376 });377 var address101 = session.peekRecord('Address', 101);378 expect(user.getAddress().getId()).toBe(201);379 expect(user.get('addressId')).toBe(201);380 expect(user.dirty).toBe(false);381 expect(address101).not.toBeNull();382 expect(user.getAddress()).not.toBe(address101);383 });384 it("should infer the key from the parent if not specified", function() {385 var user = User.load(1, null, session);386 complete({387 id: 1,388 address: {389 id: 101390 }391 });392 expect(user.getAddress().getId()).toBe(101);393 expect(user.get('addressId')).toBe(101);394 expect(user.dirty).toBe(false);395 });396 it("should not infer the key from the parent if a key is specified", function() {397 var user = User.load(1, null, session);398 complete({399 id: 1,400 // Essentially the same as favour an existing reference, just at load time401 addressId: 201,402 address: {403 id: 101404 }405 });406 expect(user.getAddress().getId()).toBe(201);407 expect(user.get('addressId')).toBe(201);408 expect(user.dirty).toBe(false);409 });410 });411 });412 });413 414 describe("getters/setters", function() {415 function createSuite(withSession) {416 describe(withSession ? "with session" : "without session", function() {417 var session, user, address, spy;418 beforeEach(function() {419 defineUser();420 spy = jasmine.createSpy();421 if (withSession) {422 session = new Ext.data.Session();423 }424 });425 426 afterEach(function() {427 if (withSession) {428 session.destroy();429 }430 session = spy = user = address = null;431 });432 433 describe("the key holder", function() {434 describe("getter", function() {435 beforeEach(function() {436 user = new User({437 id: 4438 }, session);439 440 });441 describe("without an instance", function() {442 describe("with no foreign key value", function() {443 it("should return null", function() {444 expect(user.getAddress()).toBeNull();445 });446 it("should not make any request", function() {447 spy = spyOn(Address.getProxy(), 'read');448 user.getAddress();449 expect(spy).not.toHaveBeenCalled();450 });451 describe("callbacks", function() {452 it("should call the callbacks before the function returns", function() {453 user.getAddress(spy);454 expect(spy).toHaveBeenCalled();455 spy.reset();456 user.getAddress({457 success: spy458 });459 expect(spy).toHaveBeenCalled();460 spy.reset();461 user.getAddress({462 callback: spy463 });464 expect(spy).toHaveBeenCalled();465 });466 it("should accept a function as the callback and default the scope to the model", function() {467 user.getAddress(spy);468 var call = spy.mostRecentCall;469 expect(call.args[0]).toBe(address);470 expect(call.args[1]).toBeNull();471 expect(call.args[2]).toBe(true);472 expect(call.object).toBe(user);473 });474 475 it("should accept a function with a scope", function() {476 var o = {};477 user.getAddress(spy, o);478 expect(spy.mostRecentCall.object).toBe(o); 479 });480 481 it("should accept an options object with success and default the scope to the model", function() {482 user.getAddress({483 success: spy484 }); 485 var call = spy.mostRecentCall; 486 expect(call.args[0]).toBe(address);487 expect(call.args[1]).toBeNull();488 expect(call.object).toBe(user); 489 });490 it("should accept an options object with success and a scope", function() {491 var o = {},492 call;493 user.getAddress({494 scope: o,495 success: spy496 }); 497 call = spy.mostRecentCall; 498 expect(call.object).toBe(o); 499 });500 it("should accept an options object with callback and default the scope to the model", function() {501 user.getAddress({502 callback: spy503 }); 504 var call = spy.mostRecentCall; 505 expect(call.args[0]).toBe(address);506 expect(call.args[1]).toBeNull();507 expect(call.args[2]).toBe(true);508 expect(call.object).toBe(user); 509 });510 511 it("should accept an options object with callback and a scope", function() {512 var o = {},513 call;514 user.getAddress({515 scope: o,516 callback: spy517 }); 518 call = spy.mostRecentCall; 519 expect(call.object).toBe(o); 520 });521 });522 });523 describe("with a foreign key value", function() {524 beforeEach(function() {525 user.set('addressId', 17);526 });527 if (withSession) {528 it("should create an instance in the session", function() {529 expect(user.getAddress()).toBe(session.getRecord('Address', 17, false));530 });531 it("should use an existing record instance", function() {532 address = session.getRecord('Address', 17, false);533 expect(user.getAddress()).toBe(address);534 });535 it("should not load an existing instance", function() {536 address = session.getRecord('Address', {537 id: 17538 }, false);539 user.getAddress();540 expect(address.isLoading()).toBe(false);541 });542 }543 it("should return an instance with the matching id", function() {544 expect(user.getAddress().getId()).toBe(17);545 });546 it("should be in a loading state", function() {547 expect(user.getAddress().isLoading()).toBe(true);548 });549 it("should trigger a load for the record", function() {550 spy = spyOn(Address.getProxy(), 'read');551 user.getAddress();552 expect(spy.mostRecentCall.args[0].getId()).toBe(17);553 });554 describe("calling while during a load", function() {555 it("should return the same record", function() {556 var rec = user.getAddress();557 expect(user.getAddress()).toBe(rec);558 });559 it("should not trigger a second load", function() {560 user.getAddress();561 spy = spyOn(Address.getProxy(), 'read');562 user.getAddress();563 expect(spy).not.toHaveBeenCalled();564 });565 it("should not trigger any callback until load completes", function() {566 user.getAddress();567 user.getAddress({568 success: spy,569 callback: spy570 });571 expect(spy).not.toHaveBeenCalled();572 });573 it("should trigger the callbacks once loaded", function() {574 user.getAddress();575 user.getAddress({576 success: spy,577 callback: spy578 });579 complete({});580 expect(spy.callCount).toBe(2);581 });582 });583 describe("callbacks", function() {584 it("should not trigger any callbacks until the load completes", function() {585 user.getAddress(spy);586 user.getAddress({587 success: spy588 });589 user.getAddress({590 failure: spy591 });592 user.getAddress({593 callback: spy594 });595 expect(spy).not.toHaveBeenCalled();596 });597 describe("when successful", function() {598 it("should accept a function as the callback and default the scope to the model", function() {599 address = user.getAddress(spy);600 complete({});601 var call = spy.mostRecentCall;602 expect(call.args[0]).toBe(address);603 expect(call.args[1].isOperation).toBe(true);604 expect(call.args[2]).toBe(true);605 expect(call.object).toBe(user);606 });607 608 it("should accept a function with a scope", function() {609 var o = {};610 user.getAddress(spy, o);611 complete({});612 expect(spy.mostRecentCall.object).toBe(o); 613 });614 615 it("should accept an options object with success and default the scope to the model", function() {616 address = user.getAddress({617 success: spy618 }); 619 complete({});620 var call = spy.mostRecentCall; 621 expect(call.args[0]).toBe(address);622 expect(call.args[1].isOperation).toBe(true);623 expect(call.object).toBe(user); 624 });625 it("should accept an options object with success and a scope", function() {626 var o = {},627 call;628 user.getAddress({629 scope: o,630 success: spy631 }); 632 complete({});633 call = spy.mostRecentCall; 634 expect(call.object).toBe(o); 635 });636 it("should accept an options object with callback and default the scope to the model", function() {637 address = user.getAddress({638 callback: spy639 }); 640 complete({});641 var call = spy.mostRecentCall; 642 expect(call.args[0]).toBe(address);643 expect(call.args[1].isOperation).toBe(true);644 expect(call.args[2]).toBe(true);645 expect(call.object).toBe(user); 646 });647 648 it("should accept an options object with callback and a scope", function() {649 var o = {},650 call;651 user.getAddress({652 scope: o,653 callback: spy654 }); 655 complete({});656 call = spy.mostRecentCall; 657 expect(call.object).toBe(o); 658 });659 });660 describe("when failed", function() {661 it("should accept a function as the callback and default the scope to the model", function() {662 address = user.getAddress(spy);663 complete(null, 500);664 var call = spy.mostRecentCall;665 expect(call.args[0]).toBe(address);666 expect(call.args[1].isOperation).toBe(true);667 expect(call.args[2]).toBe(false);668 expect(call.object).toBe(user);669 });670 671 it("should accept a function with a scope", function() {672 var o = {};673 user.getAddress(spy, o);674 complete(null, 500);675 expect(spy.mostRecentCall.object).toBe(o); 676 });677 678 it("should accept an options object with failure and default the scope to the model", function() {679 address = user.getAddress({680 failure: spy681 }); 682 complete(null, 500);683 var call = spy.mostRecentCall; 684 expect(call.args[0]).toBe(address);685 expect(call.args[1].isOperation).toBe(true);686 expect(call.object).toBe(user); 687 });688 it("should accept an options object with failure and a scope", function() {689 var o = {},690 call;691 user.getAddress({692 scope: o,693 failure: spy694 }); 695 complete(null, 500);696 call = spy.mostRecentCall; 697 expect(call.object).toBe(o); 698 });699 it("should accept an options object with callback and default the scope to the model", function() {700 address = user.getAddress({701 callback: spy702 }); 703 complete(null, 500);704 var call = spy.mostRecentCall; 705 expect(call.args[0]).toBe(address);706 expect(call.args[1].isOperation).toBe(true);707 expect(call.args[2]).toBe(false);708 expect(call.object).toBe(user); 709 });710 711 it("should accept an options object with callback and a scope", function() {712 var o = {},713 call;714 user.getAddress({715 scope: o,716 callback: spy717 }); 718 complete(null, 500);719 call = spy.mostRecentCall; 720 expect(call.object).toBe(o); 721 });722 });723 });724 });725 });726 describe("with an already loaded instance", function() {727 beforeEach(function() {728 address = new Address({729 id: 2730 }, session);731 732 user.setAddress(address);733 });734 it("should return the same instance", function() {735 expect(user.getAddress()).toBe(address);736 });737 it("should not attempt to load", function() {738 spy = spyOn(Address.getProxy(), 'read');739 user.getAddress();740 expect(spy).not.toHaveBeenCalled();741 });742 it("should attempt to reload if called with options.reload", function() {743 spy = spyOn(Address.getProxy(), 'read').andReturn();744 user.getAddress({745 reload: true746 });747 expect(spy).toHaveBeenCalled();748 });749 it("should reload the same record when called with reload", function() {750 var result = user.getAddress({751 reload: true752 });753 expect(result).toBe(address);754 });755 describe("callbacks", function() {756 it("should call the callbacks before the function returns", function() {757 user.getAddress(spy);758 expect(spy).toHaveBeenCalled();759 spy.reset();760 user.getAddress({761 success: spy762 });763 expect(spy).toHaveBeenCalled();764 spy.reset();765 user.getAddress({766 callback: spy767 });768 expect(spy).toHaveBeenCalled();769 });770 it("should accept a function as the callback and default the scope to the model", function() {771 user.getAddress(spy);772 var call = spy.mostRecentCall;773 expect(call.args[0]).toBe(address);774 expect(call.args[1]).toBeNull();775 expect(call.args[2]).toBe(true);776 expect(call.object).toBe(user);777 });778 779 it("should accept a function with a scope", function() {780 var o = {};781 user.getAddress(spy, o);782 expect(spy.mostRecentCall.object).toBe(o); 783 });784 785 it("should accept an options object with success and default the scope to the model", function() {786 user.getAddress({787 success: spy788 }); 789 var call = spy.mostRecentCall; 790 expect(call.args[0]).toBe(address);791 expect(call.args[1]).toBeNull();792 expect(call.object).toBe(user); 793 });794 it("should accept an options object with success and a scope", function() {795 var o = {},796 call;797 user.getAddress({798 scope: o,799 success: spy800 }); 801 call = spy.mostRecentCall; 802 expect(call.object).toBe(o); 803 });804 it("should accept an options object with callback and default the scope to the model", function() {805 user.getAddress({806 callback: spy807 }); 808 var call = spy.mostRecentCall; 809 expect(call.args[0]).toBe(address);810 expect(call.args[1]).toBeNull();811 expect(call.args[2]).toBe(true);812 expect(call.object).toBe(user); 813 });814 815 it("should accept an options object with callback and a scope", function() {816 var o = {},817 call;818 user.getAddress({819 scope: o,820 callback: spy821 }); 822 call = spy.mostRecentCall; 823 expect(call.object).toBe(o); 824 });825 });826 });827 });828 829 describe("setter", function() {830 beforeEach(function() {831 user = new User({832 id: 7833 }, session);834 });835 describe("instance", function() {836 var address;837 beforeEach(function() {838 address = new Address({839 id: 3840 }, session);841 });842 describe("with nothing existing", function() {843 beforeEach(function() {844 user.setAddress(address);845 });846 it("should have the same record reference", function() {847 expect(user.getAddress()).toBe(address);848 });849 850 it("should set the underlying key value", function() {851 expect(user.get('addressId')).toBe(3); 852 });853 it("should clear the instance and foreign key when setting to null", function() {854 user.setAddress(null);855 expect(user.getAddress()).toBeNull();856 expect(user.get('addressId')).toBeNull();857 });858 });859 describe("with an existing key, but no instance", function() {860 beforeEach(function() {861 user.setAddress(1000);862 user.setAddress(address);863 });864 it("should have the new record reference", function() {865 expect(user.getAddress()).toBe(address);866 });867 it("should set the underlying key value", function() {868 expect(user.get('addressId')).toBe(3); 869 });870 it("should clear the instance and foreign key when setting to null", function() {871 user.setAddress(null);872 expect(user.getAddress()).toBeNull();873 expect(user.get('addressId')).toBeNull();874 });875 });876 describe("with an existing instance", function() {877 beforeEach(function() {878 user.setAddress(new Address({879 id: 1000880 }, session));881 user.setAddress(address);882 });883 it("should have the new record reference", function() {884 expect(user.getAddress()).toBe(address);885 });886 it("should set the underlying key value", function() {887 expect(user.get('addressId')).toBe(3); 888 });889 it("should clear the instance and foreign key when setting to null", function() {890 user.setAddress(null);891 expect(user.getAddress()).toBeNull();892 expect(user.get('addressId')).toBeNull();893 });894 });895 });896 897 describe("value", function() {898 describe("with nothing existing", function() {899 it("should set the underlying key", function() {900 user.setAddress(16);901 expect(user.get('addressId')).toBe(16); 902 });903 it("should return a new record object that loads", function() {904 user.setAddress(16);905 spy = spyOn(Address.getProxy(), 'read');906 // Reference doesn't exist, so need to grab it again here907 expect(user.getAddress().getId()).toBe(16);908 expect(spy.mostRecentCall.args[0].getId()).toBe(16);909 });910 it("should do nothing if the key is null", function() {911 user.setAddress(null);912 expect(user.getAddress()).toBeNull();913 });914 });915 describe("with an existing key, but no instance", function() {916 beforeEach(function() {917 user.setAddress(1000);918 });919 it("should set the underlying key", function() {920 user.setAddress(16);921 expect(user.get('addressId')).toBe(16); 922 });923 it("should return a new record object that loads", function() {924 user.setAddress(16);925 spy = spyOn(Address.getProxy(), 'read');926 // Reference doesn't exist, so need to grab it again here927 expect(user.getAddress().getId()).toBe(16);928 expect(spy.mostRecentCall.args[0].getId()).toBe(16);929 });930 it("should clear the key", function() {931 user.setAddress(null);932 expect(user.get('addressId')).toBeNull();933 expect(user.getAddress()).toBeNull();934 });935 });936 describe("with an existing instance", function() {937 beforeEach(function() {938 user.setAddress(new Address({939 id: 1000940 }, session));941 });942 it("should set the underlying key", function() {943 user.setAddress(16);944 expect(user.get('addressId')).toBe(16); 945 });946 it("should return a new record object that loads", function() {947 user.setAddress(16);948 spy = spyOn(Address.getProxy(), 'read');949 // Reference doesn't exist, so need to grab it again here950 expect(user.getAddress().getId()).toBe(16);951 expect(spy.mostRecentCall.args[0].getId()).toBe(16);952 });953 it("should clear the key", function() {954 user.setAddress(null);955 expect(user.get('addressId')).toBeNull();956 expect(user.getAddress()).toBeNull();957 });958 });959 });960 describe("timing", function() {961 var address, joiner, fn;962 beforeEach(function() {963 joiner = {964 afterEdit: function() {965 fn();966 }967 };968 address = new Address({969 id: 101970 }, session);971 });972 afterEach(function() {973 fn = joiner = null;974 });975 it("should have the record instances set in afterEdit", function() {976 var val;977 fn = function() {978 val = user.getAddress();979 };980 user.join(joiner);981 user.setAddress(address);982 expect(val).toBe(address);983 });984 it("should have the value cleared in afterEdit", function() {985 var val;986 user.setAddress(address);987 fn = function() {988 val = user.getAddress();989 };990 user.join(joiner);991 user.setAddress(null);992 expect(val).toBeNull();993 });994 });995 996 describe("callbacks", function() {997 it("should accept a function as the second arg, scope should default to the model", function() {998 user.setAddress(16, spy);999 complete({});1000 var call = spy.mostRecentCall;1001 expect(call.args[0]).toBe(user);1002 expect(call.object).toBe(user);1003 }); 1004 1005 it("should accept a function with a scope", function() {1006 var o = {};1007 address = user.setAddress(16, spy, o);1008 complete({});1009 expect(spy.mostRecentCall.object).toBe(o);1010 });1011 1012 describe("options object", function() {1013 var successSpy, failureSpy, callbackSpy;1014 beforeEach(function() {1015 successSpy = jasmine.createSpy();1016 failureSpy = jasmine.createSpy();1017 callbackSpy = jasmine.createSpy();1018 });1019 afterEach(function() {1020 successSpy = failureSpy = callbackSpy = null;1021 });1022 describe("on success", function() {1023 it("should call success/callback and scope should default to the model", function() {1024 user.setAddress(16, {1025 success: successSpy,1026 callback: callbackSpy,1027 failure: failureSpy1028 });1029 complete({});1030 expect(failureSpy).not.toHaveBeenCalled();1031 expect(successSpy).toHaveBeenCalled();1032 expect(callbackSpy).toHaveBeenCalled();1033 expect(successSpy.mostRecentCall.object).toBe(user);1034 expect(callbackSpy.mostRecentCall.object).toBe(user);1035 });1036 it("should use a passed scope", function() {1037 var scope = {};1038 user.setAddress(16, {1039 scope: scope,1040 success: successSpy,1041 callback: callbackSpy1042 });1043 complete({});1044 expect(successSpy.mostRecentCall.object).toBe(scope);1045 expect(callbackSpy.mostRecentCall.object).toBe(scope);1046 });1047 });1048 describe("on failure", function() {1049 it("should call failure/callback and scope should default to the model", function() {1050 user.setAddress(16, {1051 success: successSpy,1052 callback: callbackSpy,1053 failure: failureSpy1054 });1055 complete(null, 500);1056 expect(successSpy).not.toHaveBeenCalled();1057 expect(failureSpy).toHaveBeenCalled();1058 expect(callbackSpy).toHaveBeenCalled();1059 expect(failureSpy.mostRecentCall.object).toBe(user);1060 expect(callbackSpy.mostRecentCall.object).toBe(user);1061 });1062 it("should use a passed scope", function() {1063 var scope = {};1064 user.setAddress(16, {1065 scope: scope,1066 failure: failureSpy,1067 callback: callbackSpy1068 });1069 complete(null, 500);1070 expect(failureSpy.mostRecentCall.object).toBe(scope);1071 expect(callbackSpy.mostRecentCall.object).toBe(scope);1072 });1073 });1074 });1075 });1076 });1077 describe("modifying the foreign key", function() {1078 var user;1079 beforeEach(function() {1080 user = new User({1081 id: 71082 }, session);1083 });1084 it("should set the reference with no existing key", function() {1085 user.set('addressId', 44);1086 expect(user.getAddress().getId()).toBe(44);1087 });1088 it("should clear the reference when setting to null", function() {1089 address = new Address({1090 id: 31091 }, session);1092 user.setAddress(address);1093 user.set('addressId', null);1094 expect(user.address).toBeFalsy();1095 expect(user.getAddress()).toBeNull();1096 });1097 it("should change the reference for the key", function() {1098 address = new Address({1099 id: 31100 }, session);1101 user.setAddress(address);1102 1103 user.set('addressId', 123);1104 expect(user.getAddress().getId()).toBe(123);1105 });1106 if (withSession) {1107 it("should set the new reference if it exists in the session", function() {1108 address = new Address({1109 id: 31110 }, session); 1111 user.setAddress(address);1112 var other = new Address({1113 id: 101114 }, session);1115 user.set('addressId', 10);1116 var addressName = User.associations.address.getInstanceName();1117 expect(user[addressName]).toBe(other);1118 expect(user.getAddress()).toBe(other);1119 });1120 }1121 });1122 });1123 });1124 }1125 createSuite(false);1126 createSuite(true);1127 });1128 describe("dropping", function() {1129 function createSuite(withSession) {1130 var session, user, address, storeData;1131 beforeEach(function() {1132 if (withSession) {1133 session = new Ext.data.Session();1134 }1135 storeData = [{1136 id: 1,1137 address: {1138 id: 1011139 }1140 }];1141 });1142 afterEach(function() {1143 if (withSession) {1144 session.destroy();1145 session = null;1146 }1147 storeData = user = address = null;1148 });1149 function makeUser(id, addressId) {1150 var data = {1151 id: id,1152 addressId: addressId1153 };1154 // Session will be null if withSession is false1155 user = new User(data, session);1156 }1157 function makeAddress(id) {1158 // Session will be null if withSession = false1159 address = new Address({1160 id: id1161 }, session);1162 }1163 function makeStore(data) {1164 var store = new Ext.data.Store({1165 model: User,1166 // Session will be null if withSession = false1167 session: session1168 });1169 store.loadRawData(data || storeData);1170 return store;1171 }1172 describe(withSession ? "with session" : "without session", function() {1173 describe("the key holder", function() {1174 describe("inverse not loaded", function() {1175 beforeEach(function() {1176 defineUser();1177 });1178 it("should not create the the inverse record", function() {1179 makeUser(1, 101);1180 user.drop();1181 expect(addressCalled).toBe(false);1182 });1183 1184 it("should clear the foreign key", function() {1185 makeUser(1, 101);1186 user.drop();1187 expect(user.get('addressId')).toBeNull();1188 });1189 });1190 describe("inverse loaded", function() {1191 var store;1192 afterEach(function() {1193 store.destroy();1194 store = null;1195 });1196 describe("no parent/child relationship", function() {1197 beforeEach(function() {1198 defineUser();1199 store = makeStore();1200 user = store.first();1201 address = user.getAddress();1202 });1203 it("should clear the foreign key", function() {1204 user.drop();1205 expect(user.get('addressId')).toBeNull();1206 });1207 it("should not return the inverse record", function() {1208 expect(user.getAddress()).toBe(address);1209 user.drop();1210 expect(user.getAddress()).toBeNull();1211 });1212 it("should not drop the child record", function() {1213 user.drop();1214 expect(address.dropped).toBe(false);1215 });1216 it("should clear the owner on the inverse", function() {1217 user.drop();1218 expect(address.getUser()).toBeNull();1219 });1220 });1221 describe("as a parent", function() {1222 beforeEach(function() {1223 defineUser({1224 type: null,1225 child: 'Address'1226 });1227 store = makeStore();1228 user = store.first();1229 address = user.getAddress();1230 });1231 it("should clear the foreign key", function() {1232 user.drop();1233 expect(user.get('addressId')).toBeNull();1234 });1235 it("should not return the inverse record", function() {1236 expect(user.getAddress()).toBe(address);1237 user.drop();1238 expect(user.getAddress()).toBeNull();1239 });1240 describe("dropping the child", function() {1241 it("should drop the child record", function() {1242 user.drop();1243 Ext.data.Model.schema.processKeyChecks(true);1244 expect(address.dropped).toBe(true);1245 });1246 it("should clear the owner on the inverse", function() {1247 user.drop();1248 Ext.data.Model.schema.processKeyChecks(true);1249 expect(address.getUser()).toBeNull();1250 });1251 it("should drop the child when changing the foreign key", function() {1252 user.set('addressId', null);1253 Ext.data.Model.schema.processKeyChecks(true);1254 expect(address.dropped).toBe(true);1255 });1256 it("should drop the child when nulling out via the setter", function() {1257 user.setAddress(null);1258 Ext.data.Model.schema.processKeyChecks(true);1259 expect(address.dropped).toBe(true);1260 });1261 it("should drop the child when setting a new record", function() {1262 var other = new Address({1263 id: 21264 }, session);1265 user.setAddress(other);1266 Ext.data.Model.schema.processKeyChecks(true);1267 expect(address.dropped).toBe(true);1268 expect(other.dropped).toBe(false);1269 });1270 it("should drop the child when setting a new key", function() {1271 user.setAddress(2);1272 Ext.data.Model.schema.processKeyChecks(true);1273 expect(address.dropped).toBe(true);1274 });1275 if (withSession) {1276 it("should drop when the the records are not connected", function() {1277 user = new User({1278 id: 1001,1279 addressId: 50011280 }, session);1281 var address1 = new Address({1282 id: 50011283 }, session);1284 var address2 = new Address({1285 id: 50021286 }, session);1287 user.drop();1288 Ext.data.Model.schema.processKeyChecks(true);1289 expect(address1.dropped).toBe(true);1290 expect(address2.dropped).toBe(false);1291 });1292 }1293 });1294 describe("not dropping the child", function() {1295 it("should not drop the child immediately", function() {1296 user.setAddress(null);1297 expect(address.dropped).toBe(false);1298 })1299 it("should not drop the child if it has been reassigned", function() {1300 var otherUser = new User({1301 id: 51302 }, session);1303 user.setAddress(null);1304 otherUser.setAddress(address);1305 Ext.data.Model.schema.processKeyChecks(true);1306 });1307 });1308 });1309 });1310 });1311 describe("the non-key holder", function() {1312 beforeEach(function() {1313 defineUser();1314 });1315 describe("inverse not loaded", function() {1316 it("should not raise an error", function() {1317 makeAddress(101);1318 expect(function() {1319 address.drop();1320 }).not.toThrow();1321 });1322 });1323 describe("inverse loaded", function() {1324 it("should clear the owner reference", function() {1325 var store = makeStore();1326 user = store.first();1327 address = user.getAddress();1328 expect(address.getUser()).toBe(user);1329 address.drop();1330 expect(address.getUser()).toBeNull();1331 store.destroy();1332 });1333 });1334 });1335 });1336 }1337 createSuite(false);1338 createSuite(true);1339 });...

Full Screen

Full Screen

wallet-test.js

Source:wallet-test.js Github

copy

Full Screen

...61 const flags = Script.flags.STANDARD_VERIFY_FLAGS;62 const wallet = await wdb.create({63 witness64 });65 const addr = Address.fromString(wallet.getAddress('string'));66 const type = witness ? Address.types.WITNESS : Address.types.PUBKEYHASH;67 assert.strictEqual(addr.type, type);68 const src = new MTX();69 src.addInput(dummyInput());70 src.addOutput(nesting ? wallet.getNested() : wallet.getAddress(), 5460 * 2);71 src.addOutput(new Address(), 2 * 5460);72 const mtx = new MTX();73 mtx.addTX(src, 0);74 mtx.addOutput(wallet.getAddress(), 5460);75 await wallet.sign(mtx);76 const [tx, view] = mtx.commit();77 assert(tx.verify(view, flags));78}79async function testP2SH(witness, nesting) {80 const flags = Script.flags.STANDARD_VERIFY_FLAGS;81 const receive = nesting ? 'nested' : 'receive';82 const receiveDepth = nesting ? 'nestedDepth' : 'receiveDepth';83 const vector = witness ? 'witness' : 'script';84 // Create 3 2-of-3 wallets with our pubkeys as "shared keys"85 const options = {86 witness,87 type: 'multisig',88 m: 2,89 n: 390 };91 const alice = await wdb.create(options);92 const bob = await wdb.create(options);93 const carol = await wdb.create(options);94 const recipient = await wdb.create();95 await alice.addSharedKey(bob.account.accountKey);96 await alice.addSharedKey(carol.account.accountKey);97 await bob.addSharedKey(alice.account.accountKey);98 await bob.addSharedKey(carol.account.accountKey);99 await carol.addSharedKey(alice.account.accountKey);100 await carol.addSharedKey(bob.account.accountKey);101 // Our p2sh address102 const addr1 = alice.account[receive].getAddress();103 if (witness) {104 const type = nesting ? Address.types.SCRIPTHASH : Address.types.WITNESS;105 assert.strictEqual(addr1.type, type);106 } else {107 assert.strictEqual(addr1.type, Address.types.SCRIPTHASH);108 }109 assert(alice.account[receive].getAddress().equals(addr1));110 assert(bob.account[receive].getAddress().equals(addr1));111 assert(carol.account[receive].getAddress().equals(addr1));112 const nestedAddr1 = alice.getNested();113 if (witness) {114 assert(nestedAddr1);115 assert(alice.getNested().equals(nestedAddr1));116 assert(bob.getNested().equals(nestedAddr1));117 assert(carol.getNested().equals(nestedAddr1));118 }119 {120 // Add a shared unspent transaction to our wallets121 const fund = new MTX();122 fund.addInput(dummyInput());123 fund.addOutput(nesting ? nestedAddr1 : addr1, 5460 * 10);124 // Simulate a confirmation125 const block = nextBlock();126 assert.strictEqual(alice.account[receiveDepth], 1);127 await wdb.addBlock(block, [fund.toTX()]);128 assert.strictEqual(alice.account[receiveDepth], 2);129 assert.strictEqual(alice.account.changeDepth, 1);130 }131 const addr2 = alice.account[receive].getAddress();132 assert(!addr2.equals(addr1));133 assert(alice.account[receive].getAddress().equals(addr2));134 assert(bob.account[receive].getAddress().equals(addr2));135 assert(carol.account[receive].getAddress().equals(addr2));136 // Create a tx requiring 2 signatures137 const send = new MTX();138 send.addOutput(recipient.getAddress(), 5460);139 assert(!send.verify(flags));140 await alice.fund(send, {141 rate: 10000,142 round: true143 });144 await alice.sign(send);145 assert(!send.verify(flags));146 await bob.sign(send);147 const [tx, view] = send.commit();148 assert(tx.verify(view, flags));149 assert.strictEqual(alice.account.changeDepth, 1);150 const change = alice.account.change.getAddress();151 assert(alice.account.change.getAddress().equals(change));152 assert(bob.account.change.getAddress().equals(change));153 assert(carol.account.change.getAddress().equals(change));154 // Simulate a confirmation155 {156 const block = nextBlock();157 await wdb.addBlock(block, [tx]);158 assert.strictEqual(alice.account[receiveDepth], 2);159 assert.strictEqual(alice.account.changeDepth, 2);160 assert(alice.account[receive].getAddress().equals(addr2));161 assert(!alice.account.change.getAddress().equals(change));162 }163 const change2 = alice.account.change.getAddress();164 assert(alice.account.change.getAddress().equals(change2));165 assert(bob.account.change.getAddress().equals(change2));166 assert(carol.account.change.getAddress().equals(change2));167 const input = tx.inputs[0];168 input[vector].setData(2, encoding.ZERO_SIG);169 input[vector].compile();170 assert(!tx.verify(view, flags));171 assert.strictEqual(tx.getFee(view), 10000);172}173describe('Wallet', function() {174 this.timeout(5000);175 it('should open walletdb', async () => {176 consensus.COINBASE_MATURITY = 0;177 await wdb.open();178 });179 it('should generate new key and address', async () => {180 const wallet = await wdb.create();181 const addr1 = wallet.getAddress();182 assert(addr1);183 const str = addr1.toString();184 const addr2 = Address.fromString(str);185 assert(addr2.equals(addr1));186 });187 it('should validate existing address', () => {188 assert(Address.fromString('1KQ1wMNwXHUYj1nV2xzsRcKUH8gVFpTFUc'));189 });190 it('should fail to validate invalid address', () => {191 assert.throws(() => {192 Address.fromString('1KQ1wMNwXHUYj1nv2xzsRcKUH8gVFpTFUc');193 });194 });195 it('should create and get wallet', async () => {196 const wallet1 = await wdb.create();197 await wallet1.destroy();198 const wallet2 = await wdb.get(wallet1.id);199 assert(wallet1 !== wallet2);200 assert(wallet1.master !== wallet2.master);201 assert(wallet1.master.key.equals(wallet2.master.key));202 assert(wallet1.account.accountKey.equals(wallet2.account.accountKey));203 });204 it('should sign/verify p2pkh tx', async () => {205 await testP2PKH(false, false);206 });207 it('should sign/verify p2wpkh tx', async () => {208 await testP2PKH(true, false);209 });210 it('should sign/verify p2wpkh tx w/ nested bullshit', async () => {211 await testP2PKH(true, true);212 });213 it('should multisign/verify TX', async () => {214 const wallet = await wdb.create({215 type: 'multisig',216 m: 1,217 n: 2218 });219 const xpriv = HD.PrivateKey.generate();220 const key = xpriv.deriveAccount(44, 0).toPublic();221 await wallet.addSharedKey(key);222 const script = Script.fromMultisig(1, 2, [223 wallet.account.receive.getPublicKey(),224 key.derivePath('m/0/0').publicKey225 ]);226 // Input transaction (bare 1-of-2 multisig)227 const src = new MTX();228 src.addInput(dummyInput());229 src.addOutput(script, 5460 * 2);230 src.addOutput(new Address(), 5460 * 2);231 const tx = new MTX();232 tx.addTX(src, 0);233 tx.addOutput(wallet.getAddress(), 5460);234 const maxSize = await tx.estimateSize();235 await wallet.sign(tx);236 assert(tx.toRaw().length <= maxSize);237 assert(tx.verify());238 });239 it('should handle missed and invalid txs', async () => {240 const alice = await wdb.create();241 const bob = await wdb.create();242 // Coinbase243 // balance: 51000244 const t1 = new MTX();245 t1.addInput(dummyInput());246 t1.addOutput(alice.getAddress(), 50000);247 t1.addOutput(alice.getAddress(), 1000);248 const t2 = new MTX();249 t2.addTX(t1, 0); // 50000250 t2.addOutput(alice.getAddress(), 24000);251 t2.addOutput(alice.getAddress(), 24000);252 // Save for later.253 doubleSpendWallet = alice;254 doubleSpendCoin = Coin.fromTX(t1, 0, -1);255 // balance: 49000256 await alice.sign(t2);257 const t3 = new MTX();258 t3.addTX(t1, 1); // 1000259 t3.addTX(t2, 0); // 24000260 t3.addOutput(alice.getAddress(), 23000);261 // balance: 47000262 await alice.sign(t3);263 const t4 = new MTX();264 t4.addTX(t2, 1); // 24000265 t4.addTX(t3, 0); // 23000266 t4.addOutput(alice.getAddress(), 11000);267 t4.addOutput(alice.getAddress(), 11000);268 // balance: 22000269 await alice.sign(t4);270 const f1 = new MTX();271 f1.addTX(t4, 1); // 11000272 f1.addOutput(bob.getAddress(), 10000);273 // balance: 11000274 await alice.sign(f1);275 const fake = new MTX();276 fake.addTX(t1, 1); // 1000 (already redeemed)277 fake.addOutput(alice.getAddress(), 500);278 // Script inputs but do not sign279 await alice.template(fake);280 // Fake signature281 const input = fake.inputs[0];282 input.script.setData(0, encoding.ZERO_SIG);283 input.script.compile();284 // balance: 11000285 // Fake TX should temporarily change output.286 {287 await wdb.addTX(fake.toTX());288 await wdb.addTX(t4.toTX());289 const balance = await alice.getBalance();290 assert.strictEqual(balance.unconfirmed, 22500);291 }292 {293 await wdb.addTX(t1.toTX());294 const balance = await alice.getBalance();295 assert.strictEqual(balance.unconfirmed, 72500);296 }297 {298 await wdb.addTX(t2.toTX());299 const balance = await alice.getBalance();300 assert.strictEqual(balance.unconfirmed, 46500);301 }302 {303 await wdb.addTX(t3.toTX());304 const balance = await alice.getBalance();305 assert.strictEqual(balance.unconfirmed, 22000);306 }307 {308 await wdb.addTX(f1.toTX());309 const balance = await alice.getBalance();310 assert.strictEqual(balance.unconfirmed, 11000);311 const txs = await alice.getHistory();312 assert(txs.some((wtx) => {313 return wtx.hash === f1.hash('hex');314 }));315 }316 {317 const balance = await bob.getBalance();318 assert.strictEqual(balance.unconfirmed, 10000);319 const txs = await bob.getHistory();320 assert(txs.some((wtx) => {321 return wtx.tx.hash('hex') === f1.hash('hex');322 }));323 }324 });325 it('should cleanup spenders after double-spend', async () => {326 const wallet = doubleSpendWallet;327 {328 const txs = await wallet.getHistory();329 assert.strictEqual(txs.length, 5);330 const total = txs.reduce((t, wtx) => {331 return t + wtx.tx.getOutputValue();332 }, 0);333 assert.strictEqual(total, 154000);334 }335 {336 const balance = await wallet.getBalance();337 assert.strictEqual(balance.unconfirmed, 11000);338 }339 {340 const tx = new MTX();341 tx.addCoin(doubleSpendCoin);342 tx.addOutput(wallet.getAddress(), 5000);343 await wallet.sign(tx);344 await wdb.addTX(tx.toTX());345 const balance = await wallet.getBalance();346 assert.strictEqual(balance.unconfirmed, 6000);347 }348 {349 const txs = await wallet.getHistory();350 assert.strictEqual(txs.length, 2);351 const total = txs.reduce((t, wtx) => {352 return t + wtx.tx.getOutputValue();353 }, 0);354 assert.strictEqual(total, 56000);355 }356 });357 it('should handle missed txs without resolution', async () => {358 const wdb = new WalletDB({359 name: 'wallet-test',360 db: 'memory',361 verify: false362 });363 await wdb.open();364 const alice = await wdb.create();365 const bob = await wdb.create();366 // Coinbase367 const t1 = new MTX();368 t1.addInput(dummyInput());369 t1.addOutput(alice.getAddress(), 50000);370 t1.addOutput(alice.getAddress(), 1000);371 // balance: 51000372 const t2 = new MTX();373 t2.addTX(t1, 0); // 50000374 t2.addOutput(alice.getAddress(), 24000);375 t2.addOutput(alice.getAddress(), 24000);376 // balance: 49000377 await alice.sign(t2);378 const t3 = new MTX();379 t3.addTX(t1, 1); // 1000380 t3.addTX(t2, 0); // 24000381 t3.addOutput(alice.getAddress(), 23000);382 // balance: 47000383 await alice.sign(t3);384 const t4 = new MTX();385 t4.addTX(t2, 1); // 24000386 t4.addTX(t3, 0); // 23000387 t4.addOutput(alice.getAddress(), 11000);388 t4.addOutput(alice.getAddress(), 11000);389 // balance: 22000390 await alice.sign(t4);391 const f1 = new MTX();392 f1.addTX(t4, 1); // 11000393 f1.addOutput(bob.getAddress(), 10000);394 // balance: 11000395 await alice.sign(f1);396 {397 await wdb.addTX(t4.toTX());398 const balance = await alice.getBalance();399 assert.strictEqual(balance.unconfirmed, 22000);400 }401 {402 await wdb.addTX(t1.toTX());403 const balance = await alice.getBalance();404 assert.strictEqual(balance.unconfirmed, 73000);405 }406 {407 await wdb.addTX(t2.toTX());408 const balance = await alice.getBalance();409 assert.strictEqual(balance.unconfirmed, 47000);410 }411 {412 await wdb.addTX(t3.toTX());413 const balance = await alice.getBalance();414 assert.strictEqual(balance.unconfirmed, 22000);415 }416 {417 await wdb.addTX(f1.toTX());418 const balance = await alice.getBalance();419 assert.strictEqual(balance.unconfirmed, 11000);420 const txs = await alice.getHistory();421 assert(txs.some((wtx) => {422 return wtx.tx.hash('hex') === f1.hash('hex');423 }));424 }425 {426 const balance = await bob.getBalance();427 assert.strictEqual(balance.unconfirmed, 10000);428 const txs = await bob.getHistory();429 assert(txs.some((wtx) => {430 return wtx.tx.hash('hex') === f1.hash('hex');431 }));432 }433 await wdb.addTX(t2.toTX());434 await wdb.addTX(t3.toTX());435 await wdb.addTX(t4.toTX());436 await wdb.addTX(f1.toTX());437 {438 const balance = await alice.getBalance();439 assert.strictEqual(balance.unconfirmed, 11000);440 }441 {442 const balance = await bob.getBalance();443 assert.strictEqual(balance.unconfirmed, 10000);444 }445 });446 it('should fill tx with inputs', async () => {447 const alice = await wdb.create();448 const bob = await wdb.create();449 // Coinbase450 const t1 = new MTX();451 t1.addInput(dummyInput());452 t1.addOutput(alice.getAddress(), 5460);453 t1.addOutput(alice.getAddress(), 5460);454 t1.addOutput(alice.getAddress(), 5460);455 t1.addOutput(alice.getAddress(), 5460);456 await wdb.addTX(t1.toTX());457 // Create new transaction458 const m2 = new MTX();459 m2.addOutput(bob.getAddress(), 5460);460 await alice.fund(m2, {461 rate: 10000,462 round: true463 });464 await alice.sign(m2);465 const [t2, v2] = m2.commit();466 assert(t2.verify(v2));467 assert.strictEqual(t2.getInputValue(v2), 16380);468 assert.strictEqual(t2.getOutputValue(), 6380);469 assert.strictEqual(t2.getFee(v2), 10000);470 // Create new transaction471 const t3 = new MTX();472 t3.addOutput(bob.getAddress(), 15000);473 let err;474 try {475 await alice.fund(t3, {476 rate: 10000,477 round: true478 });479 } catch (e) {480 err = e;481 }482 assert(err);483 assert.strictEqual(err.requiredFunds, 25000);484 });485 it('should fill tx with inputs with accurate fee', async () => {486 const alice = await wdb.create({487 master: KEY1488 });489 const bob = await wdb.create({490 master: KEY2491 });492 // Coinbase493 const t1 = new MTX();494 t1.addOutpoint(new Outpoint(encoding.NULL_HASH, 0));495 t1.addOutput(alice.getAddress(), 5460);496 t1.addOutput(alice.getAddress(), 5460);497 t1.addOutput(alice.getAddress(), 5460);498 t1.addOutput(alice.getAddress(), 5460);499 await wdb.addTX(t1.toTX());500 // Create new transaction501 const m2 = new MTX();502 m2.addOutput(bob.getAddress(), 5460);503 await alice.fund(m2, {504 rate: 10000505 });506 await alice.sign(m2);507 const [t2, v2] = m2.commit();508 assert(t2.verify(v2));509 assert.strictEqual(t2.getInputValue(v2), 16380);510 // Should now have a change output:511 assert.strictEqual(t2.getOutputValue(), 11130);512 assert.strictEqual(t2.getFee(v2), 5250);513 assert.strictEqual(t2.getWeight(), 2084);514 assert.strictEqual(t2.getBaseSize(), 521);515 assert.strictEqual(t2.getSize(), 521);516 assert.strictEqual(t2.getVirtualSize(), 521);517 let balance;518 bob.once('balance', (b) => {519 balance = b;520 });521 await wdb.addTX(t2);522 // Create new transaction523 const t3 = new MTX();524 t3.addOutput(bob.getAddress(), 15000);525 let err;526 try {527 await alice.fund(t3, {528 rate: 10000529 });530 } catch (e) {531 err = e;532 }533 assert(err);534 assert(balance);535 assert.strictEqual(balance.unconfirmed, 5460);536 });537 it('should sign multiple inputs using different keys', async () => {538 const alice = await wdb.create();539 const bob = await wdb.create();540 const carol = await wdb.create();541 // Coinbase542 const t1 = new MTX();543 t1.addInput(dummyInput());544 t1.addOutput(alice.getAddress(), 5460);545 t1.addOutput(alice.getAddress(), 5460);546 t1.addOutput(alice.getAddress(), 5460);547 t1.addOutput(alice.getAddress(), 5460);548 // Coinbase549 const t2 = new MTX();550 t2.addInput(dummyInput());551 t2.addOutput(bob.getAddress(), 5460);552 t2.addOutput(bob.getAddress(), 5460);553 t2.addOutput(bob.getAddress(), 5460);554 t2.addOutput(bob.getAddress(), 5460);555 await wdb.addTX(t1.toTX());556 await wdb.addTX(t2.toTX());557 // Create our tx with an output558 const tx = new MTX();559 tx.addOutput(carol.getAddress(), 5460);560 const coins1 = await alice.getCoins();561 const coins2 = await bob.getCoins();562 // Add our unspent inputs to sign563 tx.addCoin(coins1[0]);564 tx.addCoin(coins1[1]);565 tx.addCoin(coins2[0]);566 // Sign transaction567 assert.strictEqual(await alice.sign(tx), 2);568 assert.strictEqual(await bob.sign(tx), 1);569 // Verify570 assert.strictEqual(tx.verify(), true);571 tx.inputs.length = 0;572 tx.addCoin(coins1[1]);573 tx.addCoin(coins1[2]);574 tx.addCoin(coins2[1]);575 assert.strictEqual(await alice.sign(tx), 2);576 assert.strictEqual(await bob.sign(tx), 1);577 // Verify578 assert.strictEqual(tx.verify(), true);579 });580 it('should verify 2-of-3 p2sh tx', async () => {581 await testP2SH(false, false);582 });583 it('should verify 2-of-3 p2wsh tx', async () => {584 await testP2SH(true, false);585 });586 it('should verify 2-of-3 p2wsh tx w/ nested bullshit', async () => {587 await testP2SH(true, true);588 });589 it('should fill tx with account 1', async () => {590 const alice = await wdb.create();591 const bob = await wdb.create();592 {593 const account = await alice.createAccount({594 name: 'foo'595 });596 assert.strictEqual(account.name, 'foo');597 assert.strictEqual(account.accountIndex, 1);598 }599 const account = await alice.getAccount('foo');600 assert.strictEqual(account.name, 'foo');601 assert.strictEqual(account.accountIndex, 1);602 // Coinbase603 const t1 = new MTX();604 t1.addInput(dummyInput());605 t1.addOutput(account.receive.getAddress(), 5460);606 t1.addOutput(account.receive.getAddress(), 5460);607 t1.addOutput(account.receive.getAddress(), 5460);608 t1.addOutput(account.receive.getAddress(), 5460);609 await wdb.addTX(t1.toTX());610 // Create new transaction611 const t2 = new MTX();612 t2.addOutput(bob.getAddress(), 5460);613 await alice.fund(t2, {614 rate: 10000,615 round: true616 });617 await alice.sign(t2);618 assert(t2.verify());619 assert.strictEqual(t2.getInputValue(), 16380);620 assert.strictEqual(t2.getOutputValue(), 6380);621 assert.strictEqual(t2.getFee(), 10000);622 // Create new transaction623 const t3 = new MTX();624 t3.addOutput(bob.getAddress(), 15000);625 let err;626 try {627 await alice.fund(t3, {628 rate: 10000,629 round: true630 });631 } catch (e) {632 err = e;633 }634 assert(err);635 assert.strictEqual(err.requiredFunds, 25000);636 const accounts = await alice.getAccounts();637 assert.deepStrictEqual(accounts, ['default', 'foo']);638 });639 it('should fail to fill tx with account 1', async () => {640 const wallet = await wdb.create();641 {642 const account = await wallet.createAccount({643 name: 'foo'644 });645 assert.strictEqual(account.name, 'foo');646 assert.strictEqual(account.accountIndex, 1);647 }648 const account = await wallet.getAccount('foo');649 assert.strictEqual(account.name, 'foo');650 assert.strictEqual(account.accountIndex, 1);651 assert.strictEqual(wallet.account.accountIndex, 0);652 assert(!account.receive.getAddress().equals(653 wallet.account.receive.getAddress()));654 assert(wallet.getAddress().equals(wallet.account.receive.getAddress()));655 // Coinbase656 const t1 = new MTX();657 t1.addInput(dummyInput());658 t1.addOutput(wallet.getAddress(), 5460);659 t1.addOutput(wallet.getAddress(), 5460);660 t1.addOutput(wallet.getAddress(), 5460);661 t1.addOutput(account.receive.getAddress(), 5460);662 await wdb.addTX(t1.toTX());663 // Should fill from `foo` and fail664 const t2 = new MTX();665 t2.addOutput(wallet.getAddress(), 5460);666 let err;667 try {668 await wallet.fund(t2, {669 rate: 10000,670 round: true,671 account: 'foo'672 });673 } catch (e) {674 err = e;675 }676 assert(err);677 // Should fill from whole wallet and succeed678 const t3 = new MTX();679 t3.addOutput(wallet.getAddress(), 5460);680 await wallet.fund(t3, {681 rate: 10000,682 round: true683 });684 // Coinbase685 const t4 = new MTX();686 t4.addInput(dummyInput());687 t4.addOutput(account.receive.getAddress(), 5460);688 t4.addOutput(account.receive.getAddress(), 5460);689 t4.addOutput(account.receive.getAddress(), 5460);690 await wdb.addTX(t4.toTX());691 // Should fill from `foo` and succeed692 const t5 = new MTX();693 t5.addOutput(wallet.getAddress(), 5460);694 await wallet.fund(t5, {695 rate: 10000,696 round: true,697 account: 'foo'698 });699 currentWallet = wallet;700 });701 it('should create two accounts (multiple encryption)', async () => {702 {703 const wallet = await wdb.create({704 id: 'foobar',705 passphrase: 'foo'706 });707 await wallet.destroy();708 }709 const wallet = await wdb.get('foobar');710 assert(wallet);711 const options = {712 name: 'foo1'713 };714 const account = await wallet.createAccount(options, 'foo');715 assert(account);716 await wallet.lock();717 });718 it('should fill tx with inputs when encrypted', async () => {719 const wallet = await wdb.create({720 passphrase: 'foo'721 });722 wallet.master.stop();723 wallet.master.key = null;724 // Coinbase725 const t1 = new MTX();726 t1.addInput(dummyInput());727 t1.addOutput(wallet.getAddress(), 5460);728 t1.addOutput(wallet.getAddress(), 5460);729 t1.addOutput(wallet.getAddress(), 5460);730 t1.addOutput(wallet.getAddress(), 5460);731 await wdb.addTX(t1.toTX());732 // Create new transaction733 const t2 = new MTX();734 t2.addOutput(wallet.getAddress(), 5460);735 await wallet.fund(t2, {736 rate: 10000,737 round: true738 });739 // Should fail740 let err;741 try {742 await wallet.sign(t2, 'bar');743 } catch (e) {744 err = e;745 }746 assert(err);747 assert(!t2.verify());748 // Should succeed749 await wallet.sign(t2, 'foo');750 assert(t2.verify());751 });752 it('should fill tx with inputs with subtract fee (1)', async () => {753 const alice = await wdb.create();754 const bob = await wdb.create();755 // Coinbase756 const t1 = new MTX();757 t1.addInput(dummyInput());758 t1.addOutput(alice.getAddress(), 5460);759 t1.addOutput(alice.getAddress(), 5460);760 t1.addOutput(alice.getAddress(), 5460);761 t1.addOutput(alice.getAddress(), 5460);762 await wdb.addTX(t1.toTX());763 // Create new transaction764 const t2 = new MTX();765 t2.addOutput(bob.getAddress(), 21840);766 await alice.fund(t2, {767 rate: 10000,768 round: true,769 subtractFee: true770 });771 await alice.sign(t2);772 assert(t2.verify());773 assert.strictEqual(t2.getInputValue(), 5460 * 4);774 assert.strictEqual(t2.getOutputValue(), 21840 - 10000);775 assert.strictEqual(t2.getFee(), 10000);776 });777 it('should fill tx with inputs with subtract fee (2)', async () => {778 const alice = await wdb.create();779 const bob = await wdb.create();780 // Coinbase781 const t1 = new MTX();782 t1.addInput(dummyInput());783 t1.addOutput(alice.getAddress(), 5460);784 t1.addOutput(alice.getAddress(), 5460);785 t1.addOutput(alice.getAddress(), 5460);786 t1.addOutput(alice.getAddress(), 5460);787 await wdb.addTX(t1.toTX());788 const options = {789 subtractFee: true,790 rate: 10000,791 round: true,792 outputs: [{ address: bob.getAddress(), value: 21840 }]793 };794 // Create new transaction795 const t2 = await alice.createTX(options);796 await alice.sign(t2);797 assert(t2.verify());798 assert.strictEqual(t2.getInputValue(), 5460 * 4);799 assert.strictEqual(t2.getOutputValue(), 21840 - 10000);800 assert.strictEqual(t2.getFee(), 10000);801 });802 it('should fill tx with smart coin selection', async () => {803 const alice = await wdb.create();804 const bob = await wdb.create();805 // Coinbase806 const t1 = new MTX();807 t1.addInput(dummyInput());808 t1.addOutput(alice.getAddress(), 5460);809 t1.addOutput(alice.getAddress(), 5460);810 t1.addOutput(alice.getAddress(), 5460);811 t1.addOutput(alice.getAddress(), 5460);812 await wdb.addTX(t1.toTX());813 // Coinbase814 const t2 = new MTX();815 t2.addInput(dummyInput());816 t2.addOutput(alice.getAddress(), 5460);817 t2.addOutput(alice.getAddress(), 5460);818 t2.addOutput(alice.getAddress(), 5460);819 t2.addOutput(alice.getAddress(), 5460);820 const block = nextBlock();821 await wdb.addBlock(block, [t2.toTX()]);822 {823 const coins = await alice.getSmartCoins();824 assert.strictEqual(coins.length, 4);825 for (let i = 0; i < coins.length; i++) {826 const coin = coins[i];827 assert.strictEqual(coin.height, block.height);828 }829 }830 // Create a change output for ourselves.831 await alice.send({832 subtractFee: true,833 rate: 1000,834 depth: 1,835 outputs: [{ address: bob.getAddress(), value: 1461 }]836 });837 const coins = await alice.getSmartCoins();838 assert.strictEqual(coins.length, 4);839 let total = 0;840 {841 let found = false;842 for (let i = 0; i < coins.length; i++) {843 const coin = coins[i];844 if (coin.height === -1) {845 assert(!found);846 assert(coin.value < 5460);847 found = true;848 } else {849 assert.strictEqual(coin.height, block.height);850 }851 total += coin.value;852 }853 assert(found);854 }855 // Use smart selection856 const options = {857 subtractFee: true,858 smart: true,859 rate: 10000,860 outputs: [{861 address: bob.getAddress(),862 value: total863 }]864 };865 const t3 = await alice.createTX(options);866 assert.strictEqual(t3.inputs.length, 4);867 {868 let found = false;869 for (let i = 0; i < t3.inputs.length; i++) {870 const coin = t3.view.getCoinFor(t3.inputs[i]);871 if (coin.height === -1) {872 assert(!found);873 assert(coin.value < 5460);874 found = true;875 } else {876 assert.strictEqual(coin.height, block.height);877 }878 }879 assert(found);880 }881 await alice.sign(t3);882 assert(t3.verify());883 });884 it('should get range of txs', async () => {885 const wallet = currentWallet;886 const txs = await wallet.getRange({887 start: util.now() - 1000888 });889 assert.strictEqual(txs.length, 2);890 });891 it('should get range of txs from account', async () => {892 const wallet = currentWallet;893 const txs = await wallet.getRange('foo', {894 start: util.now() - 1000895 });896 assert.strictEqual(txs.length, 2);897 });898 it('should not get range of txs from non-existent account', async () => {899 const wallet = currentWallet;900 let txs, err;901 try {902 txs = await wallet.getRange('bad', {903 start: 0xdeadbeef - 1000904 });905 } catch (e) {906 err = e;907 }908 assert(!txs);909 assert(err);910 assert.strictEqual(err.message, 'Account not found.');911 });912 it('should get account balance', async () => {913 const wallet = currentWallet;914 const balance = await wallet.getBalance('foo');915 assert.strictEqual(balance.unconfirmed, 21840);916 });917 it('should import privkey', async () => {918 const key = KeyRing.generate();919 const wallet = await wdb.create({920 passphrase: 'test'921 });922 await wallet.importKey('default', key, 'test');923 const wkey = await wallet.getKey(key.getHash('hex'));924 assert.strictEqual(wkey.getHash('hex'), key.getHash('hex'));925 // Coinbase926 const t1 = new MTX();927 t1.addOutput(key.getAddress(), 5460);928 t1.addOutput(key.getAddress(), 5460);929 t1.addOutput(key.getAddress(), 5460);930 t1.addOutput(key.getAddress(), 5460);931 t1.addInput(dummyInput());932 await wdb.addTX(t1.toTX());933 const wtx = await wallet.getTX(t1.hash('hex'));934 assert(wtx);935 assert.strictEqual(t1.hash('hex'), wtx.hash);936 const options = {937 rate: 10000,938 round: true,939 outputs: [{940 address: wallet.getAddress(),941 value: 7000942 }]943 };944 // Create new transaction945 const t2 = await wallet.createTX(options);946 await wallet.sign(t2);947 assert(t2.verify());948 assert.strictEqual(t2.inputs[0].prevout.hash, wtx.hash);949 importedWallet = wallet;950 importedKey = key;951 });952 it('should import pubkey', async () => {953 const key = KeyRing.generate();954 const pub = new KeyRing(key.publicKey);955 const wallet = await wdb.create({956 watchOnly: true957 });958 await wallet.importKey('default', pub);959 const path = await wallet.getPath(pub.getHash('hex'));960 assert.strictEqual(path.hash, pub.getHash('hex'));961 const wkey = await wallet.getKey(pub.getHash('hex'));962 assert(wkey);963 });964 it('should import address', async () => {965 const key = KeyRing.generate();966 const wallet = await wdb.create({967 watchOnly: true968 });969 await wallet.importAddress('default', key.getAddress());970 const path = await wallet.getPath(key.getHash('hex'));971 assert(path);972 assert.strictEqual(path.hash, key.getHash('hex'));973 const wkey = await wallet.getKey(key.getHash('hex'));974 assert(!wkey);975 });976 it('should get details', async () => {977 const wallet = currentWallet;978 const txs = await wallet.getRange('foo', {979 start: util.now() - 1000980 });981 const details = await wallet.toDetails(txs);982 assert(details.some((tx) => {983 return tx.toJSON().outputs[0].path.name === 'foo';984 }));985 });986 it('should rename wallet', async () => {987 const wallet = currentWallet;988 await wallet.rename('test');989 const txs = await wallet.getRange('foo', {990 start: util.now() - 1000991 });992 const details = await wallet.toDetails(txs);993 assert.strictEqual(details[0].toJSON().id, 'test');994 });995 it('should change passphrase with encrypted imports', async () => {996 const wallet = importedWallet;997 const addr = importedKey.getAddress();998 assert(wallet.master.encrypted);999 let data;1000 {1001 const path = await wallet.getPath(addr);1002 assert(path);1003 assert(path.data && path.encrypted);1004 data = path.data;1005 }1006 await wallet.decrypt('test');1007 {1008 const path = await wallet.getPath(addr);1009 assert(path);1010 assert(path.data && !path.encrypted);1011 assert(await wallet.getKey(addr));1012 }1013 await wallet.encrypt('foo');1014 {1015 const path = await wallet.getPath(addr);1016 assert(path);1017 assert(path.data && path.encrypted);1018 assert(!data.equals(path.data));1019 assert(!await wallet.getKey(addr));1020 }1021 await wallet.unlock('foo');1022 const key = await wallet.getKey(addr);1023 assert(key);1024 assert.strictEqual(key.getHash('hex'), addr.getHash('hex'));1025 });1026 it('should recover from a missed tx', async () => {1027 const wdb = new WalletDB({1028 name: 'wallet-test',1029 db: 'memory',1030 verify: false1031 });1032 await wdb.open();1033 const alice = await wdb.create({1034 master: KEY11035 });1036 const bob = await wdb.create({1037 master: KEY11038 });1039 const addr = alice.getAddress();1040 // Coinbase1041 const t1 = new MTX();1042 t1.addInput(dummyInput());1043 t1.addOutput(addr, 50000);1044 await alice.add(t1.toTX());1045 await bob.add(t1.toTX());1046 // Bob misses this tx!1047 const t2 = new MTX();1048 t2.addTX(t1, 0);1049 t2.addOutput(addr, 24000);1050 t2.addOutput(addr, 24000);1051 await alice.sign(t2);1052 await alice.add(t2.toTX());1053 assert.notStrictEqual(1054 (await alice.getBalance()).unconfirmed,1055 (await bob.getBalance()).unconfirmed);1056 // Bob sees this one.1057 const t3 = new MTX();1058 t3.addTX(t2, 0);1059 t3.addTX(t2, 1);1060 t3.addOutput(addr, 30000);1061 await alice.sign(t3);1062 assert.strictEqual((await bob.getBalance()).unconfirmed, 50000);1063 await alice.add(t3.toTX());1064 await bob.add(t3.toTX());1065 assert.strictEqual((await alice.getBalance()).unconfirmed, 30000);1066 // Bob sees t2 on the chain.1067 await bob.add(t2.toTX());1068 // Bob sees t3 on the chain.1069 await bob.add(t3.toTX());1070 assert.strictEqual((await bob.getBalance()).unconfirmed, 30000);1071 });1072 it('should recover from a missed tx and double spend', async () => {1073 const wdb = new WalletDB({1074 name: 'wallet-test',1075 db: 'memory',1076 verify: false1077 });1078 await wdb.open();1079 const alice = await wdb.create({1080 master: KEY11081 });1082 const bob = await wdb.create({1083 master: KEY11084 });1085 const addr = alice.getAddress();1086 // Coinbase1087 const t1 = new MTX();1088 t1.addInput(dummyInput());1089 t1.addOutput(addr, 50000);1090 await alice.add(t1.toTX());1091 await bob.add(t1.toTX());1092 // Bob misses this tx!1093 const t2a = new MTX();1094 t2a.addTX(t1, 0);1095 t2a.addOutput(addr, 24000);1096 t2a.addOutput(addr, 24000);1097 await alice.sign(t2a);1098 await alice.add(t2a.toTX());1099 assert.notStrictEqual(...

Full Screen

Full Screen

initializeContracts.js

Source:initializeContracts.js Github

copy

Full Screen

...107 }108 // testnet only!109 if (110 contracts.indexOf('Dispenser') > -1 &&111 getAddress('Token')112 ) {113 addressBook.Dispenser = await zosCreate({114 contract: 'Dispenser',115 ctx,116 args: [117 getAddress('Token'),118 roles.ownerWallet119 ],120 verbose121 })122 }123 if (contracts.indexOf('ConditionStoreManager') > -1) {124 addressBook.ConditionStoreManager = await zosCreate({125 contract: 'ConditionStoreManager',126 ctx,127 libraries: { EpochLibrary: epochLibrary },128 args: [roles.deployer, roles.deployer],129 verbose130 })131 }132 if (contracts.indexOf('PlonkVerifier') > -1) {133 proxies.PlonkVerifier = await deployLibrary('PlonkVerifier', addresses, cache)134 }135 if (contracts.indexOf('TemplateStoreManager') > -1) {136 addressBook.TemplateStoreManager = await zosCreate({137 contract: 'TemplateStoreManager',138 ctx,139 args: [roles.deployer],140 verbose141 })142 }143 if (getAddress('ConditionStoreManager')) {144 if (contracts.indexOf('EscrowPaymentCondition') > -1) {145 addressBook.EscrowPaymentCondition = await zosCreate({146 contract: 'EscrowPaymentCondition',147 ctx,148 args: [149 roles.ownerWallet,150 getAddress('ConditionStoreManager')151 ],152 verbose153 })154 }155 if (contracts.indexOf('SignCondition') > -1) {156 addressBook.SignCondition = await zosCreate({157 contract: 'SignCondition',158 ctx,159 args: [160 roles.ownerWallet,161 getAddress('ConditionStoreManager')162 ],163 verbose164 })165 }166 if (contracts.indexOf('HashLockCondition') > -1) {167 addressBook.HashLockCondition = await zosCreate({168 contract: 'HashLockCondition',169 ctx,170 args: [171 roles.ownerWallet,172 getAddress('ConditionStoreManager')173 ],174 verbose175 })176 }177 if (contracts.indexOf('ThresholdCondition') > -1) {178 addressBook.ThresholdCondition = await zosCreate({179 contract: 'ThresholdCondition',180 ctx,181 args: [182 roles.ownerWallet,183 getAddress('ConditionStoreManager')184 ],185 verbose186 })187 }188 if (contracts.indexOf('WhitelistingCondition') > -1) {189 addressBook.WhitelistingCondition = await zosCreate({190 contract: 'WhitelistingCondition',191 ctx,192 args: [193 roles.ownerWallet,194 getAddress('ConditionStoreManager')195 ],196 verbose197 })198 }199 if (contracts.indexOf('NFT721HolderCondition') > -1) {200 addressBook.NFT721HolderCondition = await zosCreate({201 contract: 'NFT721HolderCondition',202 ctx,203 args: [204 roles.ownerWallet,205 getAddress('ConditionStoreManager')206 ],207 verbose208 })209 }210 if (contracts.indexOf('NFT721LockCondition') > -1) {211 addressBook.NFT721LockCondition = await zosCreate({212 contract: 'NFT721LockCondition',213 ctx,214 args: [215 roles.ownerWallet,216 getAddress('ConditionStoreManager')217 ],218 verbose219 })220 }221 if (contracts.indexOf('AaveBorrowCondition') > -1) {222 addressBook.AaveBorrowCondition = await zosCreate({223 contract: 'AaveBorrowCondition',224 ctx,225 args: [226 roles.ownerWallet,227 getAddress('ConditionStoreManager')228 ],229 verbose230 })231 }232 if (contracts.indexOf('AaveCollateralDepositCondition') > -1) {233 addressBook.AaveCollateralDepositCondition = await zosCreate({234 contract: 'AaveCollateralDepositCondition',235 ctx,236 args: [237 roles.ownerWallet,238 getAddress('ConditionStoreManager')239 ],240 verbose241 })242 }243 if (contracts.indexOf('AaveCollateralWithdrawCondition') > -1) {244 addressBook.AaveCollateralWithdrawCondition = await zosCreate({245 contract: 'AaveCollateralWithdrawCondition',246 ctx,247 args: [248 roles.ownerWallet,249 getAddress('ConditionStoreManager')250 ],251 verbose252 })253 }254 if (contracts.indexOf('AaveRepayCondition') > -1) {255 addressBook.AaveRepayCondition = await zosCreate({256 contract: 'AaveRepayCondition',257 ctx,258 args: [259 roles.ownerWallet,260 getAddress('ConditionStoreManager')261 ],262 verbose263 })264 }265 }266 if (getAddress('ConditionStoreManager') &&267 getAddress('TemplateStoreManager') &&268 getAddress('DIDRegistry')) {269 if (contracts.indexOf('AgreementStoreManager') > -1) {270 addressBook.AgreementStoreManager = await zosCreate({271 contract: 'AgreementStoreManager',272 ctx,273 args: [274 roles.deployer,275 getAddress('ConditionStoreManager'),276 getAddress('TemplateStoreManager'),277 getAddress('DIDRegistry')278 ],279 verbose280 })281 }282 }283 if (getAddress('ConditionStoreManager') &&284 getAddress('DIDRegistry')) {285 if (contracts.indexOf('LockPaymentCondition') > -1) {286 addressBook.LockPaymentCondition = await zosCreate({287 contract: 'LockPaymentCondition',288 ctx,289 args: [290 roles.deployer,291 getAddress('ConditionStoreManager'),292 getAddress('DIDRegistry')293 ],294 verbose295 })296 }297 if (contracts.indexOf('TransferDIDOwnershipCondition') > -1) {298 addressBook.TransferDIDOwnershipCondition = await zosCreate({299 contract: 'TransferDIDOwnershipCondition',300 ctx,301 args: [302 roles.ownerWallet,303 getAddress('ConditionStoreManager'),304 getAddress('DIDRegistry')305 ],306 verbose307 })308 }309 if (contracts.indexOf('NFTAccessCondition') > -1) {310 addressBook.NFTAccessCondition = await zosCreate({311 contract: 'NFTAccessCondition',312 ctx,313 args: [314 roles.ownerWallet,315 getAddress('ConditionStoreManager'),316 getAddress('DIDRegistry')317 ],318 verbose319 })320 }321 if (getAddress('PlonkVerifier') && contracts.indexOf('AccessProofCondition') > -1) {322 addressBook.AccessProofCondition = await zosCreate({323 contract: 'AccessProofCondition',324 ctx,325 args: [326 roles.ownerWallet,327 getAddress('ConditionStoreManager'),328 getAddress('DIDRegistry'),329 getAddress('PlonkVerifier')330 ],331 verbose332 })333 }334 }335 if (getAddress('ConditionStoreManager') &&336 getAddress('NFTUpgradeable')) {337 if (contracts.indexOf('NFTHolderCondition') > -1) {338 addressBook.NFTHolderCondition = await zosCreate({339 contract: 'NFTHolderCondition',340 ctx,341 args: [342 roles.ownerWallet,343 getAddress('ConditionStoreManager'),344 getAddress('NFTUpgradeable')345 ],346 verbose347 })348 }349 if (contracts.indexOf('TransferNFTCondition') > -1) {350 addressBook.TransferNFTCondition = await zosCreate({351 contract: 'TransferNFTCondition',352 ctx,353 args: [354 roles.ownerWallet,355 getAddress('ConditionStoreManager'),356 getAddress('NFTUpgradeable'),357 ZeroAddress358 ],359 verbose360 })361 }362 if (contracts.indexOf('NFTLockCondition') > -1) {363 addressBook.NFTLockCondition = await zosCreate({364 contract: 'NFTLockCondition',365 ctx,366 args: [367 roles.ownerWallet,368 getAddress('ConditionStoreManager'),369 getAddress('NFTUpgradeable')370 ],371 verbose372 })373 }374 }375 if (getAddress('ConditionStoreManager') &&376 getAddress('AgreementStoreManager')) {377 if (contracts.indexOf('AccessCondition') > -1) {378 addressBook.AccessCondition = await zosCreate({379 contract: 'AccessCondition',380 ctx,381 args: [382 roles.ownerWallet,383 getAddress('ConditionStoreManager'),384 getAddress('AgreementStoreManager')385 ],386 verbose387 })388 }389 if (contracts.indexOf('ComputeExecutionCondition') > -1) {390 addressBook.ComputeExecutionCondition = await zosCreate({391 contract: 'ComputeExecutionCondition',392 ctx,393 args: [394 roles.ownerWallet,395 getAddress('ConditionStoreManager'),396 getAddress('AgreementStoreManager')397 ],398 verbose399 })400 }401 }402 if (getAddress('ConditionStoreManager') &&403 getAddress('NFT721Upgradeable') &&404 getAddress('LockPaymentCondition')) {405 if (contracts.indexOf('TransferNFT721Condition') > -1) {406 addressBook.TransferNFT721Condition = await zosCreate({407 contract: 'TransferNFT721Condition',408 ctx,409 args: [410 roles.ownerWallet,411 getAddress('ConditionStoreManager'),412 getAddress('NFT721Upgradeable'),413 getAddress('LockPaymentCondition')414 ],415 verbose416 })417 }418 }419 if (getAddress('ConditionStoreManager') &&420 getAddress('NFT721LockCondition')) {421 if (contracts.indexOf('DistributeNFTCollateralCondition') > -1) {422 addressBook.DistributeNFTCollateralCondition = await zosCreate({423 contract: 'DistributeNFTCollateralCondition',424 ctx,425 args: [426 roles.ownerWallet,427 getAddress('ConditionStoreManager'),428 getAddress('NFT721LockCondition')429 ],430 verbose431 })432 }433 }434 if (getAddress('AgreementStoreManager') &&435 getAddress('DIDRegistry') &&436 getAddress('AccessCondition') &&437 getAddress('LockPaymentCondition') &&438 getAddress('EscrowPaymentCondition')) {439 if (contracts.indexOf('AccessTemplate') > -1) {440 addressBook.AccessTemplate = await zosCreate({441 contract: 'AccessTemplate',442 ctx,443 args: [444 roles.ownerWallet,445 getAddress('AgreementStoreManager'),446 getAddress('DIDRegistry'),447 getAddress('AccessCondition'),448 getAddress('LockPaymentCondition'),449 getAddress('EscrowPaymentCondition')450 ],451 verbose452 })453 }454 }455 if (getAddress('AgreementStoreManager') &&456 getAddress('DIDRegistry') &&457 getAddress('AccessProofCondition') &&458 getAddress('LockPaymentCondition') &&459 getAddress('EscrowPaymentCondition')) {460 if (contracts.indexOf('AccessProofTemplate') > -1) {461 addressBook.AccessProofTemplate = await zosCreate({462 contract: 'AccessProofTemplate',463 ctx,464 args: [465 roles.ownerWallet,466 getAddress('AgreementStoreManager'),467 getAddress('DIDRegistry'),468 getAddress('AccessProofCondition'),469 getAddress('LockPaymentCondition'),470 getAddress('EscrowPaymentCondition')471 ],472 verbose473 })474 }475 }476 if (getAddress('AgreementStoreManager') &&477 getAddress('DIDRegistry') &&478 getAddress('ComputeExecutionCondition') &&479 getAddress('LockPaymentCondition') &&480 getAddress('EscrowPaymentCondition')) {481 if (contracts.indexOf('EscrowComputeExecutionTemplate') > -1) {482 addressBook.EscrowComputeExecutionTemplate = await zosCreate({483 contract: 'EscrowComputeExecutionTemplate',484 ctx,485 args: [486 roles.ownerWallet,487 getAddress('AgreementStoreManager'),488 getAddress('DIDRegistry'),489 getAddress('ComputeExecutionCondition'),490 getAddress('LockPaymentCondition'),491 getAddress('EscrowPaymentCondition')492 ],493 verbose494 })495 }496 }497 if (getAddress('AgreementStoreManager') &&498 getAddress('NFTAccessCondition') &&499 getAddress('NFTHolderCondition')) {500 if (contracts.indexOf('NFTAccessTemplate') > -1) {501 addressBook.NFTAccessTemplate = await zosCreate({502 contract: 'NFTAccessTemplate',503 ctx,504 args: [505 roles.ownerWallet,506 getAddress('AgreementStoreManager'),507 getAddress('NFTHolderCondition'),508 getAddress('NFTAccessCondition')509 ],510 verbose511 })512 }513 }514 if (getAddress('AgreementStoreManager') &&515 getAddress('NFTAccessCondition') &&516 getAddress('NFT721HolderCondition')) {517 if (contracts.indexOf('NFT721AccessTemplate') > -1) {518 addressBook.NFT721AccessTemplate = await zosCreate({519 contract: 'NFT721AccessTemplate',520 ctx,521 args: [522 roles.ownerWallet,523 getAddress('AgreementStoreManager'),524 getAddress('NFT721HolderCondition'),525 getAddress('NFTAccessCondition')526 ],527 verbose528 })529 }530 }531 if (getAddress('AgreementStoreManager') &&532 getAddress('LockPaymentCondition') &&533 getAddress('TransferNFTCondition') &&534 getAddress('EscrowPaymentCondition')) {535 if (contracts.indexOf('NFTSalesTemplate') > -1) {536 addressBook.NFTSalesTemplate = await zosCreate({537 contract: 'NFTSalesTemplate',538 ctx,539 args: [540 roles.ownerWallet,541 getAddress('AgreementStoreManager'),542 getAddress('LockPaymentCondition'),543 getAddress('TransferNFTCondition'),544 getAddress('EscrowPaymentCondition')545 ],546 verbose547 })548 }549 }550 if (getAddress('AgreementStoreManager') &&551 getAddress('LockPaymentCondition') &&552 getAddress('TransferNFT721Condition') &&553 getAddress('EscrowPaymentCondition')) {554 if (contracts.indexOf('NFT721SalesTemplate') > -1) {555 addressBook.NFT721SalesTemplate = await zosCreate({556 contract: 'NFT721SalesTemplate',557 ctx,558 args: [559 roles.ownerWallet,560 getAddress('AgreementStoreManager'),561 getAddress('LockPaymentCondition'),562 getAddress('TransferNFT721Condition'),563 getAddress('EscrowPaymentCondition')564 ],565 verbose566 })567 }568 }569 if (getAddress('AgreementStoreManager') &&570 getAddress('LockPaymentCondition') &&571 getAddress('TransferDIDOwnershipCondition') &&572 getAddress('EscrowPaymentCondition')) {573 if (contracts.indexOf('DIDSalesTemplate') > -1) {574 addressBook.DIDSalesTemplate = await zosCreate({575 contract: 'DIDSalesTemplate',576 ctx,577 args: [578 roles.ownerWallet,579 getAddress('AgreementStoreManager'),580 getAddress('LockPaymentCondition'),581 getAddress('TransferDIDOwnershipCondition'),582 getAddress('EscrowPaymentCondition')583 ],584 verbose585 })586 }587 }588 if (getAddress('AgreementStoreManager') &&589 getAddress('NFT721LockCondition') &&590 getAddress('AaveCollateralDepositCondition') &&591 getAddress('AaveBorrowCondition') &&592 getAddress('AaveRepayCondition') &&593 getAddress('AaveCollateralWithdrawCondition') &&594 getAddress('DistributeNFTCollateralCondition')) {595 if (contracts.indexOf('AaveCreditTemplate') > -1) {596 addressBook.AaveCreditTemplate = await zosCreate({597 contract: 'AaveCreditTemplate',598 ctx,599 args: [600 roles.ownerWallet,601 getAddress('AgreementStoreManager'),602 getAddress('NFT721LockCondition'),603 getAddress('AaveCollateralDepositCondition'),604 getAddress('AaveBorrowCondition'),605 getAddress('AaveRepayCondition'),606 getAddress('AaveCollateralWithdrawCondition'),607 getAddress('DistributeNFTCollateralCondition')608 ],609 verbose610 })611 }612 }613 return { cache, addressBook, proxies }614}...

Full Screen

Full Screen

weth11.spec.js

Source:weth11.spec.js Github

copy

Full Screen

...36 const domainSeparator = await weth.DOMAIN_SEPARATOR();37 expect(domainSeparator).to.equal(domain)38 })39 it('deposits ether', async () => {40 const balanceBefore = await weth.balanceOf(await user1.getAddress())41 await weth.deposit({ value: 1 })42 const balanceAfter = await weth.balanceOf(await user1.getAddress())43 expect(balanceAfter).to.equal(balanceBefore.add('1'))44 })45 it('deposits ether using the legacy method', async () => {46 const balanceBefore = await weth.balanceOf(await user1.getAddress())47 await user1.sendTransaction({ to: weth.address, value: 1 })48 const balanceAfter = await weth.balanceOf(await user1.getAddress())49 expect(balanceAfter).to.equal(balanceBefore.add('1'))50 })51 it('deposits ether to another account', async () => {52 const balanceBefore = await weth.balanceOf(await user2.getAddress())53 await weth.depositTo(await user2.getAddress(), { value: 1 })54 const balanceAfter = await weth.balanceOf(await user2.getAddress())55 expect(balanceAfter).to.equal(balanceBefore.add('1'))56 })57 it('deposits with depositToAndCall', async () => {58 await weth.depositToAndCall(receiver.address, '0x11', { value: 1 })59 const events = await receiver.queryFilter('TransferReceived')60 expect(events.length).to.equal(1)61 expect(events[0].args.token).to.equal(weth.address)62 expect(events[0].args.sender).to.equal(await user1.getAddress())63 expect(events[0].args.value).to.equal('1')64 expect(events[0].args.data).to.equal('0x11')65 })66 describe('with a positive balance', async () => {67 beforeEach(async () => {68 await weth.deposit({ value: 10 })69 })70 it('returns the Ether balance as total supply', async () => {71 const totalSupply = await weth.totalSupply()72 expect(totalSupply).to.equal('10')73 })74 it('withdraws ether', async () => {75 const balanceBefore = await weth.balanceOf(await user1.getAddress())76 const ethBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))77 const tx = await weth.withdraw(1)78 const receipt = await tx.wait()79 const ethSpentOnGas = ethers.BigNumber.from(receipt.gasUsed).mul(tx.gasPrice) 80 const balanceAfter = await weth.balanceOf(await user1.getAddress())81 const ethBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))82 expect(balanceAfter).to.equal(balanceBefore.sub('1'))83 expect(ethBalanceAfter).to.equal(ethBalanceBefore.add('1').sub(ethSpentOnGas))84 })85 it('withdraws ether to another account', async () => {86 const fromBalanceBefore = await weth.balanceOf(await user1.getAddress())87 const toBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user2.getAddress()))88 await weth.withdrawTo(await user2.getAddress(), 1)89 const fromBalanceAfter = await weth.balanceOf(await user1.getAddress())90 const toBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user2.getAddress()))91 expect(fromBalanceAfter).to.equal(fromBalanceBefore.sub('1'))92 expect(toBalanceAfter).to.equal(toBalanceBefore.add('1'))93 })94 it('should not withdraw beyond balance', async () => {95 await expect(weth.withdraw(100))96 .to.be.reverted97 // .to.revertedWith('WETH: burn amount exceeds balance')98 await expect(weth.withdrawTo(await user2.getAddress(), 100))99 .to.be.reverted100 // .to.revertedWith('WETH: burn amount exceeds balance')101 await expect(weth.withdrawFrom(await user1.getAddress(), await user2.getAddress(), 100))102 .to.be.reverted103 // .to.revertedWith('WETH: burn amount exceeds balance')104 })105 it('transfers ether', async () => {106 const balanceBefore = await weth.balanceOf(await user2.getAddress())107 await weth.transfer(await user2.getAddress(), 1)108 const balanceAfter = await weth.balanceOf(await user2.getAddress())109 expect(balanceAfter).to.equal(balanceBefore.add('1'))110 })111 it('withdraws ether by transferring to address(0)', async () => {112 const balanceBefore = await weth.balanceOf(await user1.getAddress())113 const ethBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))114 const tx = await weth.transfer('0x0000000000000000000000000000000000000000', 1)115 const receipt = await tx.wait()116 const gasFee = receipt.gasUsed.mul(tx.gasPrice)117 const balanceAfter = await weth.balanceOf(await user1.getAddress())118 const ethBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))119 expect(balanceAfter).to.equal(balanceBefore.sub('1'))120 expect(ethBalanceAfter).to.equal(ethBalanceBefore.add('1').sub(gasFee))121 })122 it('withdraws ether by transferring to contract', async () => {123 const balanceBefore = await weth.balanceOf(await user1.getAddress())124 const ethBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))125 const tx = await weth.transfer(weth.address, 1)126 const receipt = await tx.wait()127 const gasFee = receipt.gasUsed.mul(tx.gasPrice)128 const balanceAfter = await weth.balanceOf(await user1.getAddress())129 const ethBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))130 expect(balanceAfter).to.equal(balanceBefore.sub('1'))131 expect(ethBalanceAfter).to.equal(ethBalanceBefore.add('1').sub(gasFee))132 })133 it('transfers ether using transferFrom', async () => {134 const balanceBefore = await weth.balanceOf(await user2.getAddress())135 await weth.transferFrom(await user1.getAddress(), await user2.getAddress(), 1)136 const balanceAfter = await weth.balanceOf(await user2.getAddress())137 expect(balanceAfter).to.equal(balanceBefore.add('1'))138 })139 it('withdraws ether by transferring from someone to address(0)', async () => {140 const balanceBefore = await weth.balanceOf(await user1.getAddress())141 const ethBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))142 143 const tx = await weth.transferFrom(await user1.getAddress(), '0x0000000000000000000000000000000000000000', 1)144 const receipt = await tx.wait()145 const gasFee = receipt.gasUsed.mul(tx.gasPrice)146 const balanceAfter = await weth.balanceOf(await user1.getAddress())147 const ethBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))148 149 expect(balanceAfter).to.equal(balanceBefore.sub('1'))150 expect(ethBalanceAfter).to.equal(ethBalanceBefore.add('1').sub(gasFee))151 })152 it('withdraws ether by transferring from someone to contract', async () => {153 const balanceBefore = await weth.balanceOf(await user1.getAddress())154 const ethBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))155 const tx = await weth.transferFrom(await user1.getAddress(), weth.address, 1)156 const receipt = await tx.wait()157 const gasFee = receipt.gasUsed.mul(tx.gasPrice)158 const balanceAfter = await weth.balanceOf(await user1.getAddress())159 const ethBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user1.getAddress()))160 expect(balanceAfter).to.equal(balanceBefore.sub('1'))161 expect(ethBalanceAfter).to.equal(ethBalanceBefore.add('1').sub(gasFee))162 })163 it('transfers with transferAndCall', async () => {164 const tx = await weth.transferAndCall(receiver.address, 1, '0x11')165 const events = await receiver.queryFilter('TransferReceived', tx.blockNumber)166 expect(events.length).to.equal(1)167 expect(events[0].args.token).to.equal(weth.address)168 expect(events[0].args.sender).to.equal(await user1.getAddress())169 expect(events[0].args.value).to.equal('1')170 expect(events[0].args.data).to.equal('0x11')171 })172 it('should fail with transferAndCall if recipient is not a contract', async () => {173 await expect(weth.transferAndCall(await user2.getAddress(), 1, '0x11')).to.be.reverted174 })175 it('should not transfer beyond balance', async () => {176 await expect(weth.transfer(await user2.getAddress(), 100))177 .to.be.reverted178 // .to.revertedWith('WETH: transfer amount exceeds balance')179 await expect(weth.transferFrom(await user1.getAddress(), await user2.getAddress(), 100))180 .to.be.reverted181 // .to.revertedWith('WETH: transfer amount exceeds balance')182 await expect(weth.transferAndCall(receiver.address, 100, '0x11'))183 .to.be.reverted184 // .to.revertedWith('WETH: transfer amount exceeds balance')185 })186 it('approves to increase allowance', async () => {187 const allowanceBefore = await weth.allowance(await user1.getAddress(), await user2.getAddress())188 await weth.approve(await user2.getAddress(), 1)189 const allowanceAfter = await weth.allowance(await user1.getAddress(), await user2.getAddress())190 expect(allowanceAfter).to.equal(allowanceBefore.add('1'))191 })192 it('approves with approveAndCall', async () => {193 await weth.approveAndCall(receiver.address, 1, '0x11')194 const events = await receiver.queryFilter('ApprovalReceived')195 expect(events.length).to.equal(1)196 expect(events[0].args.token).to.equal(weth.address)197 expect(events[0].args.spender).to.equal(await user1.getAddress())198 expect(events[0].args.value).to.equal('1')199 expect(events[0].args.data).to.equal('0x11')200 })201 it('approves to increase allowance with permit', async () => {202 const permitResult = await signERC2612Permit(network.provider, weth.address, await user1.getAddress(), await user2.getAddress(), '1')203 await weth.permit(await user1.getAddress(), await user2.getAddress(), '1', permitResult.deadline, permitResult.v, permitResult.r, permitResult.s)204 const allowanceAfter = await weth.allowance(await user1.getAddress(), await user2.getAddress())205 expect(allowanceAfter).to.equal('1')206 })207 it('does not approve with expired permit', async () => {208 const permitResult = await signERC2612Permit(network.provider, weth.address, await user1.getAddress(), await user2.getAddress(), '1')209 await expect(weth.permit(210 await user1.getAddress(), await user2.getAddress(), '1', 0, permitResult.v, permitResult.r, permitResult.s),211 ).to.be.reverted212 })213 it('does not approve with invalid permit', async () => {214 const permitResult = await signERC2612Permit(network.provider, weth.address, await user1.getAddress(), await user2.getAddress(), '1')215 await expect(216 weth.permit(await user1.getAddress(), await user2.getAddress(), '2', permitResult.deadline, permitResult.v, permitResult.r, permitResult.s),217 ).to.be.reverted218 })219 describe('with a positive allowance', async () => {220 beforeEach(async () => {221 await weth.approve(await user2.getAddress(), 1)222 })223 it('transfers ether using transferFrom and allowance', async () => {224 const balanceBefore = await weth.balanceOf(await user2.getAddress())225 await weth.connect(user2).transferFrom(await user1.getAddress(), await user2.getAddress(), 1)226 const balanceAfter = await weth.balanceOf(await user2.getAddress())227 expect(balanceAfter).to.equal(balanceBefore.add('1'))228 })229 it('should not transfer beyond allowance', async () => {230 await expect(weth.connect(user2).transferFrom(await user1.getAddress(), await user2.getAddress(), 2))231 .to.be.reverted232 })233 234 it('withdraws ether using withdrawFrom and allowance', async () => {235 const fromBalanceBefore = await weth.balanceOf(await user1.getAddress())236 const toBalanceBefore = ethers.BigNumber.from(await ethers.provider.getBalance(await user3.getAddress()))237 await weth.connect(user2).withdrawFrom(await user1.getAddress(), await user3.getAddress(), 1)238 const fromBalanceAfter = await weth.balanceOf(await user1.getAddress())239 const toBalanceAfter = ethers.BigNumber.from(await ethers.provider.getBalance(await user3.getAddress()))240 expect(fromBalanceAfter).to.equal(fromBalanceBefore.sub('1'))241 expect(toBalanceAfter).to.equal(toBalanceBefore.add('1'))242 })243 it('should not withdraw beyond allowance', async () => {244 await expect(weth.connect(user2).withdrawFrom(await user1.getAddress(), await user3.getAddress(), 2))245 .to.be.reverted246 // .to.be.revertedWith('WETH: request exceeds allowance')247 })248 })249 describe('with a maximum allowance', async () => {250 beforeEach(async () => {251 await weth.approve(await user2.getAddress(), MAX)252 })253 it('does not decrease allowance using transferFrom', async () => {254 await weth.connect(user2).transferFrom(await user1.getAddress(), await user2.getAddress(), 1)255 const allowanceAfter = await weth.allowance(await user1.getAddress(), await user2.getAddress())256 expect(allowanceAfter).to.equal(MAX)257 })258 it('does not decrease allowance using withdrawFrom', async () => {259 await weth.connect(user2).withdrawFrom(await user1.getAddress(), await user2.getAddress(), 1)260 const allowanceAfter = await weth.allowance(await user1.getAddress(), await user2.getAddress())261 expect(allowanceAfter).to.equal(MAX)262 })263 })264 })265 })...

Full Screen

Full Screen

testUnionTokenPause.js

Source:testUnionTokenPause.js Github

copy

Full Screen

...18 let newMemberFeeUnion;19 const deployAndInitialize = async () => {20 ({dai, unionToken, comptroller, assetManager, uToken, userManager} = await deployFullSuite());21 await dai.mint(assetManager.address, mintDAIAmount);22 await dai.mint(ALICE.getAddress(), mintDAIAmount);23 await dai.mint(BOB.getAddress(), mintDAIAmount);24 await dai.mint(CHARLIE.getAddress(), mintDAIAmount);25 await dai.mint(DAVID.getAddress(), mintDAIAmount);26 newMemberFeeUnion = await userManager.newMemberFee();27 await unionToken.transfer(DAVID.getAddress(), newMemberFeeUnion);28 await unionToken.transfer(comptroller.address, comptrollerUnionAmount);29 };30 before(async () => {31 [ADMIN, ALICE, BOB, CHARLIE, DAVID, ETHAN] = await ethers.getSigners();32 });33 describe("Enable whitelist and try user actions", () => {34 before(deployAndInitialize);35 it("Union token whitelist should be enabled", async () => {36 await unionToken.enableWhitelist();37 const whitelistEnabled = await unionToken.whitelistEnabled();38 whitelistEnabled.should.equal(true);39 });40 it("Admin should be whitelisted", async () => {41 const isWhitelisted = await unionToken.isWhitelisted(ADMIN.getAddress());42 isWhitelisted.should.eq(true);43 });44 it("Comptroller should be whitelisted", async () => {45 const isWhitelisted = await unionToken.isWhitelisted(comptroller.address);46 isWhitelisted.should.eq(true);47 });48 it("Alice, Bob and Charlie should be able to stake", async () => {49 await dai.connect(ALICE).approve(userManager.address, stakeDAIAmount);50 await userManager.connect(ALICE).stake(stakeDAIAmount);51 await dai.connect(BOB).approve(userManager.address, stakeDAIAmount);52 await userManager.connect(BOB).stake(stakeDAIAmount);53 await dai.connect(CHARLIE).approve(userManager.address, stakeDAIAmount);54 await userManager.connect(CHARLIE).stake(stakeDAIAmount);55 });56 it("Admin should be able to add Alice, Bob and Charlie", async () => {57 await userManager.addMember(ALICE.getAddress());58 await userManager.addMember(BOB.getAddress());59 await userManager.addMember(CHARLIE.getAddress());60 });61 it("Alice, Bob and Charlie should be able to vouch for David", async () => {62 await userManager.connect(ALICE).updateTrust(DAVID.getAddress(), vouchDAIAmount);63 await userManager.connect(BOB).updateTrust(DAVID.getAddress(), vouchDAIAmount);64 await userManager.connect(CHARLIE).updateTrust(DAVID.getAddress(), vouchDAIAmount);65 });66 it("David should be able to register", async () => {67 await unionToken.connect(DAVID).approve(userManager.address, newMemberFeeUnion);68 await userManager.connect(DAVID).registerMember(DAVID.getAddress());69 });70 it("David should be able to borrow", async () => {71 const davidCreditLimit = await userManager.getCreditLimit(DAVID.getAddress());72 const fee = await uToken.calculatingFee(davidCreditLimit);73 borrowDAIAmount = davidCreditLimit.sub(fee);74 await uToken.connect(DAVID).borrow(borrowDAIAmount);75 });76 it("David should wait for 100 blocks and repay with interest", async () => {77 await waitNBlocks(100);78 const borrowBalanceView = await uToken.borrowBalanceView(DAVID.getAddress());79 await dai.connect(DAVID).approve(uToken.address, borrowBalanceView);80 await uToken.connect(DAVID).repayBorrow(borrowBalanceView);81 });82 it("Alice, Bob and Charlie should be able to withdraw rewards", async () => {83 await userManager.connect(ALICE).withdrawRewards();84 await userManager.connect(BOB).withdrawRewards();85 await userManager.connect(CHARLIE).withdrawRewards();86 });87 it("Alice, Bob and Charlie should be able to unstake", async () => {88 let stakeAmount = await userManager.stakers(ALICE.getAddress());89 let lockedAmount = await userManager.getTotalLockedStake(ALICE.getAddress());90 await userManager.connect(ALICE).unstake(stakeAmount.sub(lockedAmount));91 stakeAmount = await userManager.stakers(BOB.getAddress());92 lockedAmount = await userManager.getTotalLockedStake(BOB.getAddress());93 await userManager.connect(BOB).unstake(stakeAmount.sub(lockedAmount));94 stakeAmount = await userManager.stakers(CHARLIE.getAddress());95 lockedAmount = await userManager.getTotalLockedStake(CHARLIE.getAddress());96 await userManager.connect(CHARLIE).unstake(stakeAmount.sub(lockedAmount));97 });98 describe("Alice transfers own Union tokens", () => {99 it("Alice should have enough tokens to transfer", async () => {100 const balance = await unionToken.balanceOf(ALICE.getAddress());101 balance.should.be.gte(transferUnionAmount);102 });103 it("Alice should not be able to trasfer", async () => {104 await expect(105 unionToken.connect(ALICE).transfer(ETHAN.getAddress(), transferUnionAmount)106 ).to.be.revertedWith("Whitelistable: address not whitelisted");107 });108 });109 describe("Charlie transfers Bob's Union tokens", () => {110 it("Bob should have enough tokens to transfer", async () => {111 const balance = await unionToken.balanceOf(BOB.getAddress());112 balance.should.be.gte(transferUnionAmount);113 });114 it("Bob should approve Charlie to transfer", async () => {115 await unionToken.connect(BOB).approve(CHARLIE.getAddress(), transferUnionAmount);116 });117 it("Charlie should not be able to transfer", async () => {118 await expect(119 unionToken.connect(CHARLIE).transferFrom(BOB.getAddress(), ETHAN.getAddress(), transferUnionAmount)120 ).to.be.revertedWith("Whitelistable: address not whitelisted");121 });122 });123 describe("Admin transfers own Union tokens", () => {124 it("Admin should have enough tokens to transfer", async () => {125 const balance = await unionToken.balanceOf(ADMIN.getAddress());126 balance.should.be.gte(transferUnionAmount);127 });128 it("Admin should be able to transfer Union tokens", async () => {129 await unionToken.transfer(ETHAN.getAddress(), transferUnionAmount);130 });131 });132 describe("Admin transfers Bob's Union tokens", () => {133 it("Bob should have enough tokens to transfer", async () => {134 const balance = await unionToken.balanceOf(BOB.getAddress());135 balance.should.be.gte(transferUnionAmount);136 });137 it("Bob should approve Admin to transfer", async () => {138 await unionToken.connect(BOB).approve(ADMIN.getAddress(), transferUnionAmount);139 });140 it("Admin should be able to transfer", async () => {141 await unionToken.transferFrom(BOB.getAddress(), ETHAN.getAddress(), transferUnionAmount);142 });143 });144 });145 describe("Disable whitelist and try user actions", () => {146 before(deployAndInitialize);147 it("Union token whitelist should be disabled", async () => {148 await unionToken.disableWhitelist();149 const whitelistEnabled = await unionToken.whitelistEnabled();150 whitelistEnabled.should.equal(false);151 });152 it("Alice, Bob and Charlie should be able to stake", async () => {153 await dai.connect(ALICE).approve(userManager.address, stakeDAIAmount);154 await userManager.connect(ALICE).stake(stakeDAIAmount);155 await dai.connect(BOB).approve(userManager.address, stakeDAIAmount);156 await userManager.connect(BOB).stake(stakeDAIAmount);157 await dai.connect(CHARLIE).approve(userManager.address, stakeDAIAmount);158 await userManager.connect(CHARLIE).stake(stakeDAIAmount);159 });160 it("Admin should be able to add Alice, Bob and Charlie", async () => {161 await userManager.addMember(ALICE.getAddress());162 await userManager.addMember(BOB.getAddress());163 await userManager.addMember(CHARLIE.getAddress());164 });165 it("Alice, Bob and Charlie should be able to vouch for David", async () => {166 await userManager.connect(ALICE).updateTrust(DAVID.getAddress(), vouchDAIAmount);167 await userManager.connect(BOB).updateTrust(DAVID.getAddress(), vouchDAIAmount);168 await userManager.connect(CHARLIE).updateTrust(DAVID.getAddress(), vouchDAIAmount);169 });170 it("David should be able to register", async () => {171 await unionToken.connect(DAVID).approve(userManager.address, newMemberFeeUnion);172 await userManager.connect(DAVID).registerMember(DAVID.getAddress());173 });174 it("David should be able to borrow", async () => {175 const davidCreditLimit = await userManager.getCreditLimit(DAVID.getAddress());176 const fee = await uToken.calculatingFee(davidCreditLimit);177 borrowDAIAmount = davidCreditLimit.sub(fee);178 await uToken.connect(DAVID).borrow(borrowDAIAmount);179 });180 it("David should wait for 100 blocks and repay with interest", async () => {181 await waitNBlocks(100);182 const borrowBalanceView = await uToken.borrowBalanceView(DAVID.getAddress());183 await dai.connect(DAVID).approve(uToken.address, borrowBalanceView);184 await uToken.connect(DAVID).repayBorrow(borrowBalanceView);185 });186 it("Alice, Bob and Charlie should be able to withdraw rewards", async () => {187 await userManager.connect(ALICE).withdrawRewards();188 await userManager.connect(BOB).withdrawRewards();189 await userManager.connect(CHARLIE).withdrawRewards();190 });191 it("Alice, Bob and Charlie should be able to unstake", async () => {192 let stakeAmount = await userManager.stakers(ALICE.getAddress());193 let lockedAmount = await userManager.getTotalLockedStake(ALICE.getAddress());194 await userManager.connect(ALICE).unstake(stakeAmount.sub(lockedAmount));195 stakeAmount = await userManager.stakers(BOB.getAddress());196 lockedAmount = await userManager.getTotalLockedStake(BOB.getAddress());197 await userManager.connect(BOB).unstake(stakeAmount.sub(lockedAmount));198 stakeAmount = await userManager.stakers(CHARLIE.getAddress());199 lockedAmount = await userManager.getTotalLockedStake(CHARLIE.getAddress());200 await userManager.connect(CHARLIE).unstake(stakeAmount.sub(lockedAmount));201 });202 describe("Alice transfers own Union tokens", () => {203 it("Alice should have enough tokens to transfer", async () => {204 const balance = await unionToken.balanceOf(ALICE.getAddress());205 balance.should.be.gte(transferUnionAmount);206 });207 it("Alice should be able to trasfer", async () => {208 await unionToken.connect(ALICE).transfer(ETHAN.getAddress(), transferUnionAmount);209 });210 });211 describe("Charlie transfers Bob's Union tokens", () => {212 it("Bob should have enough tokens to transfer", async () => {213 const balance = await unionToken.balanceOf(BOB.getAddress());214 balance.should.be.gte(transferUnionAmount);215 });216 it("Bob should approve Charlie to transfer", async () => {217 await unionToken.connect(BOB).approve(CHARLIE.getAddress(), transferUnionAmount);218 });219 it("Charlie should be able to transfer", async () => {220 await unionToken221 .connect(CHARLIE)222 .transferFrom(BOB.getAddress(), ETHAN.getAddress(), transferUnionAmount);223 });224 });225 describe("Admin transfers own Union tokens", () => {226 it("Admin should have enough tokens to transfer", async () => {227 const balance = await unionToken.balanceOf(ADMIN.getAddress());228 balance.should.gte(transferUnionAmount);229 });230 it("Admin should be able to transfer Union tokens", async () => {231 await unionToken.transfer(ETHAN.getAddress(), transferUnionAmount);232 });233 });234 describe("Admin transfers Bob's Union tokens", () => {235 it("Bob should have enough tokens to transfer", async () => {236 const balance = await unionToken.balanceOf(BOB.getAddress());237 balance.should.be.gte(transferUnionAmount);238 });239 it("Bob should approve Admin to transfer", async () => {240 await unionToken.connect(BOB).approve(ADMIN.getAddress(), transferUnionAmount);241 });242 it("Admin should be able to transfer", async () => {243 await unionToken.transferFrom(BOB.getAddress(), ETHAN.getAddress(), transferUnionAmount);244 });245 });246 });...

Full Screen

Full Screen

ERC721Ai_Test.js

Source:ERC721Ai_Test.js Github

copy

Full Screen

...34 Ensure tokenOfOwnerByIndex works as expected35****************************************************************************/36 describe(CONTRACT_NAME + ' - tokenOfOwnerByIndex', () => {37 it('tokenOfOwnerByIndex works as expected', async () => {38 await contract.connect(addr1).mint(addr1.getAddress(), 1)39 await contract.connect(addr2).mint(addr2.getAddress(), 1)40 await contract.connect(owner).mint(owner.getAddress(), 1)41 await contract.connect(addr1).mint(addr1.getAddress(), 1)42 await contract.connect(addr2).mint(addr2.getAddress(), 1)43 await contract.connect(owner).mint(owner.getAddress(), 1)44 await contract.connect(addr1).mint(addr1.getAddress(), 1)45 await contract.connect(addr2).mint(addr2.getAddress(), 1)46 await contract.connect(owner).mint(owner.getAddress(), 1)47 expect(await contract.tokenOfOwnerByIndex(addr1.getAddress(), 0)).to.equal(48 0,49 )50 expect(await contract.tokenOfOwnerByIndex(addr1.getAddress(), 1)).to.equal(51 3,52 )53 expect(await contract.tokenOfOwnerByIndex(addr1.getAddress(), 2)).to.equal(54 6,55 )56 expect(await contract.tokenOfOwnerByIndex(addr2.getAddress(), 0)).to.equal(57 1,58 )59 expect(await contract.tokenOfOwnerByIndex(addr2.getAddress(), 1)).to.equal(60 4,61 )62 expect(await contract.tokenOfOwnerByIndex(addr2.getAddress(), 2)).to.equal(63 7,64 )65 expect(await contract.tokenOfOwnerByIndex(owner.getAddress(), 0)).to.equal(66 2,67 )68 expect(await contract.tokenOfOwnerByIndex(owner.getAddress(), 1)).to.equal(69 5,70 )71 expect(await contract.tokenOfOwnerByIndex(owner.getAddress(), 2)).to.equal(72 8,73 )74 })75 it(REVERT_TAG + 'Attempting to fetch out of owner index reverts', async () => {76 await contract.connect(addr1).mint(addr1.getAddress(), 1)77 expect(await contract.tokenOfOwnerByIndex(addr1.getAddress(), 1))78 })79 })...

Full Screen

Full Screen

addressHelpers.js

Source:addressHelpers.js Github

copy

Full Screen

...4export const getAddress = (address) => {5 return address[NETWORK_CHAIN_ID] ? address[NETWORK_CHAIN_ID] : address[ChainId.MAINNET]6}7export const getMasterChefAddress = () => {8 return getAddress(addresses.masterChef)9}10export const getMulticallAddress = () => {11 return getAddress(addresses.multiCall)12}13// export const getLotteryV2Address = () => {14// return getAddress(addresses.lotteryV2)15// }16// export const getPancakeProfileAddress = () => {17// return getAddress(addresses.pancakeProfile)18// }19// export const getPancakeRabbitsAddress = () => {20// return getAddress(addresses.pancakeRabbits)21// }22// export const getBunnyFactoryAddress = () => {23// return getAddress(addresses.bunnyFactory)24// }25// export const getClaimRefundAddress = () => {26// return getAddress(addresses.claimRefund)27// }28// export const getPointCenterIfoAddress = () => {29// return getAddress(addresses.pointCenterIfo)30// }31// export const getBunnySpecialAddress = () => {32// return getAddress(addresses.bunnySpecial)33// }34// export const getTradingCompetitionAddress = () => {35// return getAddress(addresses.tradingCompetition)36// }37// export const getEasterNftAddress = () => {38// return getAddress(addresses.easterNft)39// }40// export const getCakeVaultAddress = () => {41// return getAddress(addresses.cakeVault)42// }43// export const getPredictionsAddress = () => {44// return getAddress(addresses.predictions)45// }46// export const getChainlinkOracleAddress = () => {47// return getAddress(addresses.chainlinkOracle)48// }49// export const getBunnySpecialCakeVaultAddress = () => {50// return getAddress(addresses.bunnySpecialCakeVault)51// }52// export const getBunnySpecialPredictionAddress = () => {53// return getAddress(addresses.bunnySpecialPrediction)54// }55// export const getBunnySpecialLotteryAddress = () => {56// return getAddress(addresses.bunnySpecialLottery)57// }58// export const getFarmAuctionAddress = () => {59// return getAddress(addresses.farmAuction)60// }61// export const getAnniversaryAchievement = () => {62// return getAddress(addresses.AnniversaryAchievement)63// }64// export const getNftMarketAddress = () => {65// return getAddress(addresses.nftMarket)66// }67// export const getNftSaleAddress = () => {68// return getAddress(addresses.nftSale)69// }70// export const getPancakeSquadAddress = () => {71// return getAddress(addresses.pancakeSquad)...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...17 MessageBoxA: 0x1,18 MessageBoxW: 0x2,19 },20};21assert.ok(getAddress("1+1") === 2);22assert.ok(getAddress("3**2") === 3 ** 2);23assert.ok(getAddress("[1+1]") === 0xce);24assert.ok(getAddress("[1+1]+s1") === 0xce + SYMBOL_TABLE.s1);25assert.ok(26 getAddress("[1+1]+s1*s2") === 0xce + SYMBOL_TABLE.s1 * SYMBOL_TABLE.s227);28assert.ok(getAddress("[1] + [1]") === 0xce + 0xce);29assert.ok(getAddress("([1] + [1]) * 2") === (0xce + 0xce) * 2);30assert.ok(getAddress("game.exe") === MODULE_TABLE["game.exe"]);31assert.ok(32 getAddress(` "game.exe" + "user32.dll" `) ===33 MODULE_TABLE["game.exe"] + MODULE_TABLE["user32.dll"]34);35assert.ok(36 getAddress("user32.MessageBoxA") === MODULE_IMPOT_TABLE.user32.MessageBoxA37);38assert.ok(39 getAddress("user32.MessageBoxA + user32.MessageBoxW") ===40 MODULE_IMPOT_TABLE.user32.MessageBoxA +41 MODULE_IMPOT_TABLE.user32.MessageBoxW42);43assert.ok(getAddress("MessageBoxA") === MODULE_IMPOT_TABLE.user32.MessageBoxA);44assert.ok(45 getAddress("MessageBoxA + MessageBoxW") ===46 MODULE_IMPOT_TABLE.user32.MessageBoxA +47 MODULE_IMPOT_TABLE.user32.MessageBoxW48);49assert.ok(50 getAddress(` "user32.MessageBoxA" + "user32.MessageBoxW" `) ===51 MODULE_IMPOT_TABLE.user32.MessageBoxA +52 MODULE_IMPOT_TABLE.user32.MessageBoxW53);54assert.ok(55 getAddress(` "MessageBoxA" + "MessageBoxW" `) ===56 MODULE_IMPOT_TABLE.user32.MessageBoxA +57 MODULE_IMPOT_TABLE.user32.MessageBoxW58);59assert.ok(getAddress(` "s1"`) === SYMBOL_TABLE.s1);60assert.ok(getAddress(` "s1" + 1 `) === SYMBOL_TABLE.s1 + 1);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('getAddress', (street, city, state, zip) => {2 cy.get('#street').type(street);3 cy.get('#city').type(city);4 cy.get('#state').type(state);5 cy.get('#zip').type(zip);6 cy.get('#submit').click();7});8Cypress.Commands.add('getAddress', (street, city, state, zip) => {9 cy.get('#street').type(street);10 cy.get('#city').type(city);11 cy.get('#state').type(state);12 cy.get('#zip').type(zip);13 cy.get('#submit').click();14});15Cypress.Commands.add('getAddress', (street, city, state, zip) => {16 cy.get('#street').type(street);17 cy.get('#city').type(city);18 cy.get('#state').type(state);19 cy.get('#zip').type(zip);20 cy.get('#submit').click();21});22Cypress.Commands.add('getAddress', (street, city, state, zip) => {23 cy.get('#street').type(street);24 cy.get('#city').type(city);25 cy.get('#state').type(state);26 cy.get('#zip').type(zip);27 cy.get('#submit').click();28});29Cypress.Commands.add('getAddress', (street, city, state, zip) => {30 cy.get('#street').type(street);31 cy.get('#city').type(city);32 cy.get('#state').type(state);33 cy.get('#zip').type(zip);34 cy.get('#submit').click();35});36Cypress.Commands.add('getAddress', (street, city, state, zip) => {37 cy.get('#street').type(street);38 cy.get('#city').type(city);39 cy.get('#state').type(state);40 cy.get('#zip').type(zip);41 cy.get('#submit').click();42});43Cypress.Commands.add('

Full Screen

Using AI Code Generation

copy

Full Screen

1import {getAddress} from 'cy-address';2describe('My First Test', () => {3 it('Visits the Kitchen Sink', () => {4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 getAddress().then(address => {7 cy.log('Address: ' + address);8 });9 })10})11const {getAddress} = require('cy-address');12module.exports = (on, config) => {13 on('task', {14 });15}16import {getAddress} from 'cy-address';17Cypress.Commands.add('getAddress', getAddress);18describe('My First Test', () => {19 it('Visits the Kitchen Sink', () => {20 cy.contains('type').click()21 cy.url().should('include', '/commands/actions')22 cy.getAddress().then(address => {23 cy.log('Address: ' + address);24 });25 })26})27describe('My First Test', () => {28 it('Visits the Kitchen Sink', () => {29 cy.contains('type').click()30 cy.url().should('include', '/commands/actions')31 cy.task('getAddress').then(address => {32 cy.log('Address: ' + address);33 });34 })35})36describe('My First Test', () => {37 it('Visits the Kitchen Sink', () => {38 cy.contains('type').click()39 cy.url().should('include',

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input').getAddress()2cy.get('input').getAddress()3Cypress.Commands.add('getAddress', () => {4})5Cypress.Commands.add('getAddress', { prevSubject: 'element' }, () => {6})7cy.get('input').getAddress()8cy.get('input').getAddress()9Cypress.Commands.add('getAddress', () => {10})11Cypress.Commands.add('getAddress', { prevSubject: 'element' }, () => {12})13cy.get('input').getAddress()14cy.get('input').getAddress()15Cypress.Commands.add('getAddress', () => {16})17Cypress.Commands.add('getAddress', { prevSubject: 'element' }, () => {18})19cy.get('input').getAddress()20cy.get('input').getAddress()21Cypress.Commands.add('getAddress', () => {22})

Full Screen

Using AI Code Generation

copy

Full Screen

1var cypress = new Cypress();2var address = cypress.getAddress();3console.log(address);4function Cypress() {5 this.getAddress = function() {6 return "123 Main Street";7 }8}9module.exports = Cypress;

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input').getAddress().then((address) => {2});3Cypress.Commands.add('getAddress', {prevSubject: 'element'}, (subject) => {4 return cy.wrap(subject).invoke('val');5});6Cypress.Commands.add('getNumber', () => {7 return Math.floor(Math.random() * 10) + 1;8});9cy.getNumber().then((number) => {10});11Cypress.Commands.add('getNumber', (num) => {12 return Math.floor(Math.random() * 10) + 1 * num;13});14cy.getNumber(2).then((number) => {15});16Cypress.Commands.overwrite('click', (originalFn, subject, options) => {17 console.log('Clicking on an element');18 return originalFn(subject, options);19});20cy.get('button').click();21Custom commands can also be added to the Cypress.Commands interface using the Cypress.Commands.overwrite() method. This method will override the original method with the new custom method. For example, we can override

Full Screen

Using AI Code Generation

copy

Full Screen

1 .then((address) => {2 console.log(address);3 });4Cypress.Commands.add('getAddress', (url) => {5 return cy.request(url).then((response) => {6 return response.body;7 });8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const address = Cypress.env('address');2Cypress.log({3 consoleProps: () => {4 return {5 }6 },7});8{9 "env": {10 }11}12describe('My First Test', () => {13 it('Does not do much!', () => {14 cy.get('[data-cy=address]').click();15 cy.get('[data-cy=address]').type(Cypress.getAddress());16 cy.get('[data-cy=address]').should('have.value', Cypress.getAddress());17 })18})19describe('My First Test', () => {20 it('Does not do much!', () => {21 cy.get('[data-cy=address]').click();22 cy.get('[data-cy=address]').type(Cypress.getAddress());23 cy.get('[data-cy=address]').should('have.value', Cypress.getAddress());24 })25})26describe('My First Test', () => {27 it('Does not do much!', () => {28 cy.get('[data-cy=address]').click();29 cy.get('[data-cy=address]').type(Cypress.getAddress());30 cy.get('[data-cy=address]').should('have.value', Cypress.getAddress());31 })32})33describe('My First Test', () => {34 it('Does not do much!', () => {35 cy.get('[data-cy=address]').click();36 cy.get('[data-cy=address]').type(Cypress.getAddress());37 cy.get('[data-cy=address]').should('have.value', Cypress.getAddress());38 })39})40describe('My First Test', () => {41 it('Does not do much!', () => {42 cy.get('[data-cy=address]').click();43 cy.get('[data-cy=address]').type(Cypress.getAddress());44 cy.get('[data-cy=address]').should('have.value', Cypress.getAddress());45 })46})47describe('My First Test', () => {48 it('Does not do much!', () => {49 cy.get('[data-cy=address]').click();

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input').type('test').should('have.value', 'test')2cy.get('button').click()3cy.get('.message').should('be.visible')4cy.get('.message').should('have.text', 'test')5cy.get('button').click()6cy.get('.message').should('not.be.visible')7cy.get('.message').should('not.have.text', 'test')8cy.get('input').type('test').should('have.value', 'test')9cy.get('button').click()10cy.get('.message').should('be.visible')11cy.get('.message').should('have.text', 'test')12cy.get('button').click()13cy.get('.message').should('not.be.visible')14cy.get('.message').should('not.have.text', 'test')15cy.get('input').type('test').should('have.value', 'test')16cy.get('button').click()17cy.get('.message').should('be.visible')18cy.get('.message').should('have.text', 'test')19cy.get('button').click()20cy.get('.message').should('not.be.visible')21cy.get('.message').should('not.have.text', 'test')22cy.get('input').type('test').should('have.value', 'test')23cy.get('button').click()24cy.get('.message').should('be.visible')25cy.get('.message').should('have.text', 'test')26cy.get('button').click()27cy.get('.message').should('not.be.visible')28cy.get('.message').should('not.have.text', 'test')29cy.get('input').type('test').should('have.value', 'test')30cy.get('button').click()31cy.get('.message').should('be.visible')32cy.get('.message').should('have.text', 'test')33cy.get('button').click()34cy.get('.message').should('not.be.visible')35cy.get('.message').should('not.have.text', 'test')36cy.get('input').type('test').should('have.value', 'test')37cy.get('button').click()38cy.get('.message').should('be.visible')39cy.get('.message').should('

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful