From 1a2293739eb640228e64e02acfc8a761b99d890c Mon Sep 17 00:00:00 2001 From: Manohar Reddy Date: Tue, 19 Dec 2023 18:45:48 +0000 Subject: [PATCH] Sprint 1.11 (#1303) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag (#1220) * Feature/ Challenge based on rounds (#1191) * Fix * Fix * Fix * Fix * Fix * Debug * Debug * Debug * Fix * Heavy logging * Fix * More logging * Changed logging * Removed logging * Debug * Fix * Fix * Fix * expose send in wasm (#1225) * fix rename dir err (#1226) * Txnfee send (#1227) * add txnfee for send function * return txn verify output * add rename dir (#1230) * Async read (#1213) * basic timings for download * upload timings * to seconds * more timings for upload processing * display ms properly * cleanup * fix merge * fix merge * add more timing logs * fix dur to ms * add timings to read and build data * async read * range over errChan * fix unit test * rmv ctx cancel from multi upload * wait for last chunk * fix loop * rmv readChunk timing * increase buffer size * rmv timing logs * cleanup * updated go to version 1.20 * use -buildvcs=false --------- Co-authored-by: din-mukhammed Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: shahnawaz-creator Co-authored-by: Manohar Reddy * Wasm for `move`, `rename`, `copy` (#1233) * add demo for move, rename and copy * remove debug logs --------- Co-authored-by: Yury * Feat/streaming server in winsdk (#1228) * fix move when srcPath is same as destPath (#1239) * fix(upload):fixed invalid ffmpeg command in transcode feature (#1236) * fix(upload):fixed invalid ffmpeg command in transcode feature * fix(upload): always delete transcode output file * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(upload): fixed HideWindow issue * fix(devops): fixed build-windows * fix(mobilesdk): add logging for MultiUpload * fix(mobilesdk): fixed file permission issue on transcode * fixed lint error --------- Co-authored-by: dabasov * Fix web streaming - wasm (#1237) * Do not send GET http request with body * Use downloadBlocks to download in player_file * Call ListDir to get file meta * Format * Download 100 blocks each time by default * Fix downloadBlocks Track the downloaded bytes and trunk the padding 0 bytes * Update downloadBlocks to download blocks concurretly Use the same download method with downloadFileByBlocks * Add ActualFileSize in PlayListFile * Update wasm_exec.js to go 1.21.0 * Update version * Replace alloc.DownloadBlocks with DownloadBlocksToFileHandler * Add concurrency control (#1245) * control file ops concurrency * cleanup * add batch size to multi op * Fix/stream tests (#1247) * fix(upload): fixed file name issue in webstreaming * removed unused code * fix share consensus (#1246) * List optimization (#1240) * list optimization * list optimization * fix list hash * add to wg * fix list test * check consensus * fix listDir test * use once for mock calls * added sharders keep list (#1231) * added sharders keep list * added holder to zboxcore * removed duplicated sharder call * fixed lint * fixed panic * fixed panic * fixed panic * fixed panic * fixed panic * added consensus * added consensus * added consensus * refactored * refactored * refactored * chec alloc and prev alloc root (#1250) * add check for chunkNumber (#1253) * add check for chunkNumber * add err log * fix save progress * split-key handler implemented in wasm sdk * chnaging go version for cdn * bumped version * minor refactoring * bumping wasm_exec.js version * Refactoring unnecessary structs * create new conID (#1256) * debugging consoles added * fix statusbar update (#1257) * lint fixes * lint ignore * nolint: unused added * use httpdo for create connection (#1259) * Add create dir in repair (#1262) * fix delete dir err in cb * add way to create dir in repair * add desc for transaction data (#1263) * Feature: provide audit zcnswap and refactor if needed (#1205) * feature: modifies zcnswap to be consitent with zcnbridge * fix: fixed bugs * fix: removed dead code * feature: extended key store logic * fix: fixed bugs * fix: fixed conflicts * fix: removed dead code * fix: fixed bugs * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * fix * updated wasm binary build fix. * feature: added test case for swap logic * fix: resolved dependency conflicts * fix: fixed bugs * feature: added zcn eth rate fetch logic * Update blobber.go * Update authorizers_query.go * feature: replaced confusing param naming * fix: updated bridge initialization in wasm bridge integration * fix: replaced value amount with correct value * fix: wrong test case values * feature: switch to the usage of zcn token smart contract * fix: fixed bridge tests --------- Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: Yury Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator * Feat/exposed cli methods in winsdk (#1248) * feat(winsdk): added CreateWallet * feat(winsdk): added RecoverWallet * feat(winsdk): added logging in CreateWallet and RecoverWallet * feat(winsdk): split InitSDK into InitZCNSDK and InitWallets * feat(winsdk): fixed zboxApiClient initialization issue * feat(winsdk): renamed init sdks * feat(winsdk): fixed init zboxApiClient issue * fix(winsdk): fixed RecoverWallet naming * fix(winsdk): fixed file name issue in GetUploadStatus for transcode feature * feat(winsdk): added GetFileContentType in winsdk * feat(winsdk): added ListAllocations * feat(winsdk): added CreateFreeAllocation * feat(winsdk): added allocation methods * fix(winsdk): added logs * feat(zboxapi): added GetFreeStorage * feat(zboxapi): also send X-App-ID-Token in header * fix(winsdk): skip TestGetFreeStorage * fix(winsdk): added getAllocationWith * fix(zboxapi): used local signHash instead of sys.SignFunc * fix(zboxapi): fixed token issue in GetFreeStorage * fix(list): exported ThumbnailHash and ThumbnailSize in ListResult * fix(0box): fixed GetFreeStorage/CreateFreeAllocation * fix(winsdk): renamed jwtToken with token in CreateFreeAllocation * fix(winsdk): renamed jwtToken with token in CreateFreeAllocation * feat(winsdk): added GetFreeMarker * feat(winsdk): added AddSharedInfo/DeleteSharedInfo/GetSharedToMe/GetSharedByMe * feat(winsdk): added CreateAuthTicket/DeleteAuthTicket * feat(winsdk): fixed GetSharedToMe/GetSharedByMe * feat(winsdk): fixed GetSharedToMe/GetSharedByMe * feat(winsdk): exported CreateAuthTicket/DeleteAuthTicket/CreateSharedInfo/DeleteSharedInfo/GetSharedByMe/GetSharedByPublic/GetSharedToMe * Fix/fail shardedr on bad code (#1264) * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * updated wasm binary build fix. * README grammar and formatting tweaks. * Merge remote-tracking branch 'origin/feature/sharder-keep-list' into feature/sharder-keep-list --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator Co-authored-by: UncertainBadg3r <139782199+UncertainBadg3r@users.noreply.github.com> * Fix/roll logs (#1266) * Added lumberjack logger * Added lumberjack logger * fix:download file/thumbnail by authticket in winsdk (#1265) * feat(winsdk): added GetWalletBalance (#1267) * enabled gosdk update for sprint branches (#1268) * Revert "enabled gosdk update for sprint branches (#1268)" (#1269) This reverts commit 201b8bdc4f94b2aeb5eda3ce16f91b4327023654. * fix in progress callback (#1270) * Cleanup update terms from update allocation (#1274) * Improve download performance (#1271) * improve download performance * add read buffer size * add hash option * fix lint test * set default to true * log for data * fix read * feature: add reset nonce for bridge (#1279) * Add registerAuthorizer to wasm (#1275) * Hotfix/parse hostname error (#1241) * Fix/remove path (#1221) * feature: added more test cases * fix: fixed existing test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added more test cases * feature: added more test cases * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * feature: added mocks * fix: fixed bugs * fix: fixed mocks * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: made components internal * Add webstreaming to multiupload (#1190) * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * fix dup upload consensus (#1195) * Fix multiupload completed callback (#1172) * remove unnecessary print * fix delete and createdir * return major error * add webstreaming * fix typos * add webstreaming to wasm multiupload * fix typo * cleanup * fix completed callback * Feat/update methods in WinSDK (#1198) * delete dir in repair (#1196) * delete dir in repair * replace ioutil * fix unit test * fix list worker test * fix rename dir error * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * fix: fixed bugs * Add NFT Config contract (#1212) * Silent the zcnbridge http request when --silent (#1207) * Change the return type of downloadBlocks to []byte in wasm (#1218) * change the order of exchanges to get the ZCN prices (#1216) * Deprecate non multi-operation functions (#1214) * remove CreateDir, Rename, Copy, Move * use docker build wasm * use @v4 version of git action * Revert "use @v4 version of git action" This reverts commit fbb93f25a6ca63d6e205eac418d031bba428eb29. * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml * remove path header, fix ws tag --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed * Revert "Fix/remove path (#1221)" (#1222) This reverts commit 464260aa3c2be34fdc0aca58582b27247528333b. * remove path header, fix ws tag * remove path header, fix ws tag (#1223) * remove path header, fix ws tag * fixed broken build --------- Co-authored-by: din-mukhammed * Updated self hosted macos runner (#1219) * Updated self hosted macos runner * fixed runner name build-sdks.yml (cherry picked from commit 1c9f143fe842e6c88fec1a6bc5fa0ced2ca84682) * added logging * updated wasm binary build fix. * updated wasm binary build fix. (cherry picked from commit 257188873db1d21ccdb04eb7e5a35ff6ef6d7696) * README grammar and formatting tweaks. --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: Manohar Reddy Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator Co-authored-by: UncertainBadg3r <139782199+UncertainBadg3r@users.noreply.github.com> Co-authored-by: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> * Adding RegisterAuthorizer method in wasmsdk (#1273) * Adding RegisterAuthorizer method in wasmsdk * Fix:wasm test fail * Adding demo for RegisterAuthorizer handler in wasm * Js and Go bridge implementation * RegisterAuthorizer handler changes and adding Async Js bridge * golangci-lint fixes * Added error handling in setSplitKey and setAuthURL * Refactoring wasm exposed handlers * Setting split key wallet before setting auth url in setAuthURL's demo * Lint Fixes after resolving conflicts * upload optimization (#1281) * add sha256 simd and blake3 * add hash chan * fix lint and unit test * fix MHash * rmv timing log * fix thumbnail hash * added logging * added logging * hotfix * hotfix * experiment * experiment * experiment * experiment * experiment * experiment * experiment * experiment * experiment * experiment * experiment * Sprint 1.11 revert (#1284) * Revert "experiment" This reverts commit 050270f52815dcd930f760f20a4c7e3e669d73fb. * Revert "experiment" This reverts commit d4821f8e28c4efce59775129b4f25eaa1df2905d. * Revert "experiment" This reverts commit 9f65b2eef30528662b59482a6c59d6a633f1ff77. * Revert "experiment" This reverts commit 6313cb8a49d211ab8a6c476ca839922be7c31288. * Revert "experiment" This reverts commit b6be0b51767f39cb53a9439c3a34fe2f828b2dfc. * Revert "experiment" This reverts commit 68d41905a3aaf1c094d50f7b418349d7c78663cc. * Revert "experiment" This reverts commit 3a23f3f33b9446cf5711f950b0cd80a40993e429. * Revert "experiment" This reverts commit 6b6578bb857c9e4351db941fc84e65fac0994c15. * Revert "experiment" This reverts commit 65a0152adc10754977a479e09cdb8d577ca8aefb. * Revert "experiment" This reverts commit 6834b058a99bba80621c756292f7f4205b24e936. * Revert "experiment" This reverts commit 8446894c579f5acd14db1b09b5966f92ca1588be. * Revert "hotfix" This reverts commit 48cf793a70f754f44c662d839bdde4e191ec2748. * Revert "hotfix" This reverts commit 895c7f0012837d2f9a0cbfdcddf47f8dbe0d13b7. * Revert "added logging" This reverts commit fafce3c9b90c0863e574a2609a202f962ecb90ac. * Revert "added logging" This reverts commit 10b6a4afbdecc1e8a201d5ac80c4d12f0b97c411. * rmv channel hasher (#1285) * Fix submit txn (#1287) * Feature: add BNT, USDC and EURC tokens for Swap (#1277) * feature: add multiple token support for swap * feature: add correct Bancor API calls * feature: added approve for swap of bancor token * fix: removed debug lines * fix: fixed swap approval * fix: fixed bug * fix: fixed bugs * change hasher (#1288) * change hasher * set max proc to 1 * set batch size to 2 * revert hasher lib changes * increase batch size to 4 * set batch size to 2 * fix build * update chunk reader * run gc * add sleep and decrease batch size * change blake3 * fix operation slice * fix batch size * increase sleep time * add memory pool * increase swg for wasm * reuse chunk reader * fix read chunk * rmv unused package * Remove sleep and GOMAXPROCS=1 * Increase batch size a little --------- Co-authored-by: peterlimg * Import eth wallet with index (#1292) * Add import account address index * Make it optional * Feat/import-account-idx (#1294) * Add import account address index * Make it optional * Add account index option * Add account bip32 option (#1295) * Fix allocation min lock (#1297) * create PRs to dependent repos when a PR is merged to sprint branches (#1283) * create PRs to dependent repos when a PR is merged to sprint branches * add branch name * move wasm-build to build-sdk.yml * cleanup sdk-release.yml * Removed padding from the CryptoJS Encrypt and Decrypt functions functions. (#1300) Co-authored-by: Manohar Reddy * Fix allocation min lock * change chunkNumber for wasm (#1304) * change numBlock for wasm * change numBlocks * revert sdk changes * Feature: implement fork per run strategy (#1299) * feature: added fork creation * fix: fixed bug * feature: improved Tenderly fork creation flow * fix parse error (#1309) * fix parse error * fix log * add swg * Fix memory usage (#1311) * fix memory usage * change hasher to sha2 256 * fix unit test * increase numBlocks * fix thumbnail hash * Fix iso header (#1314) * add ISO check * remove filename field from authticket * fix typo * log auth token * cleanup * Fix zboxcore min submit (#1315) * Fix zboxcore min submit * Fix min submit and min confirmation default configs * Fix unit tests * Fix unit tests * Revert "Fix iso header (#1314)" (#1317) This reverts commit 218d3edd1a43dce1cfd1a700adcb33fb03a883f9. * Add upload for empty file (#1316) * add upload for empty file * fix hash * check ref * fix actual size * fix empty upload (#1320) * fix read auth ticket (#1319) * allocation validation for data parity shards (#1321) * fix git action to raise PRs to update gosdk (#1313) * test gosdk update * test-gosdk-update * use binary operators instead of terinary * use github.ref * use github ref * add branch name * use quotes * prepare for PR * test work flow dispatch * test extract branch * print env * prepare for PR * feature: added custom block number during Tenderly fork creation (#1323) * Fix/retry tx on nonce error (#1322) * Revert "experiment" This reverts commit 050270f52815dcd930f760f20a4c7e3e669d73fb. * Revert "experiment" This reverts commit d4821f8e28c4efce59775129b4f25eaa1df2905d. * Revert "experiment" This reverts commit 9f65b2eef30528662b59482a6c59d6a633f1ff77. * Revert "experiment" This reverts commit 6313cb8a49d211ab8a6c476ca839922be7c31288. * Revert "experiment" This reverts commit b6be0b51767f39cb53a9439c3a34fe2f828b2dfc. * Revert "experiment" This reverts commit 68d41905a3aaf1c094d50f7b418349d7c78663cc. * Revert "experiment" This reverts commit 3a23f3f33b9446cf5711f950b0cd80a40993e429. * Revert "experiment" This reverts commit 6b6578bb857c9e4351db941fc84e65fac0994c15. * Revert "experiment" This reverts commit 65a0152adc10754977a479e09cdb8d577ca8aefb. * Revert "experiment" This reverts commit 6834b058a99bba80621c756292f7f4205b24e936. * Revert "experiment" This reverts commit 8446894c579f5acd14db1b09b5966f92ca1588be. * Revert "hotfix" This reverts commit 48cf793a70f754f44c662d839bdde4e191ec2748. * Revert "hotfix" This reverts commit 895c7f0012837d2f9a0cbfdcddf47f8dbe0d13b7. * Revert "added logging" This reverts commit fafce3c9b90c0863e574a2609a202f962ecb90ac. * Revert "added logging" This reverts commit 10b6a4afbdecc1e8a201d5ac80c4d12f0b97c411. * retry failed transaction in zbox with nonce error * Fix wm rollback (#1324) * fix wm rollback * fix rb check * version logs * fix prev version * cleanup * Cleanup free storage update allocation (#1325) * remove batch size (#1327) * fix retry op callback (#1329) * Revert "remove batch size (#1327)" (#1328) This reverts commit 310edbb4d669566acc8cfc6e2940170d2da813fa. * Add `force` param for getAllocationBlobbers wasm (#1330) * fix retry callback (#1331) * Fix fill panic (#1334) * fix fill shards panic * add log for fill err --------- Co-authored-by: YarikRevich Co-authored-by: Yaroslav Svitlytskyi <53532703+YarikRevich@users.noreply.github.com> Co-authored-by: Dinmukhammed Kambarov <52813950+din-mukhammed@users.noreply.github.com> Co-authored-by: Hitenjain14 <57557631+Hitenjain14@users.noreply.github.com> Co-authored-by: Lz Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: peterlimg <54137706+peterlimg@users.noreply.github.com> Co-authored-by: Kishan Dhakan <42718091+Kishan-Dhakan@users.noreply.github.com> Co-authored-by: shahnawaz-creator <117025384+shahnawaz-creator@users.noreply.github.com> Co-authored-by: Jayash Satolia <73050737+Jayashsatolia403@users.noreply.github.com> Co-authored-by: din-mukhammed Co-authored-by: shahnawaz-creator Co-authored-by: Yury Co-authored-by: Ash-KODES Co-authored-by: Yaroslav Svitlytskyi Co-authored-by: UncertainBadg3r <139782199+UncertainBadg3r@users.noreply.github.com> Co-authored-by: peterlimg Co-authored-by: Tanishq Gupta <52757132+tanishq67@users.noreply.github.com> Co-authored-by: Jayash Satolia Co-authored-by: GuruHubb --- .github/workflows/build-sdks.yml | 47 +- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/system_tests.yml | 3 +- .github/workflows/tests.yml | 98 +- Makefile | 2 +- core/conf/config.go | 4 +- core/conf/config_test.go | 4 +- core/conf/vars.go | 5 + core/encryption/hash.go | 18 + core/node/cache.go | 53 + core/node/node.go | 362 ++ core/node/node_test.go | 45 + core/tokenrate/tokenrate.go | 4 +- core/transaction/cache.go | 144 - core/transaction/entity.go | 36 +- core/util/fixed_merkle_tree.go | 24 +- {zcncore => core/util}/http_consensus_maps.go | 2 +- core/util/merkle_tree_interface.go | 5 +- core/util/validation_tree.go | 10 +- core/util/validation_tree_test.go | 42 +- core/version/version.go | 2 +- generate_mocks.sh | 6 + go.mod | 29 +- go.sum | 229 +- mobilesdk/sdk/sdk.go | 2 +- mobilesdk/zbox/allocation.go | 32 +- mobilesdk/zbox/storage.go | 39 +- wasmsdk/README.md | 29 +- wasmsdk/allocation.go | 24 +- wasmsdk/auth_txn.go | 53 + wasmsdk/blobber.go | 188 +- wasmsdk/bridge.go | 40 +- wasmsdk/demo/index.html | 188 +- wasmsdk/demo/main.go | 1 + wasmsdk/demo/player.js | 23 +- wasmsdk/jsbridge/func.go | 16 +- wasmsdk/player_file.go | 83 +- wasmsdk/player_stream.go | 21 +- wasmsdk/proxy.go | 18 +- wasmsdk/sdk.go | 37 +- wasmsdk/statusbar.go | 5 +- wasmsdk/swap.go | 26 - wasmsdk/wallet_base.go | 43 + winsdk/allocation.go | 97 + winsdk/browser.go | 147 + winsdk/cache.go | 58 +- winsdk/helper.go | 29 +- winsdk/sdk.go | 176 +- winsdk/status.go | 24 +- winsdk/storage.go | 249 +- winsdk/stream.go | 254 ++ winsdk/stream_models.go | 101 + winsdk/wallet.go | 96 + winsdk/zboxapi.go | 213 +- zboxapi/response.go | 84 + zboxapi/sdk.go | 218 +- zboxapi/sdk_test.go | 163 +- zboxcore/allocationchange/moveobject.go | 86 +- zboxcore/allocationchange/renameobject.go | 5 +- zboxcore/blockchain/entity.go | 55 +- zboxcore/fileref/fileref.go | 40 +- zboxcore/mocks/AllocationChange.go | 2 +- zboxcore/mocks/EncryptionScheme.go | 84 +- zboxcore/mocks/FileNameBuilder.go | 95 + zboxcore/mocks/Hasher.go | 153 + zboxcore/mocks/HttpClient.go | 7 +- zboxcore/mocks/LiveUploadReader.go | 91 + zboxcore/mocks/M3u8Writer.go | 101 + zboxcore/mocks/RefEntity.go | 2 +- zboxcore/mocks/SCRestAPIHandler.go | 2 +- zboxcore/mocks/SignFunc.go | 49 + zboxcore/mocks/StatusCallback.go | 2 +- zboxcore/mocks/Suite.go | 2 +- zboxcore/mocks/codec.go | 56 - zboxcore/sdk/allocation.go | 240 +- zboxcore/sdk/allocation_file_copy_test.go | 142 - zboxcore/sdk/allocation_file_move_test.go | 129 - zboxcore/sdk/allocation_file_rename_test.go | 139 - zboxcore/sdk/allocation_test.go | 13 +- zboxcore/sdk/blockdownloadworker.go | 59 +- zboxcore/sdk/chunk_upload_vars.go | 10 + zboxcore/sdk/chunk_upload_vars_windows.go | 10 + zboxcore/sdk/chunked_upload.go | 260 +- zboxcore/sdk/chunked_upload_blobber.go | 2 - zboxcore/sdk/chunked_upload_chunk_reader.go | 56 +- .../chunked_upload_chunk_reader_bench_test.go | 2 +- .../sdk/chunked_upload_chunk_reader_test.go | 2 +- zboxcore/sdk/chunked_upload_form_builder.go | 7 +- zboxcore/sdk/chunked_upload_hasher.go | 4 +- zboxcore/sdk/chunked_upload_model.go | 104 +- zboxcore/sdk/chunked_upload_option.go | 10 +- zboxcore/sdk/chunked_upload_web_streaming.go | 62 +- zboxcore/sdk/commitworker.go | 8 +- zboxcore/sdk/dirworker.go | 19 - zboxcore/sdk/download_reqeust_header.go | 4 +- zboxcore/sdk/downloadworker.go | 75 +- zboxcore/sdk/listworker.go | 112 +- zboxcore/sdk/listworker_test.go | 13 +- zboxcore/sdk/moveworker.go | 1 + zboxcore/sdk/multi_operation_worker.go | 46 +- zboxcore/sdk/networkworker.go | 36 +- zboxcore/sdk/playlist.go | 17 +- zboxcore/sdk/repairworker.go | 15 + zboxcore/sdk/rollback.go | 11 +- zboxcore/sdk/sdk.go | 130 +- zboxcore/sdk/sync.go | 4 +- zboxcore/sdk/upload_worker.go | 17 +- zboxcore/sdk/writemarker_mutex.go | 5 + zboxcore/zboxutil/http.go | 72 +- zboxcore/zboxutil/transport.go | 1 + zboxcore/zboxutil/uint128_test.go | 3 +- zboxcore/zboxutil/util.go | 4 +- zcnbridge/bridge.go | 659 ++- zcnbridge/bridge_helper.go | 12 + zcnbridge/bridge_test.go | 547 ++- zcnbridge/config.go | 117 +- .../ethereum/bancornetwork/bancornetwork.go | 3757 +++++++++++++++++ zcnbridge/ethereum/bancortoken/bancortoken.go | 1556 +++++++ zcnbridge/ethereum/bind.sh | 7 - zcnbridge/ethereum/erc20/Context.sol | 24 - zcnbridge/ethereum/erc20/ERC20.sol | 356 -- zcnbridge/ethereum/erc20/IERC20.sol | 82 - zcnbridge/ethereum/erc20/IERC20Metadata.sol | 28 - zcnbridge/ethereum/erc20/erc20.go | 2319 ---------- zcnbridge/ethereum/nftconfig/nftconfig.go | 656 +++ zcnbridge/ethereum/zcntoken/zcntoken.go | 1336 ++++++ zcnbridge/ethereum_wallet.go | 110 - zcnbridge/http/client.go | 9 +- zcnbridge/http/rest.go | 38 +- zcnbridge/keystore.go | 68 +- zcnbridge/mocks/EthereumClient.go | 332 ++ zcnbridge/mocks/JobResult.go | 74 + zcnbridge/mocks/KeyStore.go | 112 + zcnbridge/mocks/Transaction.go | 135 + .../mocks/TransactionCallbackAwaitable.go | 74 + zcnbridge/mocks/TransactionProvider.go | 54 + zcnbridge/transaction/callback.go | 14 +- zcnbridge/transaction/functions.go | 24 +- zcnbridge/transaction/mocks/Transaction.go | 135 + .../mocks/TransactionCallbackAwaitable.go | 74 + .../transaction/mocks/TransactionProvider.go | 54 + zcnbridge/transaction/txn.go | 112 +- zcnbridge/wallet/wallet.go | 16 +- zcnbridge/wallets/README.md | 1 + ...--d8c9156e782c68ee671c09b6b92de76c97948432 | 1 + zcncore/mocks/AuthCallback.go | 2 +- zcncore/mocks/FeeOption.go | 33 + zcncore/mocks/GetBalanceCallback.go | 2 +- zcncore/mocks/GetInfoCallback.go | 2 +- zcncore/mocks/GetNonceCallback.go | 30 + zcncore/mocks/GetUSDInfoCallback.go | 15 - zcncore/mocks/MSVoteCallback.go | 2 +- zcncore/mocks/QueryResultHandle.go | 42 + zcncore/mocks/TransactionCallback.go | 2 +- zcncore/mocks/TransactionCommon.go | 567 +++ zcncore/mocks/TransactionScheme.go | 7 +- zcncore/mocks/WalletCallback.go | 2 +- zcncore/mswallet_base.go | 6 +- zcncore/networkworker.go | 25 +- zcncore/networkworker_mobile.go | 26 +- zcncore/transaction.go | 114 +- zcncore/transaction_base.go | 64 +- zcncore/transaction_mobile.go | 48 +- zcncore/transaction_query.go | 4 +- zcncore/transaction_query_mobile.go | 4 +- zcncore/transactionauth_base.go | 9 +- zcncore/wallet_base.go | 74 +- zcnswap/config/config.go | 69 - zcnswap/contracts/IERC20.sol | 14 - zcnswap/contracts/IQuoter.sol | 55 - zcnswap/contracts/ISwapRouter.sol | 79 - zcnswap/contracts/bancor.go | 445 -- zcnswap/contracts/erc20.go | 2319 ---------- zcnswap/contracts/erc20/Context.sol | 24 - zcnswap/contracts/erc20/ERC20.sol | 356 -- zcnswap/contracts/erc20/IERC20.sol | 82 - zcnswap/contracts/erc20/IERC20Metadata.sol | 28 - zcnswap/handler.go | 84 - zcnswap/swapfactory/bancor/bancor.abi | 1 - zcnswap/swapfactory/bancor/service.go | 236 -- zcnswap/swapfactory/erc20/allowance.go | 48 - zcnswap/swapfactory/erc20/erc20.abi | 222 - zcnswap/swapfactory/erc20/service.go | 77 - zcnswap/swapfactory/models.go | 121 - zcnswap/utils/ethconvert.go | 56 - zcnswap/utils/ethutils.go | 132 - zcnswap/utils/ethutils_test.go | 15 - zcnswap/utils/units.go | 29 - znft/example/go.mod | 18 +- znft/example/go.sum | 16 +- 190 files changed, 15301 insertions(+), 9827 deletions(-) create mode 100644 core/node/cache.go create mode 100644 core/node/node.go create mode 100644 core/node/node_test.go delete mode 100644 core/transaction/cache.go rename {zcncore => core/util}/http_consensus_maps.go (99%) create mode 100644 wasmsdk/auth_txn.go delete mode 100644 wasmsdk/swap.go create mode 100644 wasmsdk/wallet_base.go create mode 100644 winsdk/allocation.go create mode 100644 winsdk/browser.go create mode 100644 winsdk/stream.go create mode 100644 winsdk/stream_models.go create mode 100644 winsdk/wallet.go create mode 100644 zboxcore/mocks/FileNameBuilder.go create mode 100644 zboxcore/mocks/Hasher.go create mode 100644 zboxcore/mocks/LiveUploadReader.go create mode 100644 zboxcore/mocks/M3u8Writer.go create mode 100644 zboxcore/mocks/SignFunc.go delete mode 100644 zboxcore/mocks/codec.go delete mode 100644 zboxcore/sdk/allocation_file_copy_test.go delete mode 100644 zboxcore/sdk/allocation_file_move_test.go delete mode 100644 zboxcore/sdk/allocation_file_rename_test.go create mode 100644 zboxcore/sdk/chunk_upload_vars.go create mode 100644 zboxcore/sdk/chunk_upload_vars_windows.go create mode 100755 zcnbridge/ethereum/bancornetwork/bancornetwork.go create mode 100644 zcnbridge/ethereum/bancortoken/bancortoken.go delete mode 100755 zcnbridge/ethereum/bind.sh delete mode 100644 zcnbridge/ethereum/erc20/Context.sol delete mode 100644 zcnbridge/ethereum/erc20/ERC20.sol delete mode 100644 zcnbridge/ethereum/erc20/IERC20.sol delete mode 100644 zcnbridge/ethereum/erc20/IERC20Metadata.sol delete mode 100644 zcnbridge/ethereum/erc20/erc20.go create mode 100644 zcnbridge/ethereum/nftconfig/nftconfig.go create mode 100644 zcnbridge/ethereum/zcntoken/zcntoken.go delete mode 100644 zcnbridge/ethereum_wallet.go create mode 100644 zcnbridge/mocks/EthereumClient.go create mode 100644 zcnbridge/mocks/JobResult.go create mode 100644 zcnbridge/mocks/KeyStore.go create mode 100644 zcnbridge/mocks/Transaction.go create mode 100644 zcnbridge/mocks/TransactionCallbackAwaitable.go create mode 100644 zcnbridge/mocks/TransactionProvider.go create mode 100644 zcnbridge/transaction/mocks/Transaction.go create mode 100644 zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go create mode 100644 zcnbridge/transaction/mocks/TransactionProvider.go create mode 100644 zcnbridge/wallets/README.md create mode 100644 zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 create mode 100644 zcncore/mocks/FeeOption.go create mode 100644 zcncore/mocks/GetNonceCallback.go delete mode 100644 zcncore/mocks/GetUSDInfoCallback.go create mode 100644 zcncore/mocks/QueryResultHandle.go create mode 100644 zcncore/mocks/TransactionCommon.go delete mode 100644 zcnswap/config/config.go delete mode 100755 zcnswap/contracts/IERC20.sol delete mode 100755 zcnswap/contracts/IQuoter.sol delete mode 100755 zcnswap/contracts/ISwapRouter.sol delete mode 100755 zcnswap/contracts/bancor.go delete mode 100755 zcnswap/contracts/erc20.go delete mode 100755 zcnswap/contracts/erc20/Context.sol delete mode 100755 zcnswap/contracts/erc20/ERC20.sol delete mode 100755 zcnswap/contracts/erc20/IERC20.sol delete mode 100755 zcnswap/contracts/erc20/IERC20Metadata.sol delete mode 100644 zcnswap/handler.go delete mode 100755 zcnswap/swapfactory/bancor/bancor.abi delete mode 100755 zcnswap/swapfactory/bancor/service.go delete mode 100755 zcnswap/swapfactory/erc20/allowance.go delete mode 100755 zcnswap/swapfactory/erc20/erc20.abi delete mode 100755 zcnswap/swapfactory/erc20/service.go delete mode 100755 zcnswap/swapfactory/models.go delete mode 100755 zcnswap/utils/ethconvert.go delete mode 100755 zcnswap/utils/ethutils.go delete mode 100755 zcnswap/utils/ethutils_test.go delete mode 100755 zcnswap/utils/units.go diff --git a/.github/workflows/build-sdks.yml b/.github/workflows/build-sdks.yml index d21034514..2069e90b1 100644 --- a/.github/workflows/build-sdks.yml +++ b/.github/workflows/build-sdks.yml @@ -62,10 +62,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -159,17 +159,17 @@ jobs: run: | tag=$(echo ${GITHUB_REF#refs/tags/}) echo ${tag} - + if [[ "${{github.event_name}}" = "workflow_dispatch" ]]; then echo "> 0Chain: trigger from workflow_dispatch" echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - - + + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -237,10 +237,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -263,7 +263,6 @@ jobs: path: | zcncore-macos.tar.gz - build-windows: name: Build-windows runs-on: [self-hosted, arc-runner] @@ -306,10 +305,10 @@ jobs: echo "::set-output name=RELEASE::false" echo "::set-output name=TAG::none" - + elif [[ ${tag} = v*\.*\.* ]] ; then echo "> 0Chain: trigger from git event" - + # upload output on release echo "::set-output name=RELEASE::true" echo "::set-output name=TAG::${tag}" @@ -331,3 +330,29 @@ jobs: name: zcn-windows path: | zcn-windows.zip + + build-wasm: + name: Build-wasm + runs-on: [self-hosted, arc-runner] + steps: + - name: Set up Go 1.20 + uses: actions/setup-go@v2 + with: + go-version: ^1.20 + + - name: Checkout + uses: actions/checkout@v2 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get -y install build-essential nghttp2 libnghttp2-dev libssl-dev wget + + - name: Build + run: docker run --rm -v $PWD:/gosdk -w /gosdk golang:1.20 make wasm-build + + - name: 'Upload Artifact' + uses: actions/upload-artifact@v3 + with: + name: zcn.wasm + path: zcn.wasm diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ad6754aa0..78975fbb6 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -34,7 +34,7 @@ jobs: - name: Set up Go 1.x uses: actions/setup-go@v3 with: - go-version: ^1.18 + go-version: ^1.20 - name: Checkout repository uses: actions/checkout@v3 diff --git a/.github/workflows/system_tests.yml b/.github/workflows/system_tests.yml index 5a22964a9..a25e0cbfe 100644 --- a/.github/workflows/system_tests.yml +++ b/.github/workflows/system_tests.yml @@ -45,11 +45,10 @@ jobs: DEV8KC: ${{ secrets.DEV8KC }} DEV9KC: ${{ secrets.DEV9KC }} SUBGRAPH_API_URL: ${{ secrets.SUBGRAPH_API_URL }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_SECRET: ${{ secrets.TENDERLY_SECRET }} DEVOPS_CHANNEL_WEBHOOK_URL: ${{ secrets.DEVOPS_CHANNEL_WEBHOOK_URL }} GRAPHNODE_SC: ${{ secrets.GRAPHNODE_SC }} GRAPHNODE_NETWORK: ${{ secrets.GRAPHNODE_NETWORK }} - GRAPHNODE_ETHEREUM_NODE_URL: https://rpc.tenderly.co/fork/${{ secrets.TENDERLY_FORK_ID }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 762fcb83c..1245bfa55 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -108,6 +108,90 @@ jobs: echo "NETWORK_URL=$(echo dev-${RUNNER_NAME:(-1)}.devnet-0chain.net)" >> $GITHUB_ENV echo "RUNNER_NUMBER=${RUNNER_NAME:(-1)}" >> $GITHUB_ENV + - name: 'Setup jq' + uses: dcarbone/install-jq-action@v2.1.0 + with: + version: '1.7' + force: 'false' + + - name: "Create Tenderly fork" + run: | + echo "TENDERLY_CREATION_INFO=$(curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{"alias":"mainnet-dev-${{ env.RUNNER_NUMBER }}-${{ github.run_id }}${{ github.run_attempt }}", "description":"", "block_number": 18539779, "network_id":"1"}' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork)" >> $GITHUB_ENV + + - name: "Parse Tenderly fork creation transaction result" + run: | + echo "TENDERLY_FORK_ID=$(echo '${{ env.TENDERLY_CREATION_INFO }}' | jq -r '.simulation_fork.id')" >> $GITHUB_ENV + echo "TENDERLY_ROOT_TRANSACTION_ID=$(echo '${{ env.TENDERLY_CREATION_INFO }}' | jq -r '.root_transaction.id')" >> $GITHUB_ENV + + - name: "Retrieve Tenderly fork block number" + run: | + echo "TENDERLY_FORK_BLOCK_NUMBER=$(curl -X GET \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + https://api.tenderly.co/api/v1/network/1/block-number | jq -r '.block_number')" >> $GITHUB_ENV + + echo "TENDERLY_FORK_BLOCK_NUMBER=$((${{ env.TENDERLY_FORK_BLOCK_NUMBER }} + 1))" >> GITHUB_ENV + + - name: "Transfer Bridge ownership in Tenderly fork" + run: | + echo "TENDERLY_ROOT_TRANSACTION_ID=$(curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{ + "network_id": "1", + "block_number": ${{ env.TENDERLY_FORK_BLOCK_NUMBER }}, + "transaction_index": null, + "from": "0xed8f3170db6d1a71c8fa6d8d73cc2c51db95d5a4", + "input": "0xf2fde38b0000000000000000000000008e25cfd9bd6c0ca67a5522cd920b3c66d39d6e97", + "to": "0x7700d773022b19622095118fadf46f7b9448be9b", + "gas": 8000000, + "gas_price": "0", + "value": "0", + "access_list": [], + "generate_access_list": true, + "save": true, + "source": "dashboard", + "block_header": null, + "root": "${{ env.TENDERLY_ROOT_TRANSACTION_ID }}", + "skip_fork_head_update": false, + "alias": "", + "description": "Transfer ownership to 0x8E25cfd9bd6c0ca67a5522cd920b3c66D39d6E97" + }' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }}/simulate | jq -r '.simulation.id')" >> $GITHUB_ENV + + echo "TENDERLY_FORK_BLOCK_NUMBER=$((${{ env.TENDERLY_FORK_BLOCK_NUMBER }} + 1))" >> GITHUB_ENV + + - name: "Transfer Authorizers ownership in Tenderly fork" + run: | + curl -X POST \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + -d '{ + "network_id": "1", + "block_number": ${{ env.TENDERLY_FORK_BLOCK_NUMBER }}, + "transaction_index": null, + "from": "0xed8f3170db6d1a71c8fa6d8d73cc2c51db95d5a4", + "input": "0xf2fde38b0000000000000000000000008e25cfd9bd6c0ca67a5522cd920b3c66d39d6e97", + "to": "0x481dab4407b9880de0a68dc62e6af611c4949e42", + "gas": 8000000, + "gas_price": "0", + "value": "0", + "access_list": [], + "generate_access_list": true, + "save": true, + "source": "dashboard", + "block_header": null, + "root": "${{ env.TENDERLY_ROOT_TRANSACTION_ID }}", + "skip_fork_head_update": false, + "alias": "", + "description": "Transfer ownership to 0x8E25cfd9bd6c0ca67a5522cd920b3c66D39d6E97" + }' \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }}/simulate + - name: "Deploy 0Chain" uses: 0chain/actions/deploy-0chain@master with: @@ -116,10 +200,10 @@ jobs: teardown_condition: "TESTS_PASSED" custom_go_sdk_version: ${{ env.CURRENT_BRANCH_HEAD }} SUBGRAPH_API_URL: ${{ secrets.SUBGRAPH_API_URL }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_FORK_ID: ${{ env.TENDERLY_FORK_ID }} graphnode_sc: ${{ secrets.GRAPHNODE_SC }} graphnode_network: ${{ secrets.GRAPHNODE_NETWORK }} - graphnode_ethereum_node_url: https://rpc.tenderly.co/fork/${{ secrets.TENDERLY_FORK_ID }} + graphnode_ethereum_node_url: https://rpc.tenderly.co/fork/${{ env.TENDERLY_FORK_ID }} svc_account_secret: ${{ secrets.SVC_ACCOUNT_SECRET }} - name: "Run System tests" @@ -135,11 +219,19 @@ jobs: retry_failures: true run_frontend_tests: true run_smoke_tests: ${{ github.ref != 'refs/heads/staging' && github.base_ref != 'staging' && github.ref != 'refs/heads/master' && github.base_ref != 'master' }} - TENDERLY_FORK_ID: ${{ secrets.TENDERLY_FORK_ID }} + TENDERLY_FORK_ID: ${{ env.TENDERLY_FORK_ID }} DEVOPS_CHANNEL_WEBHOOK_URL: ${{ secrets.DEVOPS_CHANNEL_WEBHOOK_URL }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} + - name: "Remove Tenderly fork" + if: always() + run: | + curl -X DELETE \ + -H "x-access-key: ${{ secrets.TENDERLY_SECRET }}" \ + -H "Content-Type: application/json" \ + https://api.tenderly.co/api/v1/account/zus_network/project/project/fork/${{ env.TENDERLY_FORK_ID }} + - name: "Set PR status as ${{ job.status }}" if: ${{ (success() || failure()) && steps.findPr.outputs.number }} uses: 0chain/actions/set-pr-status@master diff --git a/Makefile b/Makefile index 22acd28d0..3398c21ea 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ gosdk-build: gomod-download go build -x -v -tags bn256 ./... wasm-build: getrev - CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -o ./zcn.wasm ./wasmsdk + CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -buildvcs=false -o ./zcn.wasm ./wasmsdk wasm-test: wasm-build env -i $(shell go env) PATH="$(shell go env GOROOT)/misc/wasm:$(PATH)" CGO_ENABLED=0 GOOS=js GOARCH=wasm go test -v github.com/0chain/gosdk/wasmsdk/jsbridge/... diff --git a/core/conf/config.go b/core/conf/config.go index aae29ff2a..5b770768e 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -13,9 +13,9 @@ import ( const ( // DefaultMinSubmit default value for min_submit - DefaultMinSubmit = 50 + DefaultMinSubmit = 10 // DefaultMinConfirmation default value for min_confirmation - DefaultMinConfirmation = 50 + DefaultMinConfirmation = 10 // DefaultMaxTxnQuery default value for max_txn_query DefaultMaxTxnQuery = 5 // DefaultConfirmationChainLength default value for confirmation_chain_length diff --git a/core/conf/config_test.go b/core/conf/config_test.go index a4d07142f..3eae68b8b 100644 --- a/core/conf/config_test.go +++ b/core/conf/config_test.go @@ -75,7 +75,7 @@ func TestLoadConfig(t *testing.T) { return mockDefaultReader() }, run: func(r *require.Assertions, cfg Config) { - r.Equal(50, cfg.MinSubmit) + r.Equal(10, cfg.MinSubmit) }, }, { @@ -109,7 +109,7 @@ func TestLoadConfig(t *testing.T) { return mockDefaultReader() }, run: func(r *require.Assertions, cfg Config) { - r.Equal(50, cfg.MinConfirmation) + r.Equal(10, cfg.MinConfirmation) }, }, { diff --git a/core/conf/vars.go b/core/conf/vars.go index 02457144b..508247e99 100644 --- a/core/conf/vars.go +++ b/core/conf/vars.go @@ -41,7 +41,12 @@ func GetClientConfig() (*Config, error) { // InitClientConfig set global client config func InitClientConfig(c *Config) { onceCfg.Do(func() { + sharderConsensous := c.SharderConsensous + if sharderConsensous < 1 { + sharderConsensous = DefaultSharderConsensous + } cfg = c + cfg.SharderConsensous = sharderConsensous }) } diff --git a/core/encryption/hash.go b/core/encryption/hash.go index 233ce7770..088de16c6 100644 --- a/core/encryption/hash.go +++ b/core/encryption/hash.go @@ -4,6 +4,7 @@ import ( "crypto/sha1" "encoding/hex" + "github.com/minio/sha256-simd" "golang.org/x/crypto/sha3" ) @@ -35,6 +36,23 @@ func RawHash(data interface{}) []byte { return hash.Sum(buf) } +func ShaHash(data interface{}) []byte { + var databuf []byte + switch dataImpl := data.(type) { + case []byte: + databuf = dataImpl + case HashBytes: + databuf = dataImpl[:] + case string: + databuf = []byte(dataImpl) + default: + panic("unknown type") + } + hash := sha256.New() + _, _ = hash.Write(databuf) + return hash.Sum(nil) +} + /*FastHash - sha1 hash the given data and return the hash as hex string */ func FastHash(data interface{}) string { return hex.EncodeToString(RawFastHash(data)) diff --git a/core/node/cache.go b/core/node/cache.go new file mode 100644 index 000000000..3e19d424d --- /dev/null +++ b/core/node/cache.go @@ -0,0 +1,53 @@ +package node + +import ( + "sync" +) + +var Cache *NonceCache +var once sync.Once + +type NonceCache struct { + cache map[string]int64 + guard sync.Mutex + sharders *NodeHolder +} + +func InitCache(sharders *NodeHolder) { + Cache.sharders = sharders +} + +func init() { + once.Do(func() { + Cache = &NonceCache{ + cache: make(map[string]int64), + } + }) +} + +func (nc *NonceCache) GetNextNonce(clientId string) int64 { + nc.guard.Lock() + defer nc.guard.Unlock() + if _, ok := nc.cache[clientId]; !ok { + nonce, _, err := nc.sharders.GetNonceFromSharders(clientId) + if err != nil { + nonce = 0 + } + nc.cache[clientId] = nonce + } + + nc.cache[clientId] += 1 + return nc.cache[clientId] +} + +func (nc *NonceCache) Set(clientId string, nonce int64) { + nc.guard.Lock() + defer nc.guard.Unlock() + nc.cache[clientId] = nonce +} + +func (nc *NonceCache) Evict(clientId string) { + nc.guard.Lock() + defer nc.guard.Unlock() + delete(nc.cache, clientId) +} diff --git a/core/node/node.go b/core/node/node.go new file mode 100644 index 000000000..4ff0a50fb --- /dev/null +++ b/core/node/node.go @@ -0,0 +1,362 @@ +package node + +import ( + "context" + "encoding/json" + stdErrors "errors" + "fmt" + "net/http" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/0chain/errors" + "github.com/0chain/gosdk/core/block" + "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/util" + "github.com/0chain/gosdk/zboxcore/logger" +) + +const statSize = 20 +const defaultTimeout = 5 * time.Second + +type NodeHolder struct { + consensus int + guard sync.Mutex + stats map[string]*Node + nodes []string +} + +type Node struct { + id string + weight int64 + stats []int +} + +func NewHolder(nodes []string, consensus int) *NodeHolder { + if len(nodes) < consensus { + panic("consensus is not correct") + } + holder := NodeHolder{consensus: consensus, stats: make(map[string]*Node)} + + for _, n := range nodes { + holder.nodes = append(holder.nodes, n) + holder.stats[n] = NewNode(n) + } + return &holder +} + +func NewNode(id string) *Node { + return &Node{ + id: id, + weight: 1, + stats: []int{1}, + } +} + +func (h *NodeHolder) Success(id string) { + h.guard.Lock() + defer h.guard.Unlock() + h.adjustNode(id, 1) +} + +func (h *NodeHolder) Fail(id string) { + h.guard.Lock() + defer h.guard.Unlock() + h.adjustNode(id, -1) +} + +func (h *NodeHolder) adjustNode(id string, res int) { + n := NewNode(id) + nodes := h.nodes + if node, ok := h.stats[id]; ok { + for i, v := range nodes { + if v == id { + nodes = append(nodes[:i], nodes[i+1:]...) + break + } + } + + sourceStats := node.stats + sourceStats = append(sourceStats, res) + if len(sourceStats) > statSize { + sourceStats = sourceStats[1:] + } + node.stats = sourceStats + + w := int64(0) + for i, s := range sourceStats { + w += int64(i+1) * int64(s) + } + node.weight = w + + n = node + } + + i := sort.Search(len(nodes), func(i int) bool { + return h.stats[nodes[i]].weight < n.weight + }) + h.nodes = append(nodes[:i], append([]string{n.id}, nodes[i:]...)...) +} + +func (h *NodeHolder) Healthy() (res []string) { + h.guard.Lock() + defer h.guard.Unlock() + + return h.nodes[:h.consensus] +} + +func (h *NodeHolder) All() (res []string) { + h.guard.Lock() + defer h.guard.Unlock() + + return h.nodes +} + +const consensusThresh = 25 +const ( + GET_BALANCE = `/v1/client/get/balance?client_id=` + CURRENT_ROUND = "/v1/current-round" + GET_BLOCK_INFO = `/v1/block/get?` +) + +func (h *NodeHolder) GetNonceFromSharders(clientID string) (int64, string, error) { + return h.GetBalanceFieldFromSharders(clientID, "nonce") +} + +func (h *NodeHolder) GetBalanceFieldFromSharders(clientID, name string) (int64, string, error) { + result := make(chan *util.GetResponse) + defer close(result) + // getMinShardersVerify + numSharders := len(h.Healthy()) + h.QueryFromSharders(numSharders, fmt.Sprintf("%v%v", GET_BALANCE, clientID), result) + + consensusMaps := util.NewHttpConsensusMaps(consensusThresh) + + for i := 0; i < numSharders; i++ { + rsp := <-result + if rsp == nil { + logger.Logger.Error("nil response") + continue + } + + logger.Logger.Debug(rsp.Url, rsp.Status) + if rsp.StatusCode != http.StatusOK { + logger.Logger.Error(rsp.Body) + + } else { + logger.Logger.Debug(rsp.Body) + } + + if err := consensusMaps.Add(rsp.StatusCode, rsp.Body); err != nil { + logger.Logger.Error(rsp.Body) + } + } + + rate := consensusMaps.MaxConsensus * 100 / numSharders + if rate < consensusThresh { + if strings.TrimSpace(consensusMaps.WinError) == `{"error":"value not present"}` { + return 0, consensusMaps.WinError, nil + } + return 0, consensusMaps.WinError, errors.New("", "get balance failed. consensus not reached") + } + + winValue, ok := consensusMaps.GetValue(name) + if ok { + winBalance, err := strconv.ParseInt(string(winValue), 10, 64) + if err != nil { + return 0, "", fmt.Errorf("get balance failed. %w", err) + } + + return winBalance, consensusMaps.WinInfo, nil + } + + return 0, consensusMaps.WinInfo, errors.New("", "get balance failed. balance field is missed") +} + +func (h *NodeHolder) QueryFromSharders(numSharders int, query string, + result chan *util.GetResponse) { + + h.QueryFromShardersContext(context.Background(), numSharders, query, result) +} + +func (h *NodeHolder) QueryFromShardersContext(ctx context.Context, numSharders int, + query string, result chan *util.GetResponse) { + + sharders := h.Healthy() + + for _, sharder := range util.Shuffle(sharders)[:numSharders] { + go func(sharderurl string) { + logger.Logger.Info("Query from ", sharderurl+query) + url := fmt.Sprintf("%v%v", sharderurl, query) + timeout, cancelFunc := context.WithTimeout(ctx, defaultTimeout) + defer cancelFunc() + + req, err := util.NewHTTPGetRequestContext(timeout, url) + if err != nil { + logger.Logger.Error(sharderurl, " new get request failed. ", err.Error()) + h.Fail(sharderurl) + result <- nil + return + } + res, err := req.Get() + if err != nil { + logger.Logger.Error(sharderurl, " get error. ", err.Error()) + } + + if res.StatusCode > http.StatusBadRequest { + h.Fail(sharderurl) + } else { + h.Success(sharderurl) + } + + result <- res + }(sharder) + } +} + +func (h *NodeHolder) GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *block.Block, err error) { + + var result = make(chan *util.GetResponse, numSharders) + defer close(result) + + numSharders = len(h.Healthy()) // overwrite, use all + h.QueryFromShardersContext(ctx, numSharders, + fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round), + result) + + var ( + maxConsensus int + roundConsensus = make(map[string]int) + ) + + type respObj struct { + Block *block.Block `json:"block"` + Header *block.Header `json:"header"` + } + + for i := 0; i < numSharders; i++ { + var rsp = <-result + if rsp == nil { + logger.Logger.Error("nil response") + continue + } + logger.Logger.Debug(rsp.Url, rsp.Status) + + if rsp.StatusCode != http.StatusOK { + logger.Logger.Error(rsp.Body) + continue + } + + var respo respObj + if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { + logger.Logger.Error("block parse error: ", err) + err = nil + continue + } + + if respo.Block == nil { + logger.Logger.Debug(rsp.Url, "no block in response:", rsp.Body) + continue + } + + if respo.Header == nil { + logger.Logger.Debug(rsp.Url, "no block header in response:", rsp.Body) + continue + } + + if respo.Header.Hash != string(respo.Block.Hash) { + logger.Logger.Debug(rsp.Url, "header and block hash mismatch:", rsp.Body) + continue + } + + b = respo.Block + b.Header = respo.Header + + var h = encryption.FastHash([]byte(b.Hash)) + if roundConsensus[h]++; roundConsensus[h] > maxConsensus { + maxConsensus = roundConsensus[h] + } + } + + if maxConsensus == 0 { + return nil, errors.New("", "round info not found") + } + + return +} + +func (h *NodeHolder) GetRoundFromSharders() (int64, error) { + + sharders := h.Healthy() + if len(sharders) == 0 { + return 0, stdErrors.New("get round failed. no sharders") + } + + result := make(chan *util.GetResponse, len(sharders)) + + var numSharders = len(sharders) + // use 5 sharders to get round + if numSharders > 5 { + numSharders = 5 + } + + h.QueryFromSharders(numSharders, fmt.Sprintf("%v", CURRENT_ROUND), result) + + const consensusThresh = float32(25.0) + + var rounds []int64 + + consensus := int64(0) + roundMap := make(map[int64]int64) + + round := int64(0) + + waitTimeC := time.After(10 * time.Second) + for i := 0; i < numSharders; i++ { + select { + case <-waitTimeC: + return 0, stdErrors.New("get round failed. consensus not reached") + case rsp := <-result: + if rsp == nil { + logger.Logger.Error("nil response") + continue + } + if rsp.StatusCode != http.StatusOK { + continue + } + + var respRound int64 + err := json.Unmarshal([]byte(rsp.Body), &respRound) + + if err != nil { + continue + } + + rounds = append(rounds, respRound) + + sort.Slice(rounds, func(i, j int) bool { + return false + }) + + medianRound := rounds[len(rounds)/2] + + roundMap[medianRound]++ + + if roundMap[medianRound] > consensus { + + consensus = roundMap[medianRound] + round = medianRound + rate := consensus * 100 / int64(numSharders) + + if rate >= int64(consensusThresh) { + return round, nil + } + } + } + } + + return round, nil +} diff --git a/core/node/node_test.go b/core/node/node_test.go new file mode 100644 index 000000000..ff9bcc490 --- /dev/null +++ b/core/node/node_test.go @@ -0,0 +1,45 @@ +package node + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNodeHolder_Success(t *testing.T) { + type fields struct { + nodes []string + consensus int + } + type args struct { + id string + } + type res struct { + res []string + } + tests := []struct { + name string + fields fields + args args + res res + }{ + {name: "init", fields: struct { + nodes []string + consensus int + }{nodes: []string{"1", "2", "3", "4", "5"}, consensus: 5}, args: struct{ id string }{id: "1"}, + res: struct{ res []string }{res: []string{"1", "2", "3", "4", "5"}}}, + {name: "pull up", fields: struct { + nodes []string + consensus int + }{nodes: []string{"1", "2", "3", "4", "5"}, consensus: 5}, args: struct{ id string }{id: "5"}, + res: struct{ res []string }{res: []string{"5", "1", "2", "3", "4"}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h := NewHolder(tt.fields.nodes, tt.fields.consensus) + h.Success(tt.args.id) + + assert.Equal(t, tt.res.res, h.Healthy()) + }) + } +} diff --git a/core/tokenrate/tokenrate.go b/core/tokenrate/tokenrate.go index 7c4d4d98a..d7decffeb 100644 --- a/core/tokenrate/tokenrate.go +++ b/core/tokenrate/tokenrate.go @@ -12,9 +12,9 @@ func init() { //priority: uniswap > bancor > coingecko > coinmarketcap quotes = []quoteQuery{ - &uniswapQuoteQuery{}, - &bancorQuoteQuery{}, &coingeckoQuoteQuery{}, + &bancorQuoteQuery{}, + &uniswapQuoteQuery{}, createCoinmarketcapQuoteQuery(), //more query services } diff --git a/core/transaction/cache.go b/core/transaction/cache.go deleted file mode 100644 index c9c24873d..000000000 --- a/core/transaction/cache.go +++ /dev/null @@ -1,144 +0,0 @@ -package transaction - -import ( - "context" - "encoding/json" - stdErrors "errors" - "fmt" - "net/http" - "strconv" - "sync" - "time" - - "github.com/0chain/gosdk/core/util" -) - -const GET_BALANCE = `/v1/client/get/balance?client_id=` -const consensusThresh = float32(25.0) - -var Cache *NonceCache -var once sync.Once - -type NonceCache struct { - cache map[string]int64 - guard sync.Mutex - sharders []string -} - -func InitCache(sharders []string) { - Cache.sharders = sharders -} - -func init() { - once.Do(func() { - Cache = &NonceCache{ - cache: make(map[string]int64), - } - }) -} - -func (nc *NonceCache) GetNextNonce(clientId string) int64 { - nc.guard.Lock() - defer nc.guard.Unlock() - if _, ok := nc.cache[clientId]; !ok { - nonce, _, err := nc.getNonceFromSharders(clientId) - if err != nil { - nonce = 0 - } - nc.cache[clientId] = nonce - } - - nc.cache[clientId] += 1 - return nc.cache[clientId] -} - -func (nc *NonceCache) Set(clientId string, nonce int64) { - nc.guard.Lock() - defer nc.guard.Unlock() - nc.cache[clientId] = nonce -} - -func (nc *NonceCache) Evict(clientId string) { - nc.guard.Lock() - defer nc.guard.Unlock() - delete(nc.cache, clientId) -} - -func queryFromSharders(sharders []string, query string, - result chan *util.GetResponse) { - - queryFromShardersContext(context.Background(), sharders, query, result) -} - -func (nc *NonceCache) getNonceFromSharders(clientID string) (int64, string, error) { - return GetBalanceFieldFromSharders(clientID, "nonce", nc.sharders) -} - -func GetBalanceFieldFromSharders(clientID, name string, sharders []string) (int64, string, error) { - result := make(chan *util.GetResponse, len(sharders)) - // getMinShardersVerify - var numSharders = len(sharders) // overwrite, use all - queryFromSharders(sharders, fmt.Sprintf("%v%v", GET_BALANCE, clientID), result) - consensus := float32(0) - balMap := make(map[int64]float32) - nonce := int64(0) - var winInfo string - waitTimeC := time.After(10 * time.Second) - for i := 0; i < numSharders; i++ { - select { - case <-waitTimeC: - return 0, "", stdErrors.New("get balance failed. consensus not reached") - case rsp := <-result: - if rsp.StatusCode != http.StatusOK { - continue - } - - var objmap map[string]json.RawMessage - err := json.Unmarshal([]byte(rsp.Body), &objmap) - if err != nil { - continue - } - if v, ok := objmap[name]; ok { - bal, err := strconv.ParseInt(string(v), 10, 64) - if err != nil { - continue - } - balMap[bal]++ - if balMap[bal] > consensus { - consensus = balMap[bal] - nonce = bal - winInfo = rsp.Body - - rate := consensus * 100 / float32(len(sharders)) - if rate >= consensusThresh { - return nonce, winInfo, nil - } - } - } - } - } - - return 0, "", stdErrors.New("get balance failed, consensus not reached") -} - -func queryFromShardersContext(ctx context.Context, sharders []string, - query string, result chan *util.GetResponse) { - - for _, sharder := range util.Shuffle(sharders) { - go func(sharderurl string) { - //Logger.Info("Query from ", sharderurl+query) - url := fmt.Sprintf("%v%v", sharderurl, query) - req, err := util.NewHTTPGetRequestContext(ctx, url) - if err != nil { - //Logger.Error(sharderurl, " new get request failed. ", err.Error()) - return - } - res, err := req.Get() - if err != nil { - //Logger.Error(sharderurl, " get error. ", err.Error()) - return - } - result <- res - }(sharder) - } -} diff --git a/core/transaction/entity.go b/core/transaction/entity.go index c123b5ec1..6c06356b0 100644 --- a/core/transaction/entity.go +++ b/core/transaction/entity.go @@ -110,7 +110,6 @@ const ( NEW_ALLOCATION_REQUEST = "new_allocation_request" NEW_FREE_ALLOCATION = "free_allocation_request" UPDATE_ALLOCATION_REQUEST = "update_allocation_request" - FREE_UPDATE_ALLOCATION = "free_update_allocation" LOCK_TOKEN = "lock" UNLOCK_TOKEN = "unlock" @@ -256,14 +255,45 @@ func (t *Transaction) VerifyTransaction(verifyHandler VerifyFunc) (bool, error) return verifyHandler(t.Signature, t.Hash, t.PublicKey) } -func SendTransactionSync(txn *Transaction, miners []string) { +func SendTransactionSync(txn *Transaction, miners []string) error { wg := sync.WaitGroup{} wg.Add(len(miners)) + fails := make(chan error, len(miners)) + for _, miner := range miners { url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL) - go sendTransactionToURL(url, txn, &wg) //nolint + go func() { + _, err := sendTransactionToURL(url, txn, &wg) + if err != nil { + fails <- err + } + }() //nolint } wg.Wait() + close(fails) + + failureCount := 0 + messages := make(map[string]int) + for e := range fails { + if e != nil { + failureCount++ + messages[e.Error()] += 1 + } + } + + max := 0 + dominant := "" + for m, s := range messages { + if s > max { + dominant = m + } + } + + if failureCount == len(miners) { + return errors.New("transaction_send_error", dominant) + } + + return nil } func sendTransactionToURL(url string, txn *Transaction, wg *sync.WaitGroup) ([]byte, error) { diff --git a/core/util/fixed_merkle_tree.go b/core/util/fixed_merkle_tree.go index 13f1ba306..f076034b5 100644 --- a/core/util/fixed_merkle_tree.go +++ b/core/util/fixed_merkle_tree.go @@ -10,7 +10,7 @@ import ( goError "errors" "github.com/0chain/errors" - "golang.org/x/crypto/sha3" + "github.com/minio/sha256-simd" ) const ( @@ -20,6 +20,16 @@ const ( FixedMTDepth = 11 ) +var ( + leafPool = sync.Pool{ + New: func() interface{} { + return &leaf{ + h: sha256.New(), + } + }, + } +) + type leaf struct { h hash.Hash } @@ -37,15 +47,20 @@ func (l *leaf) Write(b []byte) (int, error) { } func getNewLeaf() *leaf { - return &leaf{ - h: sha3.New256(), + l, ok := leafPool.Get().(*leaf) + if !ok { + return &leaf{ + h: sha256.New(), + } } + l.h.Reset() + return l } // FixedMerkleTree A trusted mekerle tree for outsourcing attack protection. see section 1.8 on whitepager // see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree type FixedMerkleTree struct { - // Leaves will store hash digester that calculates sha256 hash of the leaf content + // Leaves will store hash digester that calculates blake3 hash of the leaf content Leaves []Hashable `json:"leaves,omitempty"` writeLock sync.Mutex @@ -165,6 +180,7 @@ func (fmt *FixedMerkleTree) CalculateMerkleRoot() { nodes := make([][]byte, len(fmt.Leaves)) for i := 0; i < len(nodes); i++ { nodes[i] = fmt.Leaves[i].GetHashBytes() + leafPool.Put(fmt.Leaves[i]) } for i := 0; i < FixedMTDepth; i++ { diff --git a/zcncore/http_consensus_maps.go b/core/util/http_consensus_maps.go similarity index 99% rename from zcncore/http_consensus_maps.go rename to core/util/http_consensus_maps.go index 74acbb7d4..6f95f3b3a 100644 --- a/zcncore/http_consensus_maps.go +++ b/core/util/http_consensus_maps.go @@ -1,4 +1,4 @@ -package zcncore +package util import ( "crypto/sha1" diff --git a/core/util/merkle_tree_interface.go b/core/util/merkle_tree_interface.go index db1d6f9e3..cb3e773e6 100644 --- a/core/util/merkle_tree_interface.go +++ b/core/util/merkle_tree_interface.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "github.com/0chain/gosdk/core/encryption" + "github.com/minio/sha256-simd" ) /*MerkleTreeI - a merkle tree interface required for constructing and providing verification */ @@ -40,7 +41,9 @@ func MHashBytes(h1, h2 []byte) []byte { buf := make([]byte, len(h1)+len(h2)) copy(buf, h1) copy(buf[len(h1):], h2) - return encryption.RawHash(buf) + hash := sha256.New() + _, _ = hash.Write(buf) + return hash.Sum(nil) } /*MHash - merkle hashing of a pair of child hashes */ diff --git a/core/util/validation_tree.go b/core/util/validation_tree.go index 4a5bc0b6e..b7d94bdf7 100644 --- a/core/util/validation_tree.go +++ b/core/util/validation_tree.go @@ -9,7 +9,7 @@ import ( "math" "sync" - "golang.org/x/crypto/sha3" + "github.com/minio/sha256-simd" ) const ( @@ -99,7 +99,7 @@ func (v *ValidationTree) calculateRoot() { depth := v.CalculateDepth() nodes := make([][]byte, totalLeaves) copy(nodes, v.leaves) - h := sha3.New256() + h := sha256.New() for i := 0; i < depth; i++ { if len(nodes) == 1 { @@ -154,7 +154,7 @@ func NewValidationTree(dataSize int64) *ValidationTree { return &ValidationTree{ dataSize: dataSize, - h: sha3.New256(), + h: sha256.New(), leaves: make([][]byte, totalLeaves), } } @@ -223,7 +223,7 @@ If client had required data from 2-9 then blobber would have to provide: func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) error { hashes := make([][]byte, 0) - h := sha3.New256() + h := sha256.New() // Calculate hashes from the data responded from the blobber. for i := 0; i < len(data); i += MaxMerkleLeavesSize { endIndex := i + MaxMerkleLeavesSize @@ -270,7 +270,7 @@ func (m *MerklePathForMultiLeafVerification) VerifyMultipleBlocks(data []byte) e func (m *MerklePathForMultiLeafVerification) calculateIntermediateHashes(hashes [][]byte) [][]byte { newHashes := make([][]byte, 0) - h := sha3.New256() + h := sha256.New() if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { h.Reset() diff --git a/core/util/validation_tree_test.go b/core/util/validation_tree_test.go index 9dcdd251e..149aba444 100644 --- a/core/util/validation_tree_test.go +++ b/core/util/validation_tree_test.go @@ -8,8 +8,8 @@ import ( "math" "testing" + "github.com/minio/sha256-simd" "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" ) const ( @@ -144,8 +144,8 @@ func calculateValidationMerkleRoot(data []byte) []byte { if j > len(data) { j = len(data) } - h := sha3.New256() - h.Write(data[i:j]) + h := sha256.New() + _, _ = h.Write(data[i:j]) hashes = append(hashes, h.Sum(nil)) } @@ -156,20 +156,20 @@ func calculateValidationMerkleRoot(data []byte) []byte { newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := sha256.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := sha256.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) newHashes = append(newHashes, h.Sum(nil)) } - h := sha3.New256() - h.Write(hashes[len(hashes)-1]) + h := sha256.New() + _, _ = h.Write(hashes[len(hashes)-1]) newHashes = append(newHashes, h.Sum(nil)) } @@ -191,14 +191,14 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( hashes := make([][]byte, 0) nodesData := make([]byte, 0) - h := sha3.New256() + h := sha256.New() for i := 0; i < len(b); i += MaxMerkleLeavesSize { j := i + MaxMerkleLeavesSize if j > len(b) { j = len(b) } - h.Write(b[i:j]) + _, _ = h.Write(b[i:j]) leafHash := h.Sum(nil) hashes = append(hashes, leafHash) h.Reset() @@ -212,24 +212,24 @@ func calculateValidationRootAndNodes(b []byte, startInd, endInd int) ( newHashes := make([][]byte, 0) if len(hashes)%2 == 0 { for i := 0; i < len(hashes); i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := sha256.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) nodesData = append(nodesData, hashes[i+1]...) newHashes = append(newHashes, h.Sum(nil)) } } else { for i := 0; i < len(hashes)-1; i += 2 { - h := sha3.New256() - h.Write(hashes[i]) - h.Write(hashes[i+1]) + h := sha256.New() + _, _ = h.Write(hashes[i]) + _, _ = h.Write(hashes[i+1]) nodesData = append(nodesData, hashes[i]...) nodesData = append(nodesData, hashes[i+1]...) newHashes = append(newHashes, h.Sum(nil)) } - h := sha3.New256() - h.Write(hashes[len(hashes)-1]) + h := sha256.New() + _, _ = h.Write(hashes[len(hashes)-1]) nodesData = append(nodesData, hashes[len(hashes)-1]...) newHashes = append(newHashes, h.Sum(nil)) } diff --git a/core/version/version.go b/core/version/version.go index 738463466..6655d402c 100644 --- a/core/version/version.go +++ b/core/version/version.go @@ -2,5 +2,5 @@ //====== THIS IS AUTOGENERATED FILE. DO NOT MODIFY ======== package version -const VERSIONSTR = "v1.8.17-78-g80b63345" +const VERSIONSTR = "v1.10.0-141-gf81a4b84" diff --git a/generate_mocks.sh b/generate_mocks.sh index 6e619c31f..47bc8e63f 100755 --- a/generate_mocks.sh +++ b/generate_mocks.sh @@ -10,4 +10,10 @@ mockery --output=./mocks --all cd $BASEDIR/zcncore || exit mockery --output=./mocks --all +cd $BASEDIR/zcnbridge || exit +mockery --output=./mocks --all + +cd $BASEDIR/zcnbridge/transaction || exit +mockery --output=./mocks --all + echo "Mocks files are generated." \ No newline at end of file diff --git a/go.mod b/go.mod index dc0c1a9e9..58ef1951a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/0chain/gosdk -go 1.18 +go 1.20 require ( github.com/0chain/common v0.0.6-0.20230127095721-8df4d1d72565 @@ -18,8 +18,7 @@ require ( github.com/hashicorp/golang-lru/v2 v2.0.1 github.com/herumi/bls-go-binary v1.31.0 github.com/influxdata/influxdb v1.8.3 - github.com/klauspost/reedsolomon v1.11.7 - github.com/labstack/echo v3.3.10+incompatible + github.com/klauspost/reedsolomon v1.11.8 github.com/lithammer/shortuuid/v3 v3.0.7 github.com/machinebox/graphql v0.2.2 github.com/magma/augmented-networks/accounting/protos v0.1.1 @@ -44,11 +43,8 @@ require ( ) require ( - github.com/deckarep/golang-set v1.8.0 // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d - github.com/rjeczalik/notify v0.9.1 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + github.com/minio/sha256-simd v1.0.1 ) require ( @@ -59,6 +55,7 @@ require ( github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect @@ -67,6 +64,7 @@ require ( github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect + github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -74,18 +72,17 @@ require ( github.com/golang/glog v1.0.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect - github.com/golang/snappy v0.0.4 // indirect + github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect github.com/google/flatbuffers v22.9.29+incompatible // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/hashicorp/go-bexpr v0.1.10 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.2.0 // indirect + github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c // indirect github.com/huin/goupnp v1.0.3 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/kr/pretty v0.3.1 // indirect - github.com/labstack/gommon v0.4.0 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/matryer/is v1.4.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect @@ -99,6 +96,7 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/tsdb v0.7.1 // indirect github.com/rivo/uniseg v0.4.3 // indirect + github.com/rjeczalik/notify v0.9.1 // indirect github.com/rs/cors v1.7.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect @@ -114,27 +112,26 @@ require ( github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.0 // indirect github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa // indirect - github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasttemplate v1.2.2 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect go.dedis.ch/fixbuf v1.0.3 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.8.0 // indirect google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect ) require ( github.com/btcsuite/btcd/btcutil v1.1.3 - github.com/go-kit/kit v0.10.0 // indirect github.com/klauspost/compress v1.16.0 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/remeh/sizedwaitgroup v1.0.0 github.com/yusufpapurcu/wmi v1.2.2 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.9.0 // indirect - golang.org/x/net v0.7.0 // indirect + golang.org/x/net v0.8.0 // indirect golang.org/x/time v0.3.0 // indirect google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect ) diff --git a/go.sum b/go.sum index 4eed7ae32..bf726d25b 100644 --- a/go.sum +++ b/go.sum @@ -47,43 +47,25 @@ github.com/0chain/errors v1.0.3/go.mod h1:xymD6nVgrbgttWwkpSCfLLEJbFO6iHGQwk/yeS github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= -github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/Luzifer/go-openssl/v3 v3.1.0 h1:QqKqo6kYXGGUsvtUoCpRZm8lHw+jDfhbzr36gVj+/gw= github.com/Luzifer/go-openssl/v3 v3.1.0/go.mod h1:liy3FXuuS8hfDlYh1T+l78AwQ/NjZflJz0NDvjKhwDs= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= -github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= -github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/apache/arrow/go/arrow v0.0.0-20191024131854-af6fa24be0db/go.mod h1:VTxUBvSJ3s3eHAg65PNgrsn5BtqCRPdmyXh6rAfdxN0= -github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= -github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= -github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bmizerany/pat v0.0.0-20170815010413-6226ea591a40/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c= github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -113,8 +95,6 @@ github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/c-bata/go-prompt v0.2.2/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= -github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= -github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= @@ -125,23 +105,16 @@ github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -167,17 +140,12 @@ github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUn github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/didip/tollbooth v4.0.2+incompatible h1:fVSa33JzSz0hoh2NxpwZtksAzAgd7zjmGO20HCZtF4M= github.com/didip/tollbooth v4.0.2+incompatible/go.mod h1:A9b0665CE6l1KmzpDws2++elm/CsuWBMa5Jv4WY0PEY= -github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= -github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= -github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -186,7 +154,6 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ethereum/go-ethereum v1.10.26 h1:i/7d9RBBwiXCEuyduBQzJw/mKmnvzsN14jqBmytw72s= github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= @@ -194,8 +161,6 @@ github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSw github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= -github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= -github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= @@ -203,33 +168,25 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE= github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= -github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= @@ -240,7 +197,6 @@ github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgR github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= -github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -272,8 +228,9 @@ github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= @@ -292,7 +249,6 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -307,7 +263,6 @@ github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= @@ -316,43 +271,22 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= -github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= -github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= -github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpxn4uE= github.com/hashicorp/go-bexpr v0.1.10/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0= github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= @@ -361,18 +295,13 @@ github.com/hashicorp/golang-lru/v2 v2.0.1 h1:5pv5N1lT1fjLg2VQ5KWc7kmucp2x/kvFOnx github.com/hashicorp/golang-lru/v2 v2.0.1/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/herumi/bls-go-binary v1.31.0 h1:L1goQ2tMtGgpXCg5AwHAdJQpLs/pfnWWEc3Wog6OhmI= github.com/herumi/bls-go-binary v1.31.0/go.mod h1:O4Vp1AfR4raRGwFeQpr9X/PQtncEicMoOe6BQt1oX0Y= github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA= -github.com/holiman/uint256 v1.2.0 h1:gpSYcPLWGv4sG43I2mVLiDZCNDh/EpGjSk8tmtxitHM= -github.com/holiman/uint256 v1.2.0/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c h1:DZfsyhDK1hnSS5lH8l+JggqzEleHteTYfutAiVlSUM8= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c/go.mod h1:SC8Ryt4n+UBbPbIBKaG9zbbDlp4jOru9xFZmPzLUTxw= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ= github.com/huin/goupnp v1.0.3/go.mod h1:ZxNlw5WqJj6wSsRK5+YfflQGXYfccj5VgQsMNixHM7Y= github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= @@ -382,7 +311,6 @@ github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANyt github.com/influxdata/flux v0.65.1/go.mod h1:J754/zds0vvpfwuq7Gc2wRdVwEodfpCFM7mYlOw2LqY= github.com/influxdata/influxdb v1.8.3 h1:WEypI1BQFTT4teLM+1qkEcvUi0dAvopAI/ir0vAiBg8= github.com/influxdata/influxdb v1.8.3/go.mod h1:JugdFhsvvI8gadxOI6noqNeeBHvWNTbfYGtiAn+2jhI= -github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/influxdata/influxql v1.1.1-0.20200828144457-65d3ef77d385/go.mod h1:gHp9y86a/pxhjJ+zMjNXiQAA197Xk9wLxaz+fGG+kWk= github.com/influxdata/line-protocol v0.0.0-20180522152040-32c6aa80de5e/go.mod h1:4kt73NQhadE3daL3WhR5EJ/J2ocX0PZzwxQ0gXJ7oFE= github.com/influxdata/promql/v2 v2.12.0/go.mod h1:fxOPu+DY0bqCTCECchSRtWfc+0X19ybifQhZoQNF5D8= @@ -393,12 +321,8 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jsternberg/zap-logfmt v1.0.0/go.mod h1:uvPs/4X51zdkcm5jXl5SYoN+4RK21K8mysFmDaM/h+o= @@ -406,7 +330,6 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= @@ -420,8 +343,8 @@ github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZX github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg= github.com/klauspost/pgzip v1.0.2-0.20170402124221-0bf5dcad4ada/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= -github.com/klauspost/reedsolomon v1.11.7 h1:9uaHU0slncktTEEg4+7Vl7q7XUNMBUOK4R9gnKhMjAU= -github.com/klauspost/reedsolomon v1.11.7/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A= +github.com/klauspost/reedsolomon v1.11.8 h1:s8RpUW5TK4hjr+djiOpbZJB4ksx+TdYbRH7vHQpwPOY= +github.com/klauspost/reedsolomon v1.11.8/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= @@ -433,16 +356,9 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= -github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= -github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= -github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= -github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJVuvyJQQ8= github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= -github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/machinebox/graphql v0.2.2 h1:dWKpJligYKhYKO5A2gvNhkJdQMNZeChZYyBbrZkBZfo= github.com/machinebox/graphql v0.2.2/go.mod h1:F+kbVMHuwrQ5tYgU9JXlnskM8nOaFxCAEolaQybkjWA= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= @@ -453,16 +369,12 @@ github.com/magma/augmented-networks/accounting/protos v0.1.1/go.mod h1:Hpfg8aAxl github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= @@ -470,40 +382,23 @@ github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-tty v0.0.0-20180907095812-13ff1204f104/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= +github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8ohIXc3tViBH44KcwB2g4= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= -github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= -github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= -github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= -github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -516,84 +411,57 @@ github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= -github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= -github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/opentracing/opentracing-go v1.0.3-0.20180606204148-bd9c31933947/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= -github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= -github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/paulbellamy/ratecounter v0.2.0/go.mod h1:Hfx1hDpSGoqxkVVpBi/IlYD7kChlfo5C6hzIHwPqfFE= -github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= -github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/peterh/liner v1.0.1-0.20180619022028-8c1271fcf47f/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9 h1:6ob53CVz+ja2i7easAStApZJlh7sxyq3Cm7g1Di6iqA= github.com/philhofer/fwd v1.1.2-0.20210722190033-5c56ac6d0bb9/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= -github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pkg/term v0.0.0-20180730021639-bffc007b7fd5/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/remeh/sizedwaitgroup v1.0.0 h1:VNGGFwNo/R5+MJBf6yrsr110p0m4/OX4S3DCy7Kyl5E= +github.com/remeh/sizedwaitgroup v1.0.0/go.mod h1:3j2R4OIe/SeS6YDhICBy22RWjJC5eNCJ1V+9+NVNYlo= github.com/retailnext/hllpp v1.0.1-0.20180308014038-101a6d2f8b52/go.mod h1:RDpi1RftBQPUCDRw6SmxeaREsAaRKnOclghuzp/WRzc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw= github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rjeczalik/notify v0.9.1 h1:CLCKso/QK1snAlnhNR/CNvNiFU2saUtjV0bx3EwNeCE= github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -601,13 +469,9 @@ github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKl github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= @@ -622,7 +486,6 @@ github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tL github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -631,9 +494,6 @@ github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU= github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA= github.com/status-im/keycard-go v0.2.0 h1:QDLFswOQu1r5jsycloeQh3bVU8n/NatHHaZobtDnDzA= github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9+mHxBEeo3Hbg= -github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= @@ -660,23 +520,14 @@ github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+Kd github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= -github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/uptrace/bunrouter v1.0.20 h1:jNvYNcJxF+lSYBQAaQjnE6I11Zs0m+3M5Ek7fq/Tp4c= github.com/uptrace/bunrouter v1.0.20/go.mod h1:TwT7Bc0ztF2Z2q/ZzMuSVkcb/Ig/d3MQeP2cxn3e1hI= -github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa h1:5SqCsI/2Qya2bCzK15ozrqo2sZxkh0FHynJZOTVoV6Q= github.com/urfave/cli/v2 v2.17.2-0.20221006022127-8f469abc00aa/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI= -github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= -github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= -github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= @@ -697,10 +548,6 @@ go.dedis.ch/kyber/v3 v3.1.0/go.mod h1:kXy7p3STAurkADD+/aZcsznZGKVHEqbtmdIzvPfrs1 go.dedis.ch/protobuf v1.0.5/go.mod h1:eIV4wicvi6JK0q/QnfIEGeSFNG0ZeB24kzut5+HaRLo= go.dedis.ch/protobuf v1.0.7/go.mod h1:pv5ysfkDX/EawiPqcW3ikOxsL5t+BqnV6xHSmE79KI4= go.dedis.ch/protobuf v1.0.11/go.mod h1:97QR256dnkimeNdfmURz0wAMNVbd1VmLXhG1CrTYrJ4= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= -go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= -go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -710,33 +557,26 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= @@ -788,12 +628,8 @@ golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -804,7 +640,6 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -828,8 +663,8 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -853,33 +688,27 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190124100055-b90733256f2e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200107162124-548cf772de50/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -907,9 +736,6 @@ golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -917,8 +743,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -928,17 +754,15 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -957,8 +781,6 @@ golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -967,7 +789,6 @@ golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200108203644-89082a384178/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1009,7 +830,6 @@ gonum.org/v1/gonum v0.6.0/go.mod h1:9mxDZsDKxgMAuccQkewq682L+0eCu4dCN2yonUJTCLU= gonum.org/v1/netlib v0.0.0-20181029234149-ec6d1f5cefe6/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= -google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -1030,7 +850,6 @@ google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= @@ -1042,7 +861,6 @@ google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRn google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= google.golang.org/genproto v0.0.0-20190716160619-c506a9f90610/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= @@ -1078,15 +896,10 @@ google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= @@ -1121,23 +934,18 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/cheggaaa/pb.v1 v1.0.28 h1:n1tBJnnK2r7g9OW2btFH91V92STTUevLXYFb8gy9EMk= gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1149,7 +957,6 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -1161,5 +968,3 @@ rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8 rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/mobilesdk/sdk/sdk.go b/mobilesdk/sdk/sdk.go index 98a459286..3a18186f0 100644 --- a/mobilesdk/sdk/sdk.go +++ b/mobilesdk/sdk/sdk.go @@ -346,7 +346,7 @@ func (s *StorageSDK) UpdateAllocation(size int64, extend bool, allocationID stri return "", errors.Errorf("int64 overflow in lock") } - hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, true, "", "", false, &sdk.FileOptionsParameters{}) + hash, _, err = sdk.UpdateAllocation(size, extend, allocationID, lock, "", "", false, &sdk.FileOptionsParameters{}) return hash, err } diff --git a/mobilesdk/zbox/allocation.go b/mobilesdk/zbox/allocation.go index 51e1c6153..4114915e5 100644 --- a/mobilesdk/zbox/allocation.go +++ b/mobilesdk/zbox/allocation.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/sdk" @@ -200,7 +201,13 @@ func (a *Allocation) RenameObject(remotePath string, destName string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.RenameObject(remotePath, destName) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) } // GetStatistics - get allocation stats @@ -374,7 +381,13 @@ func (a *Allocation) CopyObject(path string, destPath string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.CopyObject(path, destPath) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: path, + DestPath: destPath, + }, + }) } // MoveObject - move object from path to dest @@ -382,7 +395,13 @@ func (a *Allocation) MoveObject(path string, destPath string) error { if a == nil || a.sdkAllocation == nil { return ErrInvalidAllocation } - return a.sdkAllocation.MoveObject(path, destPath) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: path, + DestPath: destPath, + }, + }) } // GetMinWriteRead - getting back cost for allocation @@ -455,7 +474,12 @@ func (a *Allocation) GetFirstSegment(localPath, remotePath, tmpPath string, dela } func (a *Allocation) CreateDir(dirName string) error { - return a.sdkAllocation.CreateDir(dirName) + return a.sdkAllocation.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: dirName, + }, + }) } var currentPlayback StreamingImpl diff --git a/mobilesdk/zbox/storage.go b/mobilesdk/zbox/storage.go index 3e88bb6ef..e0b1bb855 100644 --- a/mobilesdk/zbox/storage.go +++ b/mobilesdk/zbox/storage.go @@ -6,12 +6,12 @@ import ( "strings" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/sdk" ) -const SPACE string = " " - type fileResp struct { sdk.FileInfo Name string `json:"name"` @@ -325,8 +325,10 @@ func RepairFile(allocationID, workdir, localPath, remotePath, thumbnailPath stri // - error func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions string, statusCb StatusCallbackMocked) error { var options []MultiUploadOption + logger.Logger.Info("multiupload: ", jsonMultiUploadOptions) err := json.Unmarshal([]byte(jsonMultiUploadOptions), &options) if err != nil { + logger.Logger.Error("multiupload: ", err) return err } totalUploads := len(options) @@ -351,6 +353,7 @@ func MultiUpload(allocationID string, workdir string, jsonMultiUploadOptions str a, err := getAllocation(allocationID) if err != nil { + logger.Logger.Error("multiupload: ", err) return err } return a.StartMultiUpload(workdir, filePaths, fileNames, thumbnailPaths, encrypts, chunkNumbers, remotePaths, isUpdates, isWebstreaming, &StatusCallbackWrapped{Callback: statusCb}) @@ -468,7 +471,13 @@ func RenameObject(allocationID, remotePath string, destName string) error { if err != nil { return err } - return a.RenameObject(remotePath, destName) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) } // GetStatistics - get allocation stats @@ -747,7 +756,13 @@ func CopyObject(allocationID, path string, destPath string) error { if err != nil { return err } - return a.CopyObject(path, destPath) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCopy, + RemotePath: path, + DestPath: destPath, + }, + }) } // MoveObject - move object from path to dest @@ -760,7 +775,14 @@ func MoveObject(allocationID, path string, destPath string) error { if err != nil { return err } - return a.MoveObject(path, destPath) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationMove, + RemotePath: path, + DestPath: destPath, + }, + }) + } // CreateDir create empty directoy on remote blobbers @@ -773,7 +795,12 @@ func CreateDir(allocationID, dirName string) error { if err != nil { return err } - return a.CreateDir(dirName) + return a.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: dirName, + }, + }) } // RevokeShare revoke authTicket diff --git a/wasmsdk/README.md b/wasmsdk/README.md index eafe54e21..7f7adbaec 100644 --- a/wasmsdk/README.md +++ b/wasmsdk/README.md @@ -18,18 +18,6 @@ set bls.SecretKey on runtime env(browser,nodejs...etc), and call `zcn.sdk.setWal > N/A -### zcn.bulkUpload - -bulk upload files. it will wrap options, and call `zcn.sdk.bulkUpload` to process upload - -**Input**: - -> bulkOptions: [ { allocationId:string,remotePath:string,file:FileReader, thumbnailBytes:[]byte, encrypt:bool,isUpdate:bool,isRepair:bool,numBlocks:int,callback:function(totalBytes, completedBytes, error) } ] - -**Output**: - -> [ {remotePath:"/d.png", success:true,error:""} ] - ## ZCN methods ### zcn.sdk.init @@ -235,7 +223,7 @@ updates allocation settings **Input**: -> allocationId string, name string,size int64, extend bool,lock int64,setImmutable, updateTerms bool,addBlobberId, removeBlobberId string, setThirdPartyExtendable bool +> allocationId string, name string,size int64, extend bool,lock int64,setImmutable,addBlobberId, removeBlobberId string, setThirdPartyExtendable bool **Output**: @@ -497,16 +485,7 @@ download blocks of a file **Output**: -> {commandSuccess:bool, fileName:string,url:string, error:string} - -**Example** - -```json -{ - "commandSuccess": true, - "fileName": "scan3.png", - "url": "blob:http://localhost:3000/42157751-1d33-4448-88c8-7d7e2ad887a5" -} +> {[]byte, error:string} ``` ### zcn.sdk.upload @@ -521,7 +500,7 @@ upload file > {commandSuccess:bool, error:string} -### zcn.sdk.bulkUpload +### zcn.sdk.multiUpload bulk upload files with json options @@ -616,7 +595,7 @@ create folder from blobbers **Input**: -> allocationID string, size int, extend bool, updateTerms bool, addBlobberId string, removeBlobberId string +> allocationID string, size int, extend bool, addBlobberId string, removeBlobberId string **Output**: diff --git a/wasmsdk/allocation.go b/wasmsdk/allocation.go index f102af7cf..3812cf199 100644 --- a/wasmsdk/allocation.go +++ b/wasmsdk/allocation.go @@ -45,7 +45,7 @@ func createfreeallocation(freeStorageMarker string) (string, error) { func getAllocationBlobbers(preferredBlobberURLs []string, dataShards, parityShards int, size int64, - minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64) ([]string, error) { + minReadPrice, maxReadPrice, minWritePrice, maxWritePrice int64, force bool) ([]string, error) { if len(preferredBlobberURLs) > 0 { return sdk.GetBlobberIds(preferredBlobberURLs) @@ -57,7 +57,7 @@ func getAllocationBlobbers(preferredBlobberURLs []string, }, sdk.PriceRange{ Min: uint64(minWritePrice), Max: uint64(maxWritePrice), - }) + }, force) } func createAllocation(datashards, parityshards int, size int64, @@ -76,8 +76,8 @@ func createAllocation(datashards, parityshards int, size int64, Min: uint64(minWritePrice), Max: uint64(maxWritePrice), }, - Lock: uint64(lock), - BlobberIds: blobberIds, + Lock: uint64(lock), + BlobberIds: blobberIds, ThirdPartyExtendable: setThirdPartyExtendable, } @@ -121,7 +121,6 @@ func UpdateForbidAllocation(allocationID string, forbidupload, forbiddelete, for false, //extend, allocationID, // allocID, 0, //lock, - false, //updateTerms, "", //addBlobberId, "", //removeBlobberId, false, //thirdPartyExtendable, @@ -146,7 +145,6 @@ func freezeAllocation(allocationID string) (string, error) { false, //extend, allocationID, // allocID, 0, //lock, - false, //updateTerms, "", //addBlobberId, "", //removeBlobberId, false, //thirdPartyExtendable, @@ -182,7 +180,6 @@ func updateAllocationWithRepair(allocationID string, size int64, extend bool, lock int64, - updateTerms bool, addBlobberId, removeBlobberId string) (string, error) { sdk.SetWasm() allocationObj, err := sdk.GetAllocation(allocationID) @@ -194,7 +191,7 @@ func updateAllocationWithRepair(allocationID string, statusBar := &StatusBar{wg: wg, isRepair: true} wg.Add(1) - hash, err := allocationObj.UpdateWithRepair(size, extend, uint64(lock), updateTerms, addBlobberId, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) + hash, err := allocationObj.UpdateWithRepair(size, extend, uint64(lock), addBlobberId, removeBlobberId, false, &sdk.FileOptionsParameters{}, statusBar) if err == nil { clearAllocation(allocationID) } @@ -205,9 +202,8 @@ func updateAllocationWithRepair(allocationID string, func updateAllocation(allocationID string, size int64, extend bool, lock int64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool) (string, error) { - hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), updateTerms, addBlobberId, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) + hash, _, err := sdk.UpdateAllocation(size, extend, allocationID, uint64(lock), addBlobberId, removeBlobberId, setThirdPartyExtendable, &sdk.FileOptionsParameters{}) if err == nil { clearAllocation(allocationID) @@ -218,12 +214,11 @@ func updateAllocation(allocationID string, func getAllocationMinLock(datashards, parityshards int, size int64, - maxreadPrice, maxwritePrice uint64, + maxwritePrice uint64, ) (int64, error) { - readPrice := sdk.PriceRange{Min: 0, Max: maxreadPrice} writePrice := sdk.PriceRange{Min: 0, Max: maxwritePrice} - value, err := sdk.GetAllocationMinLock(datashards, parityshards, size, readPrice, writePrice) + value, err := sdk.GetAllocationMinLock(datashards, parityshards, size, writePrice) if err != nil { sdkLogger.Error(err) return 0, err @@ -236,9 +231,8 @@ func getUpdateAllocationMinLock( allocationID string, size int64, extend bool, - updateTerms bool, addBlobberId, removeBlobberId string) (int64, error) { - return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, updateTerms, addBlobberId, removeBlobberId) + return sdk.GetUpdateAllocationMinLock(allocationID, size, extend, addBlobberId, removeBlobberId) } func getRemoteFileMap(allocationID string) ([]*fileResp, error) { diff --git a/wasmsdk/auth_txn.go b/wasmsdk/auth_txn.go new file mode 100644 index 000000000..b2716c86c --- /dev/null +++ b/wasmsdk/auth_txn.go @@ -0,0 +1,53 @@ +//go:build js && wasm +// +build js,wasm + +package main + +import ( + "fmt" + "syscall/js" + + "github.com/0chain/gosdk/core/sys" +) + +type AuthCallbackFunc func(msg string) string + +var authCallback AuthCallbackFunc + +// Register the callback function +func registerAuthorizer(this js.Value, args []js.Value) interface{} { + // Store the callback function + authCallback = parseAuthorizerCallback(args[0]) + + sys.Authorize = func(msg string) (string, error) { + return authCallback(msg), nil + } + + return nil +} + +// Use the stored callback function +func callAuth(this js.Value, args []js.Value) interface{} { + fmt.Println("callAuth is called") + if len(args) == 0 { + return nil + } + + if authCallback != nil { + msg := args[0].String() + result, _ := sys.Authorize(msg) + fmt.Println("auth is called, result:", result) + return js.ValueOf(result) + } + + return nil +} + +// Parse the JavaScript callback function into Go AuthorizerCallback type +func parseAuthorizerCallback(jsCallback js.Value) AuthCallbackFunc { + return func(msg string) string { + // Call the JavaScript callback function from Go + result := jsCallback.Invoke(msg) + return result.String() + } +} diff --git a/wasmsdk/blobber.go b/wasmsdk/blobber.go index 153c6de23..cd9d59338 100644 --- a/wasmsdk/blobber.go +++ b/wasmsdk/blobber.go @@ -7,16 +7,18 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "path" - "path/filepath" "strings" "sync" "syscall/js" "time" + "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/wasmsdk/jsbridge" "github.com/0chain/gosdk/zboxcore/fileref" @@ -26,8 +28,6 @@ import ( const FileOperationInsert = "insert" -var allocObj *sdk.Allocation - func listObjects(allocationID string, remotePath string) (*sdk.ListResult, error) { alloc, err := getAllocation(allocationID) if err != nil { @@ -52,7 +52,12 @@ func createDir(allocationID, remotePath string) error { return err } - return allocationObj.CreateDir(remotePath) + return allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCreateDir, + RemotePath: remotePath, + }, + }) } // getFileStats get file stats from blobbers @@ -152,7 +157,14 @@ func Rename(allocationID, remotePath, destName string) (*FileCommandResponse, er return nil, err } - err = allocationObj.RenameObject(remotePath, destName) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationRename, + RemotePath: remotePath, + DestName: destName, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -187,7 +199,14 @@ func Copy(allocationID, remotePath, destPath string) (*FileCommandResponse, erro return nil, err } - err = allocationObj.CopyObject(remotePath, destPath) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationCopy, + RemotePath: remotePath, + DestPath: destPath, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -222,7 +241,14 @@ func Move(allocationID, remotePath, destPath string) (*FileCommandResponse, erro return nil, err } - err = allocationObj.MoveObject(remotePath, destPath) + err = allocationObj.DoMultiOperation([]sdk.OperationRequest{ + { + OperationType: constants.FileOperationMove, + RemotePath: remotePath, + DestPath: destPath, + }, + }) + if err != nil { PrintError(err.Error()) return nil, err @@ -305,71 +331,6 @@ func Share(allocationID, remotePath, clientID, encryptionPublicKey string, expir } -// download file -func download( - allocationID, remotePath, authTicket, lookupHash string, - downloadThumbnailOnly bool, numBlocks int, callbackFuncName string, isFinal bool) (*DownloadCommandResponse, error) { - - wg := &sync.WaitGroup{} - statusBar := &StatusBar{wg: wg} - if callbackFuncName != "" { - callback := js.Global().Get(callbackFuncName) - statusBar.callback = func(totalBytes, completedBytes int, filename, objURL, err string) { - callback.Invoke(totalBytes, completedBytes, filename, objURL, err) - } - } - wg.Add(1) - - if len(remotePath) == 0 && len(authTicket) == 0 { - return nil, RequiredArg("remotePath/authTicket") - } - - fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) - localPath := allocationID + "_" + fileName - var ( - err error - downloader sdk.Downloader - ) - - fs, _ := sys.Files.Open(localPath) - mf, _ := fs.(*sys.MemFile) - - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithOnlyThumbnail(downloadThumbnailOnly), - sdk.WithBlocks(0, 0, numBlocks), - sdk.WithFileHandler(mf)) - - if err != nil { - PrintError(err.Error()) - return nil, err - } - - defer sys.Files.Remove(localPath) //nolint - - err = downloader.Start(statusBar, isFinal) - - if err == nil { - wg.Wait() - } else { - PrintError("Download failed.", err.Error()) - return nil, err - } - if !statusBar.success { - return nil, errors.New("Download failed: unknown error") - } - - resp := &DownloadCommandResponse{ - CommandSuccess: true, - FileName: downloader.GetFileName(), - } - - resp.Url = CreateObjectURL(mf.Buffer.Bytes(), "application/octet-stream") - - return resp, nil - -} - // MultiOperation - do copy, move, delete and createdir operation together // ## Inputs // - allocationID @@ -553,7 +514,6 @@ func bulkUpload(jsonBulkUploadOptions string) ([]BulkUploadResult, error) { if err != nil { return nil, err } - n := len(options) wait := make(chan BulkUploadResult, 1) @@ -663,6 +623,9 @@ func multiUpload(jsonBulkUploadOptions string) (MultiUploadResult, error) { if numBlocks < 1 { numBlocks = 100 } + if allocationObj.DataShards > 7 { + numBlocks = 75 + } options := []sdk.ChunkedUploadOption{ sdk.WithThumbnail(option.ThumbnailBytes.Buffer), sdk.WithEncrypt(encrypt), @@ -749,6 +712,9 @@ func uploadWithJsFuncs(allocationID, remotePath string, readChunkFuncName string if numBlocks < 1 { numBlocks = 100 } + if allocationObj.DataShards > 7 { + numBlocks = 50 + } ChunkedUpload, err := sdk.CreateChunkedUpload("/", allocationObj, fileMeta, fileReader, isUpdate, isRepair, webStreaming, zboxutil.NewConnectionId(), sdk.WithThumbnail(thumbnailBytes), @@ -859,75 +825,45 @@ func upload(allocationID, remotePath string, fileBytes, thumbnailBytes []byte, w } // download download file blocks -func downloadBlocks(allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string, isFinal bool) (*DownloadCommandResponse, error) { - +func downloadBlocks(alloc *sdk.Allocation, remotePath, authTicket, lookupHash string, startBlock, endBlock int64) ([]byte, error) { if len(remotePath) == 0 && len(authTicket) == 0 { return nil, RequiredArg("remotePath/authTicket") } - wg := &sync.WaitGroup{} - statusBar := &StatusBar{wg: wg} - if callbackFuncName != "" { - callback := js.Global().Get(callbackFuncName) - statusBar.callback = func(totalBytes, completedBytes int, filename, objURL, err string) { - callback.Invoke(totalBytes, completedBytes, filename, objURL, err) - } - } - wg.Add(1) - - fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) - localPath := filepath.Join(allocationID, fileName) - - fs, _ := sys.Files.Open(localPath) - mf, _ := fs.(*sys.MemFile) - var ( - err error - downloader sdk.Downloader + wg = &sync.WaitGroup{} + statusBar = &StatusBar{wg: wg} ) - if allocObj == nil { - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithBlocks(startBlockNumber, endBlockNumber, numBlocks), - sdk.WithFileHandler(mf)) + fileName := strings.Replace(path.Base(remotePath), "/", "-", -1) + localPath := alloc.ID + "-" + fmt.Sprintf("%v-%s", startBlock, fileName) - } else { - downloader, err = sdk.CreateDownloader(allocationID, localPath, remotePath, - sdk.WithAuthticket(authTicket, lookupHash), - sdk.WithBlocks(startBlockNumber, endBlockNumber, numBlocks), - sdk.WithAllocation(allocObj), - sdk.WithFileHandler(mf)) + fs, err := sys.Files.Open(localPath) + if err != nil { + return nil, fmt.Errorf("could not open local file: %v", err) } - if err != nil { - PrintError(err.Error()) - return nil, err + mf, _ := fs.(*sys.MemFile) + if mf == nil { + return nil, fmt.Errorf("invalid memfile") } defer sys.Files.Remove(localPath) //nolint - err = downloader.Start(statusBar, isFinal) - - if err == nil { - wg.Wait() - } else { - PrintError("Download failed.", err.Error()) + wg.Add(1) + err = alloc.DownloadByBlocksToFileHandler( + mf, + remotePath, + startBlock, + endBlock, + 10, + false, + statusBar, true) + if err != nil { return nil, err } - if !statusBar.success { - return nil, errors.New("Download failed: unknown error") - } - - resp := &DownloadCommandResponse{ - CommandSuccess: true, - FileName: fileName, - } - - resp.Url = CreateObjectURL(mf.Buffer.Bytes(), "application/octet-stream") - - return resp, nil - + wg.Wait() + return mf.Buffer.Bytes(), nil } // GetBlobbersList get list of active blobbers, and format them as array json string diff --git a/wasmsdk/bridge.go b/wasmsdk/bridge.go index 80b236f4c..a06e4ddce 100644 --- a/wasmsdk/bridge.go +++ b/wasmsdk/bridge.go @@ -3,13 +3,16 @@ package main import ( "context" "encoding/json" + "path" "strconv" "time" "github.com/0chain/gosdk/zcnbridge" "github.com/0chain/gosdk/zcnbridge/errors" + "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/0chain/gosdk/zcnbridge/wallet" "github.com/0chain/gosdk/zcncore" + "github.com/ethereum/go-ethereum/ethclient" ) var bridge *zcnbridge.BridgeClient @@ -23,23 +26,34 @@ func initBridge( gasLimit uint64, value int64, consensusThreshold float64) error { - wallet := zcncore.GetWalletRaw() - if len(wallet.ClientID) == 0 { + if len(zcncore.GetWalletRaw().ClientID) == 0 { return errors.New("wallet_error", "wallet is not set") } - bridge = &zcnbridge.BridgeClient{ - EthereumAddress: ethereumAddress, - BridgeAddress: bridgeAddress, - AuthorizersAddress: authorizersAddress, - TokenAddress: tokenAddress, - Password: "", - EthereumNodeURL: ethereumNodeURL, - Homedir: ".", - GasLimit: gasLimit, - ConsensusThreshold: consensusThreshold, + ethereumClient, err := ethclient.Dial(ethereumNodeURL) + if err != nil { + return errors.New("wallet_error", err.Error()) } + transactionProvider := transaction.NewTransactionProvider() + + keyStore := zcnbridge.NewKeyStore( + path.Join(".", zcnbridge.EthereumWalletStorageDir)) + + bridge = zcnbridge.NewBridgeClient( + bridgeAddress, + tokenAddress, + authorizersAddress, + ethereumAddress, + "", + gasLimit, + consensusThreshold, + zcnbridge.BancorAPIURL, + ethereumClient, + transactionProvider, + keyStore, + ) + return nil } @@ -54,7 +68,7 @@ func burnZCN(amount, txnfee uint64) string { //nolint return errors.Wrap("burnZCN", "failed to burn ZCN tokens", err).Error() } - return tx.Hash + return tx.GetHash() } // Mints ZCN tokens and returns a hash of the mint transaction diff --git a/wasmsdk/demo/index.html b/wasmsdk/demo/index.html index 6b5867813..d7eee1b5d 100644 --- a/wasmsdk/demo/index.html +++ b/wasmsdk/demo/index.html @@ -3,7 +3,7 @@ - + @@ -36,19 +36,20 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates
Wallet
+ value="632d7e04fb8ff9cebe36caa20050458811d5eb3d3bdeb6a3877116a6c9d3ad68" />

+ value="1a82efcc1afa64468ba6d090da6ae4995e1c2c5fb3a107b01d5f67fe1f66bc08" />

+ value="aeb6a6c2bd30a9cd9323a46d887bfc9cf7996d0d2158a55453d7b16a99ace7182e998dd30c0d34c3093796f7075aaa97f3e25589c278971634cba3f2303b3216" />

+ value="visit acquire month friend twice guide hard myself differ video style shaft situate general valve dice brick carbon replace powder indicate hello orient search" />
+ @@ -152,8 +153,19 @@

please download zcn.wasm from https://github.com/0chain/gosdk/releases/lates

+
+ Split Key + + + + + + +
+
+
+
- + \ No newline at end of file diff --git a/wasmsdk/demo/main.go b/wasmsdk/demo/main.go index 762b553cc..ad0cab057 100644 --- a/wasmsdk/demo/main.go +++ b/wasmsdk/demo/main.go @@ -14,6 +14,7 @@ import ( func main() { zcncore.InitSignatureScheme("bls0chain") + ctx, cf := context.WithCancel(context.Background()) router := bunrouter.New() diff --git a/wasmsdk/demo/player.js b/wasmsdk/demo/player.js index b16a7cc48..eeddc5752 100644 --- a/wasmsdk/demo/player.js +++ b/wasmsdk/demo/player.js @@ -25,6 +25,27 @@ async function startPlay({ throw new Error('video element is required'); } + videoElement.addEventListener('error', function () { + switch (videoElement.error.code) { + case videoElement.error.MEDIA_ERR_ABORTED: + console.error("Fetch aborted by the user."); + break; + case videoElement.error.MEDIA_ERR_NETWORK: + console.error("Network error occurred."); + break; + case videoElement.error.MEDIA_ERR_DECODE: + console.error("Media decoding failed."); + break; + case videoElement.error.MEDIA_ERR_SRC_NOT_SUPPORTED: + console.error("Media not supported."); + break; + default: + console.error("An unknown error occurred."); + break; + } + }); + + await goWasm.sdk.play( allocationId, remotePath, authTicket, lookupHash, isLive); @@ -79,7 +100,7 @@ async function startPlay({ }).then(() => { // Auto-play started }); - } + } } diff --git a/wasmsdk/jsbridge/func.go b/wasmsdk/jsbridge/func.go index 7e520dd7d..1c35286fc 100644 --- a/wasmsdk/jsbridge/func.go +++ b/wasmsdk/jsbridge/func.go @@ -31,17 +31,21 @@ func BindFunc(global js.Value, jsFuncName string, fn interface{}) error { func BindAsyncFuncs(global js.Value, fnList map[string]interface{}) { for jsFuncName, fn := range fnList { - jsFunc, err := promise(fn) + if jsFuncName == "registerAuthorizer" || jsFuncName == "callAuth" { + global.Set(jsFuncName, fn) + } else { + jsFunc, err := promise(fn) - if err != nil { - log.Println(jsFuncName, err) - } + if err != nil { + log.Println("bridge promise failed:", jsFuncName, err) + } - global.Set(jsFuncName, jsFunc) + global.Set(jsFuncName, jsFunc) + } } - } + func BindFuncs(global js.Value, fnList map[string]interface{}) { for jsFuncName, fn := range fnList { diff --git a/wasmsdk/player_file.go b/wasmsdk/player_file.go index 03ee62008..440f65b9c 100644 --- a/wasmsdk/player_file.go +++ b/wasmsdk/player_file.go @@ -5,11 +5,8 @@ package main import ( "context" - "path/filepath" - "strconv" - "sync" + "fmt" - "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -27,6 +24,7 @@ type FilePlayer struct { playlistFile *sdk.PlaylistFile downloadedChunks chan []byte + downloadedLen int ctx context.Context cancel context.CancelFunc prefetchQty int @@ -61,59 +59,28 @@ func (p *FilePlayer) Stop() { } func (p *FilePlayer) download(startBlock int64) { - wg := &sync.WaitGroup{} - statusBar := &StatusBar{wg: wg} - wg.Add(1) - endBlock := startBlock + int64(p.numBlocks) - 1 if endBlock > p.playlistFile.NumBlocks { endBlock = p.playlistFile.NumBlocks } + fmt.Println("start:", startBlock, "end:", endBlock, "numBlocks:", p.numBlocks, "total:", p.playlistFile.NumBlocks) - fileName := strconv.FormatInt(startBlock, 10) + "-" + strconv.FormatInt(endBlock, 10) + "-" + p.playlistFile.Name - localPath := filepath.Join(p.allocationID, fileName) - - fs, _ := sys.Files.Open(localPath) - mf, _ := fs.(*sys.MemFile) - - downloader, err := sdk.CreateDownloader(p.allocationID, localPath, p.remotePath, - sdk.WithAllocation(p.allocationObj), - sdk.WithAuthticket(p.authTicket, p.lookupHash), - sdk.WithBlocks(startBlock, endBlock, p.numBlocks), - sdk.WithFileHandler(mf)) - + data, err := downloadBlocks(p.allocationObj, p.remotePath, p.authTicket, p.lookupHash, startBlock, endBlock) + // data, err := downloadBlocks2(int(startBlock), int(endBlock), p.allocationObj, p.remotePath) if err != nil { PrintError(err.Error()) return } - - defer sys.Files.Remove(localPath) //nolint - - PrintInfo("playlist: downloading blocks[", p.playlistFile.Name, ":", startBlock, "-", endBlock, "]") - err = downloader.Start(statusBar, true) - - if err == nil { - wg.Wait() - } else { - PrintError("Download failed.", err.Error()) - return - } - if !statusBar.success { - PrintError("Download failed: unknown error") - return - } - - PrintInfo("playlist: downloaded blocks[", p.playlistFile.Name, ":", startBlock, "-", endBlock, "]") - withRecover(func() { if p.downloadedChunks != nil { - p.downloadedChunks <- mf.Buffer.Bytes() + p.downloadedChunks <- data } }) } func (p *FilePlayer) startDownload() { + fmt.Println("start download") if p.playlistFile.NumBlocks < 1 { PrintError("playlist: numBlocks is invalid") return @@ -125,9 +92,11 @@ func (p *FilePlayer) startDownload() { PrintInfo("playlist: download is cancelled") return default: + fmt.Println("download start:", startBlock) p.download(startBlock) startBlock += int64(p.numBlocks) + fmt.Println("download end, new start:", startBlock) if startBlock > p.playlistFile.NumBlocks { @@ -144,19 +113,45 @@ func (p *FilePlayer) startDownload() { } func (p *FilePlayer) loadPlaylistFile() (*sdk.PlaylistFile, error) { - if p.isViewer { //get playlist file from auth ticket return sdk.GetPlaylistFileByAuthTicket(p.ctx, p.allocationObj, p.authTicket, p.lookupHash) } - //get playlist file from remote allocations's path - return sdk.GetPlaylistFile(p.ctx, p.allocationObj, p.remotePath) + d, err := p.allocationObj.ListDir(p.remotePath) + if err != nil { + fmt.Println("could not list dir:", p.remotePath) + return nil, err + } + f := d.Children[0] + var ( + dataShards = p.allocationObj.DataShards + effectivePerShardSize = (int(f.ActualSize) + dataShards - 1) / dataShards + totalBlocks = (effectivePerShardSize + sdk.DefaultChunkSize - 1) / sdk.DefaultChunkSize + ) + + fmt.Println("totalBlocks:", totalBlocks) + fmt.Println("file size:", f.Size) + + return &sdk.PlaylistFile{ + Name: f.Name, + Path: f.Path, + LookupHash: f.LookupHash, + NumBlocks: int64(totalBlocks), + Size: f.Size, + ActualFileSize: f.ActualSize, + MimeType: f.MimeType, + Type: f.Type, + }, nil } func (p *FilePlayer) GetNext() []byte { b, ok := <-p.downloadedChunks if ok { + if p.downloadedLen+len(b) > int(p.playlistFile.ActualFileSize) { + b = b[:int(p.playlistFile.ActualFileSize)-p.downloadedLen] + } + p.downloadedLen += len(b) return b } @@ -165,13 +160,13 @@ func (p *FilePlayer) GetNext() []byte { // createFilePalyer create player for remotePath func createFilePalyer(allocationID, remotePath, authTicket, lookupHash string) (*FilePlayer, error) { - player := &FilePlayer{} player.prefetchQty = 3 player.remotePath = remotePath player.authTicket = authTicket player.lookupHash = lookupHash player.numBlocks = 10 + player.allocationID = allocationID //player is viewer if len(authTicket) > 0 { diff --git a/wasmsdk/player_stream.go b/wasmsdk/player_stream.go index 7d4f1a09b..1ed3f358c 100644 --- a/wasmsdk/player_stream.go +++ b/wasmsdk/player_stream.go @@ -5,6 +5,7 @@ package main import ( "context" + "fmt" "path/filepath" "strings" "sync" @@ -176,8 +177,26 @@ func (p *StreamPlayer) loadList() ([]sdk.PlaylistFile, error) { return sdk.GetPlaylistByAuthTicket(p.ctx, p.allocationObj, p.authTicket, p.lookupHash, lookupHash) } + d, err := p.allocationObj.ListDir(p.remotePath) + if err != nil { + return nil, err + } + fmt.Printf("dir: %+v\n", d) + return []sdk.PlaylistFile{ + sdk.PlaylistFile{ + Name: d.Name, + Path: d.Path, + LookupHash: d.LookupHash, + NumBlocks: d.ActualNumBlocks, + Size: d.Size, + MimeType: d.MimeType, + Type: d.Type, + }, + }, nil + + // return []sdk.PlaylistFile{}, nil //get list from remote allocations's path - return sdk.GetPlaylist(p.ctx, p.allocationObj, p.remotePath, lookupHash) + // return sdk.GetPlaylist(p.ctx, p.allocationObj, p.remotePath, lookupHash) } func (p *StreamPlayer) GetNext() []byte { diff --git a/wasmsdk/proxy.go b/wasmsdk/proxy.go index acd6cb950..2f1c8f7b7 100644 --- a/wasmsdk/proxy.go +++ b/wasmsdk/proxy.go @@ -163,14 +163,9 @@ func main() { //blobber "delete": Delete, - "rename": Rename, - "copy": Copy, - "move": Move, "share": Share, - "download": download, "multiDownload": multiDownload, "upload": upload, - "bulkUpload": bulkUpload, "multiUpload": multiUpload, "multiOperation": MultiOperation, "listObjects": listObjects, @@ -184,6 +179,7 @@ func main() { "updatecontainer": UpdateContainer, "searchcontainer": SearchContainer, "updateForbidAllocation": UpdateForbidAllocation, + "send": send, // player "play": play, @@ -228,9 +224,7 @@ func main() { "executeSmartContract": executeSmartContract, "faucet": faucet, - //swap - "setSwapWallets": setSwapWallets, - "swapToken": swapToken, + // bridge "initBridge": initBridge, "burnZCN": burnZCN, "mintZCN": mintZCN, @@ -246,6 +240,14 @@ func main() { "createJwtSession": createJwtSession, "createJwtToken": createJwtToken, "refreshJwtToken": refreshJwtToken, + + //split key + "splitKeys": splitKeys, + "setWalletInfo": setWalletInfo, + "setAuthUrl": setAuthUrl, + + "registerAuthorizer": js.FuncOf(registerAuthorizer), + "callAuth": js.FuncOf(callAuth), }) fmt.Println("__wasm_initialized__ = true;") diff --git a/wasmsdk/sdk.go b/wasmsdk/sdk.go index ad9892829..b616d48ee 100644 --- a/wasmsdk/sdk.go +++ b/wasmsdk/sdk.go @@ -6,9 +6,11 @@ package main import ( "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" + "sync" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/imageutil" @@ -43,7 +45,7 @@ func initSDKs(chainID, blockWorker, signatureScheme string, fmt.Println("wasm: InitZCNSDK ", err) return err } - + sdk.SetWasm() return nil } @@ -121,3 +123,36 @@ func makeSCRestAPICall(scAddress, relativePath, paramsJson string) (string, erro b, err := zboxutil.MakeSCRestAPICall(scAddress, relativePath, params, nil) return string(b), err } + +func send(toClientID string, tokens uint64, fee uint64, desc string) (string, error) { + wg := &sync.WaitGroup{} + cb := &transactionCallback{wg: wg} + txn, err := zcncore.NewTransaction(cb, fee, 0) + if err != nil { + return "", err + } + + wg.Add(1) + err = txn.Send(toClientID, tokens, desc) + if err == nil { + wg.Wait() + } else { + return "", err + } + + if cb.success { + cb.success = false + wg.Add(1) + err := txn.Verify() + if err == nil { + wg.Wait() + } else { + return "", err + } + if cb.success { + return txn.GetVerifyOutput(), nil + } + } + + return "", errors.New(cb.errMsg) +} diff --git a/wasmsdk/statusbar.go b/wasmsdk/statusbar.go index bbf2fd7df..c04498d35 100644 --- a/wasmsdk/statusbar.go +++ b/wasmsdk/statusbar.go @@ -4,10 +4,11 @@ package main import ( - "github.com/0chain/gosdk/core/sys" - "gopkg.in/cheggaaa/pb.v1" "path" "sync" + + "github.com/0chain/gosdk/core/sys" + "gopkg.in/cheggaaa/pb.v1" ) // StatusBar is to check status of any operation diff --git a/wasmsdk/swap.go b/wasmsdk/swap.go deleted file mode 100644 index a5bd4f944..000000000 --- a/wasmsdk/swap.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "fmt" - - "github.com/0chain/gosdk/zcnswap" - "github.com/0chain/gosdk/zcnswap/config" -) - -func setSwapWallets(usdcTokenAddress, bancorAddress, zcnTokenAddress, ethWalletMnemonic string) { - config.Configuration = config.SwapConfig{ - UsdcTokenAddress: usdcTokenAddress, - BancorAddress: bancorAddress, - ZcnTokenAddress: zcnTokenAddress, - WalletMnemonic: ethWalletMnemonic, - } - - fmt.Println("[swap]wallets are initialized") -} - -func swapToken(swapAmount int64, tokenSource string) (string, error) { - return zcnswap.Swap(swapAmount, tokenSource) -} diff --git a/wasmsdk/wallet_base.go b/wasmsdk/wallet_base.go new file mode 100644 index 000000000..2915a7953 --- /dev/null +++ b/wasmsdk/wallet_base.go @@ -0,0 +1,43 @@ +package main + +import ( + "github.com/0chain/gosdk/zcncore" +) + +// Split keys from the primary master key + +// nolint: unused +func splitKeys(privateKey string, numSplits int) (string, error) { + wStr, err := zcncore.SplitKeys(privateKey, numSplits) + return wStr, err +} + +// SetWalletInfo should be set before any transaction or client specific APIs +// splitKeyWallet parameter is valid only if SignatureScheme is "BLS0Chain" +// # Inputs +// - jsonWallet: json format of wallet +// - splitKeyWallet: if wallet keys is split + +// nolint: unused +func setWalletInfo(jsonWallet string, splitKeyWallet bool) bool { + err := zcncore.SetWalletInfo(jsonWallet, splitKeyWallet) + if err == nil { + return true + } else { + return false + } +} + +// SetAuthUrl will be called by app to set zauth URL to SDK. +// # Inputs +// - url: the url of zAuth server + +// nolint: unused +func setAuthUrl(url string) bool { + err := zcncore.SetAuthUrl(url) + if err == nil { + return true + } else { + return false + } +} diff --git a/winsdk/allocation.go b/winsdk/allocation.go new file mode 100644 index 000000000..f121c2a1f --- /dev/null +++ b/winsdk/allocation.go @@ -0,0 +1,97 @@ +package main + +/* +#include +*/ +import ( + "C" +) +import ( + "encoding/json" + + "github.com/0chain/gosdk/zboxapi" + "github.com/0chain/gosdk/zboxcore/sdk" + "github.com/0chain/gosdk/zcncore" +) + +// GetAllocation get allocation info +// ## Inputs +// - allocationID +// +// ## Output +// +// { +// "error":"", +// "result":"{}", +// } +// +//export GetAllocation +func GetAllocation(allocationID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) + return WithJSON(getAllocation(allocID)) +} + +// ListAllocations get allocation list +// ## Output +// +// { +// "error":"", +// "result":"[{},{}]", +// } +// +//export ListAllocations +func ListAllocations() *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + items, err := sdk.GetAllocations() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(items, nil) +} + +// CreateFreeAllocation create a free allocation +// ## Inputs +// - freeMarker +// return +// { +// "error":"", +// "result":"id", +// } +// +//export CreateFreeAllocation +func CreateFreeAllocation(freemarker *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + marker := &zboxapi.FreeMarker{} + js := C.GoString(freemarker) + err := json.Unmarshal([]byte(js), marker) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + lock := zcncore.ConvertToValue(marker.FreeTokens) + + allocationID, _, err := sdk.CreateFreeAllocation(js, lock) + + if err != nil { + log.Error("win: ", err, "lock: ", lock, " marker:", js) + return WithJSON("", err) + } + + return WithJSON(allocationID, nil) +} diff --git a/winsdk/browser.go b/winsdk/browser.go new file mode 100644 index 000000000..8f4dca987 --- /dev/null +++ b/winsdk/browser.go @@ -0,0 +1,147 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "errors" + "strings" + + "github.com/0chain/gosdk/zboxcore/sdk" +) + +type RemoteFile struct { + sdk.FileInfo + Name string `json:"name"` + Path string `json:"path"` +} + +// ListAll - list all files from blobbers +// ## Inputs +// - allocationID +// +// ## Outputs +// +// { +// "error":"", +// "result":[{},{}]", +// } +// +//export ListAll +func ListAll(allocationID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + ref, err := alloc.GetRemoteFileMap(nil, "/") + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + files := make([]RemoteFile, 0) + for path, data := range ref { + paths := strings.SplitAfter(path, "/") + var f = RemoteFile{ + Name: paths[len(paths)-1], + Path: path, + FileInfo: data, + } + files = append(files, f) + } + + return WithJSON(files, nil) +} + +// List - list files from blobbers +// ## Inputs +// - allocationID +// - remotePath +// +// - authTicket +// - lookupHash +// +// ## Outputs +// +// { +// "error":"", +// "result":[{},{}]", +// } +// +//export List +func List(allocationID, remotePath, authTicket, lookupHash *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) + remotepath := C.GoString(remotePath) + authticket := C.GoString(authTicket) + lookuphash := C.GoString(lookupHash) + + if len(remotepath) == 0 && len(authticket) == 0 { + return WithJSON("[]", errors.New("Error: remotepath / authticket flag is missing")) + } + + if len(remotepath) > 0 { + if len(allocID) == 0 { + return WithJSON("[]", errors.New("Error: allocationID is missing")) + } + + allocationObj, err := getAllocation(allocID) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + ref, err := allocationObj.ListDir(remotepath) + if err != nil { + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + } + + return WithJSON(ref.Children, nil) + } + if len(authticket) > 0 { + + if len(lookuphash) == 0 { + return WithJSON("[]", errors.New("Error: lookuphash flag is missing")) + } + + allocationObj, _, err := getAllocationWith(authticket) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + at := sdk.InitAuthTicket(authticket) + lookuphash, err = at.GetLookupHash() + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + ref, err := allocationObj.ListDirFromAuthTicket(authticket, lookuphash) + if err != nil { + log.Error("win: ", err) + return WithJSON("[]", err) + } + + return WithJSON(ref.Children, nil) + } + return WithJSON("[]", nil) +} diff --git a/winsdk/cache.go b/winsdk/cache.go index 63efccde4..b5d4c918f 100644 --- a/winsdk/cache.go +++ b/winsdk/cache.go @@ -1,8 +1,12 @@ package main import ( + "encoding/base64" + "encoding/json" + "errors" "time" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" lru "github.com/hashicorp/golang-lru/v2" ) @@ -12,8 +16,14 @@ type cachedAllocation struct { Allocation *sdk.Allocation } +type cachedFileMeta struct { + CacheExpiresAt time.Time + FileMeta *sdk.ConsolidatedFileMeta +} + var ( cachedAllocations, _ = lru.New[string, *cachedAllocation](100) + cachedFileMetas, _ = lru.New[string, *cachedFileMeta](1000) ) func getAllocation(allocationID string) (*sdk.Allocation, error) { @@ -34,10 +44,56 @@ func getAllocation(allocationID string) (*sdk.Allocation, error) { it = &cachedAllocation{ Allocation: a, - CacheExpiresAt: time.Now().Add(5 * time.Minute), + CacheExpiresAt: time.Now().Add(30 * time.Minute), } cachedAllocations.Add(allocationID, it) return it.Allocation, nil } + +func getAllocationWith(authTicket string) (*sdk.Allocation, *marker.AuthTicket, error) { + + sEnc, err := base64.StdEncoding.DecodeString(authTicket) + if err != nil { + return nil, nil, errors.New("Error decoding the auth ticket." + err.Error()) + } + at := &marker.AuthTicket{} + err = json.Unmarshal(sEnc, at) + if err != nil { + return nil, nil, errors.New("Error unmarshaling the auth ticket." + err.Error()) + } + alloc, err := getAllocation(at.AllocationID) + return alloc, at, err +} + +func getFileMeta(allocationID, remotePath string) (*sdk.ConsolidatedFileMeta, error) { + + var it *cachedFileMeta + var ok bool + + it, ok = cachedFileMetas.Get(allocationID + ":" + remotePath) + + if ok && it.CacheExpiresAt.After(time.Now()) { + return it.FileMeta, nil + } + + a, err := getAllocation(allocationID) + if err != nil { + return nil, err + } + + f, err := a.GetFileMeta(remotePath) + if err != nil { + return nil, err + } + + it = &cachedFileMeta{ + FileMeta: f, + CacheExpiresAt: time.Now().Add(30 * time.Minute), + } + + cachedFileMetas.Add(allocationID, it) + + return it.FileMeta, nil +} diff --git a/winsdk/helper.go b/winsdk/helper.go index 1dbae6aa2..867ab2677 100644 --- a/winsdk/helper.go +++ b/winsdk/helper.go @@ -7,18 +7,27 @@ import ( "C" ) import ( + "encoding/base64" "encoding/json" "os" + "path/filepath" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/zboxcore/marker" - "github.com/0chain/gosdk/zboxcore/sdk" ) -func getHomeDir() string { - dir, _ := os.UserHomeDir() +func getZcnWorkDir() (string, error) { + d, err := os.UserHomeDir() + if err != nil { + return "", err + } + + z := filepath.Join(d, ".zcn") + + // create ~/.zcn folder if it doesn't exists + os.MkdirAll(z, 0766) //nolint: errcheck - return dir + return z, nil } type JsonResult struct { @@ -48,9 +57,17 @@ func getLookupHash(allocationID, path string) string { return encryption.Hash(allocationID + ":" + path) } -func getAuthTicket(authTicket *C.char) (*marker.AuthTicket, string, error) { +func decodeAuthTicket(authTicket *C.char) (*marker.AuthTicket, string, error) { at := C.GoString(authTicket) - t, err := sdk.InitAuthTicket(at).Unmarshall() + buf, err := base64.StdEncoding.DecodeString(at) + if err != nil { + return nil, at, err + } + t := &marker.AuthTicket{} + err = json.Unmarshal(buf, t) + if err != nil { + return nil, at, err + } return t, at, err } diff --git a/winsdk/sdk.go b/winsdk/sdk.go index 2dbcacc2d..667da05a3 100644 --- a/winsdk/sdk.go +++ b/winsdk/sdk.go @@ -29,7 +29,6 @@ import ( var log logger.Logger func main() { - } // SetLogFile - set log file @@ -38,6 +37,11 @@ func main() { // //export SetLogFile func SetLogFile(file *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() f, err := os.OpenFile(C.GoString(file), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { @@ -53,27 +57,16 @@ func SetLogFile(file *C.char) *C.char { zboxutil.GetLogger().SetLevel(logger.DEBUG) zboxutil.GetLogger().SetLogFile(f, true) + zboxapi.GetLogger().SetLevel(logger.DEBUG) + zboxapi.GetLogger().SetLogFile(f, true) + log.SetLogFile(f, true) log.SetLevel(logger.DEBUG) return WithJSON(true, nil) } -// InitSDK - init zbox/zcn sdk from config -// - clientJson -// { -// "client_id":"8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0", -// "client_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", -// "keys":[ -// { -// "public_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", -// "private_key":"72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" -// }], -// "mnemonics":"abandon mercy into make powder fashion butter ignore blade vanish plastic shock learn nephew matrix indoor surge document motor group barely offer pottery antenna", -// "version":"1.0", -// "date_created":"1668667145", -// "nonce":0 -// } +// InitSDKs - init zcncore sdk and zboxapi client from config // - configJson // { // "block_worker": "https://dev.0chain.net/dns", @@ -91,13 +84,17 @@ func SetLogFile(file *C.char) *C.char { // "sharder_consensous": 2, // } // -//export InitSDK -func InitSDK(configJson *C.char, clientJson *C.char) *C.char { +//export InitSDKs +func InitSDKs(configJson *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() - l.Logger.Info("Start InitStorageSDK") + l.Logger.Info("Start InitSDKs") configJs := C.GoString(configJson) - clientJs := C.GoString(clientJson) configObj := &conf.Config{} @@ -121,7 +118,7 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { return nil }) if err != nil { - l.Logger.Error(err, configJs, clientJs) + l.Logger.Error(err, configJs) return WithJSON(false, err) } @@ -131,15 +128,56 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { l.Logger.Info(configObj.SignatureScheme) l.Logger.Info(configObj.PreferredBlobbers) + if zboxApiClient == nil { + zboxApiClient = zboxapi.NewClient() + } + + zboxApiClient.SetRequest(configObj.ZboxHost, configObj.ZboxAppType) + l.Logger.Info("Init ZBoxAPI Client success") + + return WithJSON(true, nil) +} + +// InitWallet - init wallet for storage sdk and zboxapi client +// - clientJson +// { +// "client_id":"8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0", +// "client_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", +// "keys":[ +// { +// "public_key":"c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4", +// "private_key":"72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" +// }], +// "mnemonics":"abandon mercy into make powder fashion butter ignore blade vanish plastic shock learn nephew matrix indoor surge document motor group barely offer pottery antenna", +// "version":"1.0", +// "date_created":"1668667145", +// "nonce":0 +// } +// +//export InitWallet +func InitWallet(clientJson *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + l.Logger.Info("Start InitStorageSDK") + + clientJs := C.GoString(clientJson) + + configObj, err := conf.GetClientConfig() + if err != nil { + l.Logger.Error(err) + return WithJSON(false, err) + } + err = sdk.InitStorageSDK(clientJs, configObj.BlockWorker, configObj.ChainID, configObj.SignatureScheme, configObj.PreferredBlobbers, 0) if err != nil { - l.Logger.Error(err, configJs, clientJs) + l.Logger.Error(err, clientJs) return WithJSON(false, err) } l.Logger.Info("InitStorageSDK success") - zboxApiClient = zboxapi.NewClient() - zboxApiClient.SetRequest(configObj.ZboxHost, configObj.ZboxAppType) c := client.GetClient() if c != nil { zboxApiClient.SetWallet(client.GetClientID(), client.GetClientPrivateKey(), client.GetClientPublicKey()) @@ -148,7 +186,7 @@ func InitSDK(configJson *C.char, clientJson *C.char) *C.char { l.Logger.Info("InitZboxApiClient skipped") } - l.Logger.Info("Init successful") + l.Logger.Info("InitSDKs successful") return WithJSON(true, nil) } @@ -164,6 +202,11 @@ var ErrInvalidSignatureScheme = errors.New("invalid_signature_scheme") // //export SignRequest func SignRequest(privateKey, signatureScheme, data *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() key := C.GoString(privateKey) scheme := C.GoString(signatureScheme) d := C.GoString(data) @@ -185,7 +228,11 @@ func SignRequest(privateKey, signatureScheme, data *C.char) *C.char { // //export VerifySignature func VerifySignature(publicKey, signatureScheme string, data string, signature string) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() hash := encryption.Hash(data) signScheme := zcncrypto.NewSignatureScheme(signatureScheme) @@ -209,6 +256,11 @@ func VerifySignature(publicKey, signatureScheme string, data string, signature s // //export CryptoJsEncrypt func CryptoJsEncrypt(passphrase, message *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() pass := C.GoString(passphrase) msg := C.GoString(message) @@ -225,6 +277,11 @@ func CryptoJsEncrypt(passphrase, message *C.char) *C.char { // //export CryptoJsDecrypt func CryptoJsDecrypt(passphrase, encryptedMessage *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() pass := C.GoString(passphrase) msg := C.GoString(encryptedMessage) @@ -241,6 +298,11 @@ func CryptoJsDecrypt(passphrase, encryptedMessage *C.char) *C.char { // //export GetPublicEncryptionKey func GetPublicEncryptionKey(mnemonics *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() m := C.GoString(mnemonics) return WithJSON(zcncore.GetPublicEncryptionKey(m)) } @@ -257,6 +319,68 @@ func GetPublicEncryptionKey(mnemonics *C.char) *C.char { // //export GetLookupHash func GetLookupHash(allocationID *C.char, path *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() hash := getLookupHash(C.GoString(allocationID), C.GoString(path)) return WithJSON(hash, nil) } + +// SetFFmpeg set the full file name of ffmpeg.exe +// ## Inputs: +// - fullFileName +// return +// { +// "error":"", +// "result":true, +// } +// +//export SetFFmpeg +func SetFFmpeg(fullFileName *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + f := C.GoString(fullFileName) + + _, err := os.Stat(f) + if os.IsNotExist(err) { + return WithJSON(false, err) + } + sdk.CmdFFmpeg = C.GoString(fullFileName) + return WithJSON(true, nil) +} + +// GetFileContentType get content/MIME type of file +// ## Inputs: +// - fullFileName +// return +// { +// "error":"", +// "result":true, +// } +// +//export GetFileContentType +func GetFileContentType(file *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + f, err := os.Open(C.GoString(file)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + defer f.Close() + + mime, err := zboxutil.GetFileContentType(f) + if err != nil { + return WithJSON("", err) + } + + return WithJSON(mime, nil) +} diff --git a/winsdk/status.go b/winsdk/status.go index c1d0caa69..265f02ee3 100644 --- a/winsdk/status.go +++ b/winsdk/status.go @@ -1,13 +1,15 @@ package main import ( - "github.com/0chain/gosdk/zboxcore/sdk" + "sync" + lru "github.com/hashicorp/golang-lru/v2" ) var ( statusUpload, _ = lru.New[string, *Status](1000) statusDownload, _ = lru.New[string, *Status](1000) + transcodeFiles, _ = lru.New[string, string](1000) ) type Status struct { @@ -17,6 +19,7 @@ type Status struct { Error string Completed bool LookupHash string + wg *sync.WaitGroup } type StatusCallback struct { @@ -24,11 +27,13 @@ type StatusCallback struct { items *lru.Cache[string, *Status] } -func NewStatusBar(items *lru.Cache[string, *Status], key string) sdk.StatusCallback { - return &StatusCallback{ +func NewStatusBar(items *lru.Cache[string, *Status], key string) *StatusCallback { + sc := &StatusCallback{ key: key, items: items, } + + return sc } func (c *StatusCallback) getStatus(lookupHash string) *Status { @@ -69,6 +74,11 @@ func (c *StatusCallback) InProgress(allocationID, remotePath string, op int, com s.LookupHash = lookupHash if completedBytes >= s.TotalBytes { s.Completed = true + if s.wg != nil { + s.wg.Done() + s.wg = nil + } + } } @@ -78,6 +88,10 @@ func (c *StatusCallback) Error(allocationID string, remotePath string, op int, e s := c.getStatus(lookupHash) s.Error = err.Error() s.LookupHash = lookupHash + if s.wg != nil { + s.wg.Done() + s.wg = nil + } } func (c *StatusCallback) Completed(allocationID, remotePath string, filename string, mimetype string, size int, op int) { @@ -87,6 +101,10 @@ func (c *StatusCallback) Completed(allocationID, remotePath string, filename str s.Completed = true s.LookupHash = lookupHash s.CompletedBytes = s.TotalBytes + if s.wg != nil { + s.wg.Done() + s.wg = nil + } } func (c *StatusCallback) CommitMetaCompleted(request, response string, err error) { diff --git a/winsdk/storage.go b/winsdk/storage.go index 493f3d02b..fc5bcd5f2 100644 --- a/winsdk/storage.go +++ b/winsdk/storage.go @@ -12,7 +12,10 @@ import ( "errors" "fmt" "os" + "time" + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zboxcore/marker" "github.com/0chain/gosdk/zboxcore/sdk" ) @@ -26,6 +29,12 @@ import ( // //export GetFileStats func GetFileStats(allocationID, remotePath *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) path := C.GoString(remotePath) @@ -57,20 +66,6 @@ func GetFileStats(allocationID, remotePath *C.char) *C.char { return WithJSON(result, nil) } -// GetAllocation get allocation info -// -// return -// { -// "error":"", -// "result":"{}", -// } -// -//export GetAllocation -func GetAllocation(allocationID *C.char) *C.char { - allocID := C.GoString(allocationID) - return WithJSON(getAllocation(allocID)) -} - // Delete delete path // // return @@ -81,6 +76,12 @@ func GetAllocation(allocationID *C.char) *C.char { // //export Delete func Delete(allocationID, path *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -120,6 +121,11 @@ type MultiOperationOption struct { // //export MultiOperation func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocationID := C.GoString(_allocationID) jsonMultiOperationOptions := C.GoString(_jsonMultiOperationOptions) if allocationID == "" { @@ -156,6 +162,12 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { } // GetFileMeta get metadata by path +// ## Inputs +// - allocationID +// - path +// - authTicket +// +// ## Outputs // // return // { @@ -164,19 +176,43 @@ func MultiOperation(_allocationID, _jsonMultiOperationOptions *C.char) *C.char { // } // //export GetFileMeta -func GetFileMeta(allocationID, path *C.char) *C.char { +func GetFileMeta(allocationID, path, authTicket *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) - alloc, err := getAllocation(allocID) + t := C.GoString(authTicket) + + var ticket *marker.AuthTicket + + var alloc *sdk.Allocation + var err error + isShared := len(t) > 0 + if isShared { + alloc, ticket, err = getAllocationWith(t) + } else { + alloc, err = getAllocation(allocID) + } + if err != nil { + log.Error("win: ", err) return WithJSON(nil, err) } s := C.GoString(path) - f, err := alloc.GetFileMeta(s) + var f *sdk.ConsolidatedFileMeta + if isShared { + f, err = alloc.GetFileMetaFromAuthTicket(t, ticket.FilePathHash) + } else { + f, err = alloc.GetFileMeta(s) + } if err != nil { + log.Error("win: ", err, " authTicket=", t, " path=", s) return WithJSON(nil, err) } @@ -195,6 +231,11 @@ func GetFileMeta(allocationID, path *C.char) *C.char { // //export BulkUpload func BulkUpload(allocationID, files *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) workdir, _ := os.UserHomeDir() jsFiles := C.GoString(files) @@ -224,7 +265,17 @@ func BulkUpload(allocationID, files *C.char) *C.char { isUpdates[idx] = option.IsUpdate isWebstreaming[idx] = option.IsWebstreaming encrypts[idx] = option.Encrypt - statusUpload.Add(getLookupHash(allocID, option.RemotePath+option.Name), &Status{}) + if option.IsWebstreaming { + originalLookupHash := getLookupHash(allocID, option.RemotePath+option.Name) + _, transcodeRemotePath := sdk.GetTranscodeFile(option.RemotePath + option.Name) + transcodeLookupHash := getLookupHash(allocID, transcodeRemotePath) + transcodeFiles.Add(originalLookupHash, transcodeLookupHash) + statusUpload.Add(transcodeLookupHash, &Status{}) + + } else { + statusUpload.Add(getLookupHash(allocID, option.RemotePath+option.Name), &Status{}) + } + } a, err := getAllocation(allocID) @@ -252,8 +303,20 @@ func BulkUpload(allocationID, files *C.char) *C.char { // //export GetUploadStatus func GetUploadStatus(lookupHash *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + h := C.GoString(lookupHash) + + h2, ok := transcodeFiles.Get(h) - s, ok := statusUpload.Get(C.GoString(lookupHash)) + if ok { + h = h2 + } + + s, ok := statusUpload.Get(h) if !ok { s = &Status{} @@ -295,6 +358,11 @@ func SetNumBlockDownloads(num int) { // //export DownloadFile func DownloadFile(allocationID, localPath, remotePath *C.char, verifyDownload, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -329,6 +397,11 @@ func DownloadFile(allocationID, localPath, remotePath *C.char, verifyDownload, i // //export DownloadThumbnail func DownloadThumbnail(allocationID, localPath, remotePath *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -365,8 +438,13 @@ func DownloadThumbnail(allocationID, localPath, remotePath *C.char, verifyDownlo // //export DownloadSharedFile func DownloadSharedFile(localPath, authTicket *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { return WithJSON(info, err) } @@ -405,9 +483,15 @@ func DownloadSharedFile(localPath, authTicket *C.char, verifyDownload bool, isFi // //export DownloadSharedThumbnail func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { + log.Error("win: ", err, " authTicket=", at) return WithJSON(info, err) } info.AllocationID = t.AllocationID @@ -415,6 +499,7 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, alloc, err := getAllocation(t.AllocationID) if err != nil { + log.Error("win: ", err, " authTicket=", at) return WithJSON(info, err) } @@ -422,6 +507,7 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, err = alloc.DownloadThumbnailFromAuthTicket(C.GoString(localPath), at, t.FilePathHash, t.FileName, verifyDownload, statusBar, isFinal) if err != nil { + log.Error("win: ", err, " authTicket=", at, " lookuphash=", t.FilePathHash) return WithJSON(info, err) } @@ -450,6 +536,12 @@ func DownloadSharedThumbnail(localPath, authTicket *C.char, verifyDownload bool, func DownloadFileBlocks(allocationID, localPath, remotePath *C.char, startBlock int64, endBlock int64, numBlocks int, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + allocID := C.GoString(allocationID) alloc, err := getAllocation(allocID) @@ -472,7 +564,6 @@ func DownloadFileBlocks(allocationID, // DownloadSharedFileBlocks - downalod shared file blocks // ## Inputs -// - allocationID // - localPath // - remotePath // - startBlock @@ -489,12 +580,16 @@ func DownloadFileBlocks(allocationID, // } // //export DownloadSharedFileBlocks -func DownloadSharedFileBlocks(allocationID, - localPath, authTicket *C.char, startBlock int64, endBlock int64, +func DownloadSharedFileBlocks(localPath, authTicket *C.char, startBlock int64, endBlock int64, numBlocks int, verifyDownload bool, isFinal bool) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() info := &SharedInfo{} - t, at, err := getAuthTicket(authTicket) + t, at, err := decodeAuthTicket(authTicket) if err != nil { return WithJSON(info, err) } @@ -529,7 +624,11 @@ func DownloadSharedFileBlocks(allocationID, // //export GetDownloadStatus func GetDownloadStatus(key *C.char, isThumbnail bool) *C.char { - + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() k := C.GoString(key) if isThumbnail { k += ":thumbnail" @@ -543,3 +642,101 @@ func GetDownloadStatus(key *C.char, isThumbnail bool) *C.char { return WithJSON(s, nil) } + +// CreateAuthTicket - create AuthTicket for sharing +// ## Inputs +// - allocationID +// - remotePath +// - refereeClientID +// - refereePublicEncryptionKey +// - availableAfter +// - expirationSeconds +// +// ## Outputs +// +// { +// "error":"", +// "result":"{}", +// } +// +//export CreateAuthTicket +func CreateAuthTicket(allocationID, remotePath, refereeClientID, refereePublicEncryptionKey, availableAfter *C.char, expirationSeconds int64) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + alloc, err := getAllocation(C.GoString(allocationID)) + + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + rPath := C.GoString(remotePath) + + fileMeta, err := alloc.GetFileMeta(rPath) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + af := time.Now() + availableAfterString := C.GoString(availableAfter) + + if len(availableAfterString) > 0 { + aa, err := common.ParseTime(af, availableAfterString) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + af = *aa + } + + at, err := alloc.GetAuthTicket(rPath, fileMeta.Name, fileMeta.Type, C.GoString(refereeClientID), C.GoString(refereePublicEncryptionKey), expirationSeconds, &af) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(at, nil) + +} + +// DeleteAuthTicket - delete AuthTicket +// ## Inputs +// - allocationID +// - remotePath +// - refereeClientID +// +// ## Outputs +// +// { +// "error":"", +// "result":"true", +// } +// +//export DeleteAuthTicket +func DeleteAuthTicket(allocationID, remotePath, refereeClientID *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + alloc, err := getAllocation(C.GoString(allocationID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + rPath := C.GoString(remotePath) + + err = alloc.RevokeShare(rPath, C.GoString(refereeClientID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) + +} diff --git a/winsdk/stream.go b/winsdk/stream.go new file mode 100644 index 000000000..bad529daf --- /dev/null +++ b/winsdk/stream.go @@ -0,0 +1,254 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "fmt" + "math" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + "github.com/0chain/gosdk/zboxcore/sdk" + lru "github.com/hashicorp/golang-lru/v2" +) + +var ( + numBlocks int = 100 + sizePerRequest int64 = sdk.CHUNK_SIZE * int64(numBlocks) // 6400K 100 blocks + server *httptest.Server + streamAllocationID string + cachedDownloadedBlocks, _ = lru.New[string, []byte](1000) +) + +// StartStreamServer - start local media stream server +// ## Inputs +// - allocationID +// +// ## Outputs +// +// { +// "error":"", +// "result":"http://127.0.0.1:4313/", +// } +// +//export StartStreamServer +func StartStreamServer(allocationID *C.char) *C.char { + allocID := C.GoString(allocationID) + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + streamingMedia(w, r) + }) + + if server != nil { + server.Close() + } + + server = httptest.NewServer(handler) + streamAllocationID = allocID + log.Info("win: ", server.URL) + return WithJSON(server.URL, nil) +} + +func streamingMedia(w http.ResponseWriter, req *http.Request) { + + remotePath := req.URL.Path + log.Info("win: start streaming media: ", streamAllocationID, remotePath) + + f, err := getFileMeta(streamAllocationID, remotePath) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + w.Header().Set("Content-Type", f.MimeType) + + rangeHeader := req.Header.Get("Range") + + log.Info("win: range: ", rangeHeader, " mimetype: ", f.MimeType, " numBlocks:", f.NumBlocks, " ActualNumBlocks:", f.ActualNumBlocks, " ActualFileSize:", f.ActualFileSize) + // we can simply hint Chrome to send serial range requests for media file by + // + // if rangeHeader == "" { + // w.Header().Set("Accept-Ranges", "bytes") + // w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + // w.WriteHeader(200) + // fmt.Printf("hint browser to send range requests, total size: %d\n", size) + // return + // } + // + // but this not worked for Safari and Firefox + if rangeHeader == "" { + ra := httpRange{ + start: 0, + length: sizePerRequest, + total: f.ActualFileSize, + } + w.Header().Set("Accept-Ranges", "bytes") + + w.Header().Set("Content-Range", ra.Header()) + + w.WriteHeader(http.StatusPartialContent) + + if req.Method != "HEAD" { + buf, err := downloadBlocks(remotePath, f, ra) + if err != nil { + http.Error(w, err.Error(), 500) + } + + written, err := w.Write(buf) + + if err != nil { + http.Error(w, err.Error(), 500) + } + + w.Header().Set("Content-Length", strconv.Itoa(written)) + + for k, v := range w.Header() { + log.Info("win: response ", k, " = ", v[0]) + } + + } else { + w.Header().Set("Content-Length", "0") + } + return + } + + ranges, err := parseRange(rangeHeader, f.ActualFileSize) + if err != nil { + http.Error(w, err.Error(), 400) + return + } + + // multi-part requests are not supported + if len(ranges) > 1 { + http.Error(w, "unsupported multi-part", http.StatusRequestedRangeNotSatisfiable) + return + } + + ra := ranges[0] + + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("Content-Range", ra.Header()) + + w.WriteHeader(http.StatusPartialContent) + + if req.Method != "HEAD" { + + buf, err := downloadBlocks(remotePath, f, ra) + + if err != nil { + http.Error(w, err.Error(), 500) + } + + written, err := w.Write(buf) + if err != nil { + http.Error(w, err.Error(), 500) + } + w.Header().Set("Content-Length", strconv.Itoa(written)) + + for k, v := range w.Header() { + log.Info("win: response ", k, " = ", v[0]) + } + } else { + w.Header().Set("Content-Length", "0") + } +} + +func downloadBlocks(remotePath string, f *sdk.ConsolidatedFileMeta, ra httpRange) ([]byte, error) { + defer func() { + if r := recover(); r != nil { + log.Error("win: ", r) + } + }() + alloc, err := getAllocation(streamAllocationID) + + if err != nil { + return nil, err + } + var startBlock int64 + + if ra.start == 0 { + startBlock = 1 + } else { + startBlock = int64(math.Floor(float64(ra.start)/float64(sdk.CHUNK_SIZE)/float64(alloc.DataShards))) + 1 + } + + if startBlock > f.NumBlocks { + startBlock = f.NumBlocks + } + + blocks := int(math.Ceil(float64(ra.length) / float64(sdk.CHUNK_SIZE) / float64(alloc.DataShards))) + + endBlock := startBlock + int64(blocks) + + if endBlock > f.NumBlocks { + endBlock = f.NumBlocks + } + + if startBlock == endBlock { + endBlock = 0 + } + + offset := 0 + blockStart := (startBlock - 1) * sdk.CHUNK_SIZE * int64(alloc.DataShards) + if ra.start > blockStart { + offset = int(ra.start) - int(blockStart) + } + + lookupHash := getLookupHash(streamAllocationID, remotePath) + key := lookupHash + fmt.Sprintf(":%v-%v", startBlock, endBlock) + log.Info("win: start download blocks ", startBlock, " - ", endBlock, "/", f.NumBlocks, "(", f.ActualNumBlocks, ") for ", remotePath) + buf, ok := cachedDownloadedBlocks.Get(key) + if ok { + return buf, nil + } + + mf := filepath.Join(os.TempDir(), strings.ReplaceAll(remotePath, "/", "_")+fmt.Sprintf("_%v_%v", startBlock, endBlock)) + defer os.Remove(mf) + + // _, err = os.Stat(mf) + + // if os.IsNotExist(err) { + statusBar := NewStatusBar(statusDownload, key) + status := statusBar.getStatus(key) + status.wg = &sync.WaitGroup{} + status.wg.Add(1) + log.Info("win: download blocks to ", mf) + err = alloc.DownloadFileByBlock(mf, remotePath, startBlock, endBlock, numBlocks, false, statusBar, true) + //err = alloc.DownloadFile(mf, remotePath, true, statusBar, true) + if err != nil { + return nil, err + } + + log.Info("win: waiting for download to done") + status.wg.Wait() + // } + + buf, err = os.ReadFile(mf) + if err != nil { + return nil, err + } + + log.Info("win: downloaded blocks ", len(buf), " start:", ra.start, " blockStart:", blockStart, " offset:", offset, " len:", ra.length) + if len(buf) > 0 { + if len(buf) > int(ra.length) { + b := buf[offset : offset+int(ra.length)] + cachedDownloadedBlocks.Add(key, b) + return b, nil + } + cachedDownloadedBlocks.Add(key, buf) + return buf[offset:], nil + } + + // os.Remove(mf) + return nil, nil +} diff --git a/winsdk/stream_models.go b/winsdk/stream_models.go new file mode 100644 index 000000000..96f0a7874 --- /dev/null +++ b/winsdk/stream_models.go @@ -0,0 +1,101 @@ +package main + +import ( + "errors" + "fmt" + "net/textproto" + "strconv" + "strings" +) + +var errNoOverlap = errors.New("invalid range: failed to overlap") + +type httpRange struct { + start, length, total int64 +} + +func (r httpRange) Header() string { + return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, r.total) +} + +// parseRange parses a Range header string as per RFC 7233. +// errNoOverlap is returned if none of the ranges overlap. +// +// Examples of valid byte ranges (assuming a resource of length 10240): +// bytes=0-499, the first 500 bytes +// bytes=1000-1999, 1000 bytes start from offset 1000 +// bytes=-500, the final 500 bytes (byte offsets 9739-10239, inclusive) +// bytes=0-0,-1, the first and last bytes only +// bytes=0-, bytes=0-10250, be interpreted as bytes=0-10239 +func parseRange(s string, total int64) ([]httpRange, error) { + if s == "" { + return nil, nil // header not present + } + const b = "bytes=" + if !strings.HasPrefix(s, b) { + return nil, errors.New("invalid range") + } + var ranges []httpRange + noOverlap := false + for _, ra := range strings.Split(s[len(b):], ",") { + ra = textproto.TrimString(ra) + if ra == "" { + continue + } + start, end, ok := strings.Cut(ra, "-") + if !ok { + return nil, errors.New("invalid range") + } + start, end = textproto.TrimString(start), textproto.TrimString(end) + var r httpRange + if start == "" { + if end == "" || end[0] == '-' { + return nil, errors.New("invalid range") + } + i, err := strconv.ParseInt(end, 10, 64) + if i < 0 || err != nil { + return nil, errors.New("invalid range") + } + if i > total { + i = total + } + r.start = total - i + r.length = total - r.start + } else { + i, err := strconv.ParseInt(start, 10, 64) + if err != nil || i < 0 { + return nil, errors.New("invalid range") + } + if i >= total { + // If the range begins after the size of the content, + // then it does not overlap. + noOverlap = true + i = total - 1 + //continue, since server may attempt to return a largeEnoughLen, errNoOverlap never happen + } + r.start = i + if end == "" { + r.length = sizePerRequest + if r.length > total-r.start && !noOverlap { + r.length = total - r.start + } + } else { + i, err := strconv.ParseInt(end, 10, 64) + if err != nil || r.start > i { + return nil, errors.New("invalid range") + } + if i >= total { + i = total - 1 + } + r.length = i - r.start + 1 + } + } + r.total = total + ranges = append(ranges, r) + } + if noOverlap && len(ranges) == 0 { + // The specified ranges did not overlap with the content. + return nil, errNoOverlap + } + return ranges, nil +} diff --git a/winsdk/wallet.go b/winsdk/wallet.go new file mode 100644 index 000000000..2c5eaeec6 --- /dev/null +++ b/winsdk/wallet.go @@ -0,0 +1,96 @@ +package main + +/* +#include +*/ +import ( + "C" +) + +import ( + "os" + "path/filepath" + + "github.com/0chain/gosdk/zcncore" +) + +// CreateWallet - create a new wallet, and save it to ~/.zcn/wallet.json +// ## Outputs +// +// { +// "error":"", +// "result":\"{}\"", +// } +// +//export CreateWallet +func CreateWallet() *C.char { + w, err := zcncore.CreateWalletOffline() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + d, err := getZcnWorkDir() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + if err = os.WriteFile(filepath.Join(d, "wallet.json"), []byte(w), 0644); err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(w, nil) +} + +// RecoverWallet - recover the wallet, and save it to ~/.zcn/wallet.json +// ## Outputs +// +// { +// "error":"", +// "result":\"{}\"", +// } +// +//export RecoverWallet +func RecoverWallet(mnemonic *C.char) *C.char { + w, err := zcncore.RecoverOfflineWallet(C.GoString(mnemonic)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + d, err := getZcnWorkDir() + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + if err = os.WriteFile(filepath.Join(d, "wallet.json"), []byte(w), 0644); err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(w, nil) +} + +// GetWalletBalance - get wallet balance +// ## Inputs +// - clientID +// ## Outputs +// +// { +// "error":"", +// "result":\"0.00\"", +// } +// +//export GetWalletBalance +func GetWalletBalance(clientID *C.char) *C.char { + b, err := zcncore.GetWalletBalance(C.GoString(clientID)) + if err != nil { + log.Error("win: ", err) + return WithJSON(0, err) + } + + return WithJSON(b.ToToken()) +} diff --git a/winsdk/zboxapi.go b/winsdk/zboxapi.go index e7ac10b03..0a8c5a628 100644 --- a/winsdk/zboxapi.go +++ b/winsdk/zboxapi.go @@ -10,6 +10,7 @@ import ( import ( "context" + "encoding/json" "errors" "github.com/0chain/gosdk/core/logger" @@ -28,8 +29,15 @@ var ( // //export InitZBox func InitZBox(zboxHost, zboxAppType *C.char) { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + if zboxApiClient == nil { + zboxApiClient = zboxapi.NewClient() + } - zboxApiClient = zboxapi.NewClient() zboxApiClient.SetRequest(C.GoString(zboxHost), C.GoString(zboxAppType)) c := client.GetClient() @@ -50,6 +58,11 @@ func InitZBox(zboxHost, zboxAppType *C.char) { // //export SetZBoxWallet func SetZBoxWallet(clientID, clientPrivateKey, clientPublicKey *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(false, ErrZboxApiNotInitialized) } @@ -75,6 +88,11 @@ func SetZBoxWallet(clientID, clientPrivateKey, clientPublicKey *C.char) *C.char // //export GetCsrfToken func GetCsrfToken() *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(0, ErrZboxApiNotInitialized) } @@ -92,6 +110,11 @@ func GetCsrfToken() *C.char { // //export CreateJwtSession func CreateJwtSession(phoneNumber *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON(0, ErrZboxApiNotInitialized) } @@ -108,6 +131,11 @@ func CreateJwtSession(phoneNumber *C.char) *C.char { // //export CreateJwtToken func CreateJwtToken(phoneNumber *C.char, jwtSessionID int64, otp *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON("", ErrZboxApiNotInitialized) } @@ -124,8 +152,191 @@ func CreateJwtToken(phoneNumber *C.char, jwtSessionID int64, otp *C.char) *C.cha // //export RefreshJwtToken func RefreshJwtToken(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() if zboxApiClient == nil { return WithJSON("", ErrZboxApiNotInitialized) } return WithJSON(zboxApiClient.RefreshJwtToken(context.TODO(), C.GoString(phoneNumber), C.GoString(token))) } + +// GetFreeMarker create a free storage marker +// ## Inputs +// - phoneNumber +// - token +// return +// { +// "error":"", +// "result":"{}", +// } +// +//export GetFreeMarker +func GetFreeMarker(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + marker, err := zboxApiClient.GetFreeStorage(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON("", err) + } + + return WithJSON(marker, nil) +} + +// CreateSharedInfo create a shareInfo on 0box db +// ## Inputs +// - phoneNumber +// - token +// - sharedInfo +// +// ## Output +// +// { +// "error":"", +// "result":true, +// } +// +//export CreateSharedInfo +func CreateSharedInfo(phoneNumber, token, sharedInfo *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + js := C.GoString(sharedInfo) + + s := zboxapi.SharedInfo{} + err := json.Unmarshal([]byte(js), &s) + if err != nil { + log.Error("win: ", js, err) + return WithJSON(false, err) + } + + err = zboxApiClient.CreateSharedInfo(context.TODO(), C.GoString(phoneNumber), C.GoString(token), s) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) +} + +// DeleteSharedInfo create a shareInfo on 0box db +// ## Inputs +// - phoneNumber +// - token +// - authTicket +// - lookupHash +// +// ## Output +// +// { +// "error":"", +// "result":true, +// } +// +//export DeleteSharedInfo +func DeleteSharedInfo(phoneNumber, token, authTicket, lookupHash *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + err := zboxApiClient.DeleteSharedInfo(context.TODO(), C.GoString(phoneNumber), C.GoString(token), C.GoString(authTicket), C.GoString(lookupHash)) + if err != nil { + log.Error("win: ", err) + return WithJSON(false, err) + } + + return WithJSON(true, nil) +} + +// GetSharedByMe get file list that is shared by me privatly +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedByMe +func GetSharedByMe(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + list, err := zboxApiClient.GetSharedByMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} + +// GetSharedByPublic get file list that is clicked by me +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedByPublic +func GetSharedByPublic(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + list, err := zboxApiClient.GetSharedByPublic(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} + +// GetSharedToMe get file list that is shared to me +// ## Inputs +// - phoneNumber +// - token +// +// ## Output +// +// { +// "error":"", +// "result":[{},{}], +// } +// +//export GetSharedToMe +func GetSharedToMe(phoneNumber, token *C.char) *C.char { + defer func() { + if r := recover(); r != nil { + log.Error("win: crash ", r) + } + }() + list, err := zboxApiClient.GetSharedToMe(context.TODO(), C.GoString(phoneNumber), C.GoString(token)) + if err != nil { + log.Error("win: ", err) + return WithJSON(nil, err) + } + + return WithJSON(list, nil) +} diff --git a/zboxapi/response.go b/zboxapi/response.go index 9daa193fb..66a2662c4 100644 --- a/zboxapi/response.go +++ b/zboxapi/response.go @@ -1,6 +1,7 @@ package zboxapi import ( + "encoding/base64" "encoding/json" "errors" ) @@ -20,3 +21,86 @@ type CsrfTokenResponse struct { type JwtTokenResponse struct { Token string `json:"jwt_token"` } + +type FreeStorageResponse struct { + Data string `json:"marker"` + FundingID int `json:"funding_id"` +} + +type MarkerData struct { + Marker string `json:"marker"` + RecipientPublicKey string `json:"recipient_public_key"` +} + +func (fs *FreeStorageResponse) ToMarker() (*FreeMarker, error) { + + buf, err := base64.StdEncoding.DecodeString(fs.Data) + + if err != nil { + return nil, err + } + + data := &MarkerData{} + err = json.Unmarshal(buf, &data) + if err != nil { + return nil, err + } + + buf, err = base64.StdEncoding.DecodeString(data.Marker) + if err != nil { + return nil, err + } + + fm := &FreeMarker{} + + err = json.Unmarshal(buf, fm) + if err != nil { + return nil, err + } + + return fm, nil +} + +type FreeMarker struct { + Assigner string `json:"assigner"` + Recipient string `json:"recipient"` + FreeTokens float64 `json:"free_tokens"` + Nonce int64 `json:"nonce"` + Signature string `json:"signature"` +} + +type JsonResult[T any] struct { + Message string `json:"message"` + Error string `json:"error"` + Data []T `json:"data"` +} + +type SharedInfo struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + Link string `json:"link"` +} + +type SharedInfoSent struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + Receiver string `json:"receiver_client_id"` + Link string `json:"link"` + ReceiverName string `json:"receiver_name"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type SharedInfoReceived struct { + AuthTicket string `json:"auth_ticket"` + Message string `json:"message"` + ShareInfoType string `json:"share_info_type"` + ClientID string `json:"client_id"` + Receiver string `json:"receiver_client_id"` + LookupHash string `json:"lookup_hash"` + SenderName string `json:"sender_name"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} diff --git a/zboxapi/sdk.go b/zboxapi/sdk.go index 14a6b3edc..dee51560a 100644 --- a/zboxapi/sdk.go +++ b/zboxapi/sdk.go @@ -1,6 +1,7 @@ package zboxapi import ( + "bytes" "context" "encoding/json" "errors" @@ -11,10 +12,39 @@ import ( thrown "github.com/0chain/errors" "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/core/resty" "github.com/0chain/gosdk/core/sys" + "github.com/0chain/gosdk/core/zcncrypto" ) +var log logger.Logger + +func GetLogger() *logger.Logger { + return &log +} + +func signHash(hash string, signatureScheme string, keys []sys.KeyPair) (string, error) { + retSignature := "" + for _, kv := range keys { + ss := zcncrypto.NewSignatureScheme(signatureScheme) + err := ss.SetPrivateKey(kv.PrivateKey) + if err != nil { + return "", err + } + + if len(retSignature) == 0 { + retSignature, err = ss.Sign(hash) + } else { + retSignature, err = ss.Add(retSignature, hash) + } + if err != nil { + return "", err + } + } + return retSignature, nil +} + type Client struct { baseUrl string appType string @@ -41,7 +71,9 @@ func (c *Client) SetWallet(clientID, clientPrivateKey, clientPublicKey string) { } func (c *Client) parseResponse(resp *http.Response, respBody []byte, result interface{}) error { - if resp.StatusCode == http.StatusOK { + + log.Info("zboxapi: ", resp.StatusCode, " ", string(respBody)) + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { if err := json.Unmarshal(respBody, result); err != nil { return thrown.Throw(ErrInvalidJsonResponse, string(respBody)) } @@ -90,7 +122,7 @@ func (c *Client) createResty(ctx context.Context, csrfToken, phoneNumber string, if c.clientPrivateKey != "" { data := fmt.Sprintf("%v:%v:%v", c.clientID, phoneNumber, c.clientPublicKey) hash := encryption.Hash(data) - sign, err := sys.Sign(hash, "bls0chain", []sys.KeyPair{{ + sign, err := signHash(hash, "bls0chain", []sys.KeyPair{{ PrivateKey: c.clientPrivateKey, }}) if err != nil { @@ -209,3 +241,185 @@ func (c *Client) RefreshJwtToken(ctx context.Context, phoneNumber string, token return result.Token, nil } + +func (c *Client) GetFreeStorage(ctx context.Context, phoneNumber, token string) (*FreeMarker, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + result := &FreeStorageResponse{} + r.DoGet(ctx, c.baseUrl+"/v2/freestorage"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + return c.parseResponse(resp, respBody, result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.ToMarker() + +} + +func (c *Client) CreateSharedInfo(ctx context.Context, phoneNumber, token string, s SharedInfo) error { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return err + } + headers := map[string]string{ + "X-App-ID-Token": token, + "Content-Type": "application/json", + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return err + } + + buf, err := json.Marshal(s) + if err != nil { + return err + } + + result := &JsonResult[string]{} + r.DoPost(ctx, bytes.NewReader(buf), c.baseUrl+"/v2/shareinfo"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return errs[0] + } + + return nil +} + +func (c *Client) DeleteSharedInfo(ctx context.Context, phoneNumber, token, authTicket string, lookupHash string) error { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return err + } + + result := &JsonResult[string]{} + r.DoDelete(ctx, c.baseUrl+"/v2/shareinfo?auth_ticket="+authTicket+"&lookup_hash="+lookupHash). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return errs[0] + } + + return nil +} + +func (c *Client) GetSharedByPublic(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { + return c.getShared(ctx, phoneNumber, token, false) +} + +func (c *Client) GetSharedByMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoSent, error) { + return c.getShared(ctx, phoneNumber, token, true) +} + +func (c *Client) getShared(ctx context.Context, phoneNumber, token string, isPrivate bool) ([]SharedInfoSent, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + shareInfoType := "public" + if isPrivate { + shareInfoType = "private" + } + + result := &JsonResult[SharedInfoSent]{} + r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/shared?share_info_type="+shareInfoType). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.Data, nil + +} + +func (c *Client) GetSharedToMe(ctx context.Context, phoneNumber, token string) ([]SharedInfoReceived, error) { + csrfToken, err := c.GetCsrfToken(ctx) + if err != nil { + return nil, err + } + headers := map[string]string{ + "X-App-ID-Token": token, + } + + r, err := c.createResty(ctx, csrfToken, phoneNumber, headers) + + if err != nil { + return nil, err + } + + result := &JsonResult[SharedInfoReceived]{} + r.DoGet(ctx, c.baseUrl+"/v2/shareinfo/received?share_info_type=private"). + Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error { + if err != nil { + return err + } + + return c.parseResponse(resp, respBody, &result) + }) + + if errs := r.Wait(); len(errs) > 0 { + return nil, errs[0] + } + + return result.Data, nil + +} diff --git a/zboxapi/sdk_test.go b/zboxapi/sdk_test.go index 39c70d376..2b54496ca 100644 --- a/zboxapi/sdk_test.go +++ b/zboxapi/sdk_test.go @@ -2,18 +2,20 @@ package zboxapi import ( "context" + "encoding/base64" + "encoding/json" "testing" "github.com/stretchr/testify/require" ) var ( - BaseURL = "https://0box.demo.zus.network" + BaseURL = "https://0box.dev.zus.network" AppType = "vult" - ClientID = "8f6ce6457fc04cfb4eb67b5ce3162fe2b85f66ef81db9d1a9eaa4ffe1d2359e0" - ClientPublicKey = "c8c88854822a1039c5a74bdb8c025081a64b17f52edd463fbecb9d4a42d15608f93b5434e926d67a828b88e63293b6aedbaf0042c7020d0a96d2e2f17d3779a4" - ClientPrivateKey = "72f480d4b1e7fb76e04327b7c2348a99a64f0ff2c5ebc3334a002aa2e66e8506" - PhoneNumber = "+917777777777" + ClientID = "70e1318a9709786cf975f15ca941bee73d0f422305ecd78b0f358870ec17f41d" + ClientPublicKey = "4ec4b4dfb8c9ceb8fb6e84ef46e503c3445a0c6d770986a019cdbef4bc47b70dfadd5441f708f0df47df14e5cd6a0aa94ec31ca66e337692d9a92599d9456a81" + ClientPrivateKey = "982801f352e886eaaf61196d83373b4cc09e9a598ffe1f49bf5adf905174cb0c" + PhoneNumber = "+16026666666" ) func TestGetCsrfToken(t *testing.T) { @@ -49,5 +51,156 @@ func TestJwtToken(t *testing.T) { require.Nil(t, err) require.NotEmpty(t, refreshedToken) require.NotEqual(t, token, refreshedToken) +} + +func TestGetFreeStorage(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + marker, err := c.GetFreeStorage(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.NotEmpty(t, marker.Assigner) + require.Equal(t, ClientID, marker.Recipient) +} + +var testShareInfo = SharedInfo{ + AuthTicket: "eyJjbGllbnRfaWQiOiIiLCJvd25lcl9pZCI6IjcwZTEzMThhOTcwOTc4NmNmOTc1ZjE1Y2E5NDFiZWU3M2QwZjQyMjMwNWVjZDc4YjBmMzU4ODcwZWMxN2Y0MWQiLCJhbGxvY2F0aW9uX2lkIjoiZjQ0OTUxZDkwODRiMTExZGMxNDliMmNkN2E5Nzg5YmU5MDVlYjFiMWRhNzdjMjYxNDZiMWNkY2IxNzE3NTI0NiIsImZpbGVfcGF0aF9oYXNoIjoiM2RlOWQ1ZTMzYWJlNWI3ZjhhNzM2OGY0ZmE4N2QwMmY1MjI1YzIzMzhmM2Q3YWI0MGQxNDczM2NiYmI4ZTc1YiIsImFjdHVhbF9maWxlX2hhc2giOiJkYTJjMzIxZmFiN2RkNmYyZDVlZTAzZWQwNDk2OGJlMTA0YjdjNmY2MTYyYTVmY2ZjNDFmZTEyZTY3ZDBkNjUzIiwiZmlsZV9uYW1lIjoiUVHlm77niYcyMDIxMDkzMDEyMDM1Ny5qcGciLCJyZWZlcmVuY2VfdHlwZSI6ImYiLCJleHBpcmF0aW9uIjowLCJ0aW1lc3RhbXAiOjE2OTgyODY5MjcsImVuY3J5cHRlZCI6ZmFsc2UsInNpZ25hdHVyZSI6ImRkMzg4NzI2YTcwYzBjN2Y5NDZkMTQwMTRjMjhhZTg1MjM4ZTliNmJkMmExMzRjMWUxOGE3MTE5NDViYzg4MGYifQ==", + Message: "shared by unit test", + ShareInfoType: "public", + Link: "https://0box.page.link/cnfFExcvKKRaFzyE9", +} + +func TestCreateSharedInfo(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + err = c.CreateSharedInfo(context.TODO(), PhoneNumber, "jwt-"+token, testShareInfo) + + require.NoError(t, err) + +} + +func TestGetSharedToMe(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedToMe(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + // require.NotEmpty(t, marker.Assigner) + // require.Equal(t, ClientID, marker.Recipient) +} + +func TestGetSharedByMe(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedByMe(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + +} + +func TestGetSharedByPublic(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + list, err := c.GetSharedByPublic(context.TODO(), PhoneNumber, "jwt-"+token) + + require.NoError(t, err) + require.Greater(t, len(list), 0) + +} + +func TestDeleteSharedInfo(t *testing.T) { + t.Skip("Only for local debugging") + + c := NewClient() + c.SetRequest(BaseURL, AppType) + c.SetWallet(ClientID, ClientPrivateKey, ClientPublicKey) + sessionID, err := c.CreateJwtSession(context.TODO(), PhoneNumber) + + require.Nil(t, err) + require.GreaterOrEqual(t, sessionID, int64(0)) + + token, err := c.CreateJwtToken(context.TODO(), PhoneNumber, sessionID, "000000") //any otp works on test phone number + + require.Nil(t, err) + require.NotEmpty(t, token) + + buf, _ := base64.StdEncoding.DecodeString(testShareInfo.AuthTicket) + + items := make(map[string]any) + + json.Unmarshal(buf, &items) + + lookupHash := items["file_path_hash"].(string) + + err = c.DeleteSharedInfo(context.TODO(), PhoneNumber, "jwt-"+token, testShareInfo.AuthTicket, lookupHash) + + require.NoError(t, err) } diff --git a/zboxcore/allocationchange/moveobject.go b/zboxcore/allocationchange/moveobject.go index a8119b760..5f7ed9b63 100644 --- a/zboxcore/allocationchange/moveobject.go +++ b/zboxcore/allocationchange/moveobject.go @@ -7,18 +7,58 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/pathutil" + "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/google/uuid" ) type MoveFileChange struct { change ObjectTree fileref.RefEntity DestPath string + Uuid uuid.UUID } -func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]string) (err error) { +func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, fileIDMeta map[string]string) (err error) { + oldParentPath, oldFileName := pathutil.Split(ch.ObjectTree.GetPath()) + fields, err := common.GetPathFields(oldParentPath) + if err != nil { + return + } - fields, err := common.GetPathFields(ch.DestPath) + delRef := rootRef + for i := 0; i < len(fields); i++ { + found := false + for _, child := range delRef.Children { + if child.GetName() == fields[i] { + delRef = child.(*fileref.Ref) + delRef.HashToBeComputed = true + found = true + break + } + } + + if !found { + err = errors.New("invalid_reference_path", "Ref not found in root reference object") + return + } + } + + var removed bool + for i, child := range delRef.Children { + if child.GetName() == oldFileName { + delRef.RemoveChild(i) + removed = true + break + } + } + + if !removed { + err = errors.New("incomplete_move", "could not remove ref from source path") + return + } + + fields, err = common.GetPathFields(ch.DestPath) if err != nil { return } @@ -39,12 +79,16 @@ func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]strin } if !found { + uid := util.GetSHA1Uuid(ch.Uuid, fields[i]) + ch.Uuid = uid newRef := &fileref.Ref{ Type: fileref.DIRECTORY, AllocationID: dirRef.AllocationID, Path: path.Join("/", strings.Join(fields[:i+1], "/")), Name: fields[i], + FileID: uid.String(), } + fileIDMeta[newRef.Path] = newRef.FileID dirRef.AddChild(newRef) dirRef = newRef } @@ -63,49 +107,11 @@ func (ch *MoveFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]strin affectedRef = ch.ObjectTree.(*fileref.Ref) } - oldParentPath, oldFileName := pathutil.Split(ch.ObjectTree.GetPath()) affectedRef.Path = pathutil.Join(dirRef.GetPath(), affectedRef.Name) ch.processChildren(affectedRef) dirRef.AddChild(ch.ObjectTree) - fields, err = common.GetPathFields(oldParentPath) - if err != nil { - return - } - - delRef := rootRef - for i := 0; i < len(fields); i++ { - found := false - for _, child := range delRef.Children { - if child.GetName() == fields[i] { - delRef = child.(*fileref.Ref) - delRef.HashToBeComputed = true - found = true - break - } - } - - if !found { - err = errors.New("invalid_reference_path", "Ref not found in root reference object") - return - } - } - - var removed bool - for i, child := range delRef.Children { - if child.GetName() == oldFileName { - delRef.RemoveChild(i) - removed = true - break - } - } - - if !removed { - err = errors.New("incomplete_move", "could not remove ref from source path") - return - } - rootRef.CalculateHash() return } diff --git a/zboxcore/allocationchange/renameobject.go b/zboxcore/allocationchange/renameobject.go index d9e3955a8..64f5851d9 100644 --- a/zboxcore/allocationchange/renameobject.go +++ b/zboxcore/allocationchange/renameobject.go @@ -16,7 +16,6 @@ type RenameFileChange struct { } func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]string) (err error) { - parentPath := path.Dir(ch.ObjectTree.GetPath()) fields, err := common.GetPathFields(parentPath) if err != nil { @@ -47,11 +46,12 @@ func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]str if ch.ObjectTree.GetType() == fileref.FILE { affectedRef = &(ch.ObjectTree.(*fileref.FileRef)).Ref } else { - err = errors.New("invalid_rename_op", "Object to rename is not a file use move instead") + affectedRef = ch.ObjectTree.(*fileref.Ref) } affectedRef.Path = pathutil.Join(parentPath, ch.NewName) affectedRef.Name = ch.NewName + affectedRef.HashToBeComputed = true dirRef.AddChild(ch.ObjectTree) found = true @@ -76,6 +76,7 @@ func (ch *RenameFileChange) processChildren(curRef *fileref.Ref) { } else { childRef = childRefEntity.(*fileref.Ref) } + childRef.HashToBeComputed = true childRef.Path = pathutil.Join(curRef.Path, childRef.Name) if childRefEntity.GetType() == fileref.DIRECTORY { ch.processChildren(childRef) diff --git a/zboxcore/blockchain/entity.go b/zboxcore/blockchain/entity.go index 160be645e..77f4efe7d 100644 --- a/zboxcore/blockchain/entity.go +++ b/zboxcore/blockchain/entity.go @@ -2,11 +2,43 @@ package blockchain import ( "encoding/json" + "github.com/0chain/gosdk/core/util" + "math" + "sync" "sync/atomic" "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/core/conf" + "github.com/0chain/gosdk/core/node" ) +var miners []string +var mGuard sync.Mutex + +func getMinMinersSubmit() int { + minMiners := util.MaxInt(calculateMinRequired(float64(chain.MinSubmit), float64(len(chain.Miners))/100), 1) + return minMiners +} + +func calculateMinRequired(minRequired, percent float64) int { + return int(math.Ceil(minRequired * percent)) +} + +func GetStableMiners() []string { + mGuard.Lock() + defer mGuard.Unlock() + if len(miners) == 0 { + miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) + } + + return miners +} +func ResetStableMiners() { + mGuard.Lock() + defer mGuard.Unlock() + miners = util.GetRandom(chain.Miners, getMinMinersSubmit()) +} + type ChainConfig struct { BlockWorker string Sharders []string @@ -74,13 +106,14 @@ func PopulateNodes(nodesjson string) ([]string, error) { } var chain *ChainConfig +var Sharders *node.NodeHolder func init() { chain = &ChainConfig{ MaxTxnQuery: 5, QuerySleepTime: 5, - MinSubmit: 50, - MinConfirmation: 50, + MinSubmit: 10, + MinConfirmation: 10, } } @@ -94,10 +127,11 @@ func PopulateChain(minerjson string, sharderjson string) error { if err != nil { return err } - chain.Sharders, err = PopulateNodes(sharderjson) + sharders, err := PopulateNodes(sharderjson) if err != nil { return err } + SetSharders(sharders) return nil } @@ -105,8 +139,11 @@ func GetBlockWorker() string { return chain.BlockWorker } +func GetAllSharders() []string { + return Sharders.All() +} func GetSharders() []string { - return chain.Sharders + return Sharders.Healthy() } func GetMiners() []string { @@ -134,7 +171,15 @@ func SetBlockWorker(blockWorker string) { } func SetSharders(sharderArray []string) { - chain.Sharders = sharderArray + consensus := conf.DefaultSharderConsensous + config, err := conf.GetClientConfig() + if err == nil && config != nil { + consensus = config.SharderConsensous + } + if len(sharderArray) < consensus { + consensus = len(sharderArray) + } + Sharders = node.NewHolder(sharderArray, consensus) } func SetMiners(minerArray []string) { diff --git a/zboxcore/fileref/fileref.go b/zboxcore/fileref/fileref.go index ad18b5583..df821c5f0 100644 --- a/zboxcore/fileref/fileref.go +++ b/zboxcore/fileref/fileref.go @@ -60,24 +60,28 @@ type RefEntity interface { } type Ref struct { - Type string `json:"type" mapstructure:"type"` - AllocationID string `json:"allocation_id" mapstructure:"allocation_id"` - Name string `json:"name" mapstructure:"name"` - Path string `json:"path" mapstructure:"path"` - Size int64 `json:"size" mapstructure:"size"` - ActualSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` - Hash string `json:"hash" mapstructure:"hash"` - ChunkSize int64 `json:"chunk_size" mapstructure:"chunk_size"` - NumBlocks int64 `json:"num_of_blocks" mapstructure:"num_of_blocks"` - PathHash string `json:"path_hash" mapstructure:"path_hash"` - LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` - FileID string `json:"file_id" mapstructure:"file_id"` - FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` - HashToBeComputed bool - ChildrenLoaded bool - Children []RefEntity `json:"-" mapstructure:"-"` - CreatedAt common.Timestamp `json:"created_at" mapstructure:"created_at"` - UpdatedAt common.Timestamp `json:"updated_at" mapstructure:"updated_at"` + Type string `json:"type" mapstructure:"type"` + AllocationID string `json:"allocation_id" mapstructure:"allocation_id"` + Name string `json:"name" mapstructure:"name"` + Path string `json:"path" mapstructure:"path"` + Size int64 `json:"size" mapstructure:"size"` + ActualSize int64 `json:"actual_file_size" mapstructure:"actual_file_size"` + Hash string `json:"hash" mapstructure:"hash"` + ChunkSize int64 `json:"chunk_size" mapstructure:"chunk_size"` + NumBlocks int64 `json:"num_of_blocks" mapstructure:"num_of_blocks"` + PathHash string `json:"path_hash" mapstructure:"path_hash"` + LookupHash string `json:"lookup_hash" mapstructure:"lookup_hash"` + FileID string `json:"file_id" mapstructure:"file_id"` + FileMetaHash string `json:"file_meta_hash" mapstructure:"file_meta_hash"` + ThumbnailHash string `json:"thumbnail_hash" mapstructure:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size" mapstructure:"thumbnail_size"` + ActualThumbnailHash string `json:"actual_thumbnail_hash" mapstructure:"actual_thumbnail_hash"` + ActualThumbnailSize int64 `json:"actual_thumbnail_size" mapstructure:"actual_thumbnail_size"` + HashToBeComputed bool + ChildrenLoaded bool + Children []RefEntity `json:"-" mapstructure:"-"` + CreatedAt common.Timestamp `json:"created_at" mapstructure:"created_at"` + UpdatedAt common.Timestamp `json:"updated_at" mapstructure:"updated_at"` } func GetReferenceLookup(allocationID string, path string) string { diff --git a/zboxcore/mocks/AllocationChange.go b/zboxcore/mocks/AllocationChange.go index ea012fc55..d5205842a 100644 --- a/zboxcore/mocks/AllocationChange.go +++ b/zboxcore/mocks/AllocationChange.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/EncryptionScheme.go b/zboxcore/mocks/EncryptionScheme.go index 834fab862..bbd4f0286 100644 --- a/zboxcore/mocks/EncryptionScheme.go +++ b/zboxcore/mocks/EncryptionScheme.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -17,6 +17,10 @@ func (_m *EncryptionScheme) Decrypt(_a0 *encryption.EncryptedMessage) ([]byte, e ret := _m.Called(_a0) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage) ([]byte, error)); ok { + return rf(_a0) + } if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage) []byte); ok { r0 = rf(_a0) } else { @@ -25,7 +29,6 @@ func (_m *EncryptionScheme) Decrypt(_a0 *encryption.EncryptedMessage) ([]byte, e } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.EncryptedMessage) error); ok { r1 = rf(_a0) } else { @@ -40,6 +43,10 @@ func (_m *EncryptionScheme) Encrypt(data []byte) (*encryption.EncryptedMessage, ret := _m.Called(data) var r0 *encryption.EncryptedMessage + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (*encryption.EncryptedMessage, error)); ok { + return rf(data) + } if rf, ok := ret.Get(0).(func([]byte) *encryption.EncryptedMessage); ok { r0 = rf(data) } else { @@ -48,7 +55,6 @@ func (_m *EncryptionScheme) Encrypt(data []byte) (*encryption.EncryptedMessage, } } - var r1 error if rf, ok := ret.Get(1).(func([]byte) error); ok { r1 = rf(data) } else { @@ -72,18 +78,35 @@ func (_m *EncryptionScheme) GetEncryptedKey() string { return r0 } +// GetEncryptedKeyPoint provides a mock function with given fields: +func (_m *EncryptionScheme) GetEncryptedKeyPoint() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + // GetPrivateKey provides a mock function with given fields: func (_m *EncryptionScheme) GetPrivateKey() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -98,13 +121,16 @@ func (_m *EncryptionScheme) GetPublicKey() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -119,13 +145,16 @@ func (_m *EncryptionScheme) GetReGenKey(encPublicKey string, tag string) (string ret := _m.Called(encPublicKey, tag) var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(string, string) (string, error)); ok { + return rf(encPublicKey, tag) + } if rf, ok := ret.Get(0).(func(string, string) string); ok { r0 = rf(encPublicKey, tag) } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func(string, string) error); ok { r1 = rf(encPublicKey, tag) } else { @@ -149,16 +178,48 @@ func (_m *EncryptionScheme) InitForDecryption(tag string, encryptedKey string) e return r0 } +// InitForDecryptionWithPoint provides a mock function with given fields: tag, point +func (_m *EncryptionScheme) InitForDecryptionWithPoint(tag string, point string) error { + ret := _m.Called(tag, point) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(tag, point) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // InitForEncryption provides a mock function with given fields: tag func (_m *EncryptionScheme) InitForEncryption(tag string) { _m.Called(tag) } +// InitForEncryptionWithPoint provides a mock function with given fields: tag, point +func (_m *EncryptionScheme) InitForEncryptionWithPoint(tag string, point string) error { + ret := _m.Called(tag, point) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(tag, point) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // Initialize provides a mock function with given fields: mnemonic func (_m *EncryptionScheme) Initialize(mnemonic string) ([]byte, error) { ret := _m.Called(mnemonic) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(string) ([]byte, error)); ok { + return rf(mnemonic) + } if rf, ok := ret.Get(0).(func(string) []byte); ok { r0 = rf(mnemonic) } else { @@ -167,7 +228,6 @@ func (_m *EncryptionScheme) Initialize(mnemonic string) ([]byte, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(mnemonic) } else { @@ -196,6 +256,10 @@ func (_m *EncryptionScheme) ReDecrypt(D *encryption.ReEncryptedMessage) ([]byte, ret := _m.Called(D) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.ReEncryptedMessage) ([]byte, error)); ok { + return rf(D) + } if rf, ok := ret.Get(0).(func(*encryption.ReEncryptedMessage) []byte); ok { r0 = rf(D) } else { @@ -204,7 +268,6 @@ func (_m *EncryptionScheme) ReDecrypt(D *encryption.ReEncryptedMessage) ([]byte, } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.ReEncryptedMessage) error); ok { r1 = rf(D) } else { @@ -219,6 +282,10 @@ func (_m *EncryptionScheme) ReEncrypt(encMsg *encryption.EncryptedMessage, reGen ret := _m.Called(encMsg, reGenKey, clientPublicKey) var r0 *encryption.ReEncryptedMessage + var r1 error + if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage, string, string) (*encryption.ReEncryptedMessage, error)); ok { + return rf(encMsg, reGenKey, clientPublicKey) + } if rf, ok := ret.Get(0).(func(*encryption.EncryptedMessage, string, string) *encryption.ReEncryptedMessage); ok { r0 = rf(encMsg, reGenKey, clientPublicKey) } else { @@ -227,7 +294,6 @@ func (_m *EncryptionScheme) ReEncrypt(encMsg *encryption.EncryptedMessage, reGen } } - var r1 error if rf, ok := ret.Get(1).(func(*encryption.EncryptedMessage, string, string) error); ok { r1 = rf(encMsg, reGenKey, clientPublicKey) } else { diff --git a/zboxcore/mocks/FileNameBuilder.go b/zboxcore/mocks/FileNameBuilder.go new file mode 100644 index 000000000..b8df10942 --- /dev/null +++ b/zboxcore/mocks/FileNameBuilder.go @@ -0,0 +1,95 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// FileNameBuilder is an autogenerated mock type for the FileNameBuilder type +type FileNameBuilder struct { + mock.Mock +} + +// ClipsFile provides a mock function with given fields: index +func (_m *FileNameBuilder) ClipsFile(index int) string { + ret := _m.Called(index) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(index) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// ClipsFileName provides a mock function with given fields: index +func (_m *FileNameBuilder) ClipsFileName(index int) string { + ret := _m.Called(index) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(index) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// FileExt provides a mock function with given fields: +func (_m *FileNameBuilder) FileExt() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// OutDir provides a mock function with given fields: +func (_m *FileNameBuilder) OutDir() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// OutFile provides a mock function with given fields: +func (_m *FileNameBuilder) OutFile() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +type mockConstructorTestingTNewFileNameBuilder interface { + mock.TestingT + Cleanup(func()) +} + +// NewFileNameBuilder creates a new instance of FileNameBuilder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFileNameBuilder(t mockConstructorTestingTNewFileNameBuilder) *FileNameBuilder { + mock := &FileNameBuilder{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/Hasher.go b/zboxcore/mocks/Hasher.go new file mode 100644 index 000000000..1e20707a3 --- /dev/null +++ b/zboxcore/mocks/Hasher.go @@ -0,0 +1,153 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// Hasher is an autogenerated mock type for the Hasher type +type Hasher struct { + mock.Mock +} + +// Finalize provides a mock function with given fields: +func (_m *Hasher) Finalize() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetFileHash provides a mock function with given fields: +func (_m *Hasher) GetFileHash() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetFixedMerkleRoot provides a mock function with given fields: +func (_m *Hasher) GetFixedMerkleRoot() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetValidationRoot provides a mock function with given fields: +func (_m *Hasher) GetValidationRoot() (string, error) { + ret := _m.Called() + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// WriteToFile provides a mock function with given fields: buf +func (_m *Hasher) WriteToFile(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WriteToFixedMT provides a mock function with given fields: buf +func (_m *Hasher) WriteToFixedMT(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WriteToValidationMT provides a mock function with given fields: buf +func (_m *Hasher) WriteToValidationMT(buf []byte) error { + ret := _m.Called(buf) + + var r0 error + if rf, ok := ret.Get(0).(func([]byte) error); ok { + r0 = rf(buf) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewHasher interface { + mock.TestingT + Cleanup(func()) +} + +// NewHasher creates a new instance of Hasher. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewHasher(t mockConstructorTestingTNewHasher) *Hasher { + mock := &Hasher{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/HttpClient.go b/zboxcore/mocks/HttpClient.go index 0d9a50f09..e7a62e27c 100644 --- a/zboxcore/mocks/HttpClient.go +++ b/zboxcore/mocks/HttpClient.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *HttpClient) Do(req *http.Request) (*http.Response, error) { ret := _m.Called(req) var r0 *http.Response + var r1 error + if rf, ok := ret.Get(0).(func(*http.Request) (*http.Response, error)); ok { + return rf(req) + } if rf, ok := ret.Get(0).(func(*http.Request) *http.Response); ok { r0 = rf(req) } else { @@ -26,7 +30,6 @@ func (_m *HttpClient) Do(req *http.Request) (*http.Response, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(*http.Request) error); ok { r1 = rf(req) } else { diff --git a/zboxcore/mocks/LiveUploadReader.go b/zboxcore/mocks/LiveUploadReader.go new file mode 100644 index 000000000..3c470b5bf --- /dev/null +++ b/zboxcore/mocks/LiveUploadReader.go @@ -0,0 +1,91 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// LiveUploadReader is an autogenerated mock type for the LiveUploadReader type +type LiveUploadReader struct { + mock.Mock +} + +// GetClipsFile provides a mock function with given fields: clipsIndex +func (_m *LiveUploadReader) GetClipsFile(clipsIndex int) string { + ret := _m.Called(clipsIndex) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(clipsIndex) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetClipsFileName provides a mock function with given fields: cliipsIndex +func (_m *LiveUploadReader) GetClipsFileName(cliipsIndex int) string { + ret := _m.Called(cliipsIndex) + + var r0 string + if rf, ok := ret.Get(0).(func(int) string); ok { + r0 = rf(cliipsIndex) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Read provides a mock function with given fields: p +func (_m *LiveUploadReader) Read(p []byte) (int, error) { + ret := _m.Called(p) + + var r0 int + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (int, error)); ok { + return rf(p) + } + if rf, ok := ret.Get(0).(func([]byte) int); ok { + r0 = rf(p) + } else { + r0 = ret.Get(0).(int) + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(p) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Size provides a mock function with given fields: +func (_m *LiveUploadReader) Size() int64 { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +type mockConstructorTestingTNewLiveUploadReader interface { + mock.TestingT + Cleanup(func()) +} + +// NewLiveUploadReader creates a new instance of LiveUploadReader. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewLiveUploadReader(t mockConstructorTestingTNewLiveUploadReader) *LiveUploadReader { + mock := &LiveUploadReader{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/M3u8Writer.go b/zboxcore/mocks/M3u8Writer.go new file mode 100644 index 000000000..858e00d7f --- /dev/null +++ b/zboxcore/mocks/M3u8Writer.go @@ -0,0 +1,101 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// M3u8Writer is an autogenerated mock type for the M3u8Writer type +type M3u8Writer struct { + mock.Mock +} + +// Seek provides a mock function with given fields: offset, whence +func (_m *M3u8Writer) Seek(offset int64, whence int) (int64, error) { + ret := _m.Called(offset, whence) + + var r0 int64 + var r1 error + if rf, ok := ret.Get(0).(func(int64, int) (int64, error)); ok { + return rf(offset, whence) + } + if rf, ok := ret.Get(0).(func(int64, int) int64); ok { + r0 = rf(offset, whence) + } else { + r0 = ret.Get(0).(int64) + } + + if rf, ok := ret.Get(1).(func(int64, int) error); ok { + r1 = rf(offset, whence) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Sync provides a mock function with given fields: +func (_m *M3u8Writer) Sync() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Truncate provides a mock function with given fields: size +func (_m *M3u8Writer) Truncate(size int64) error { + ret := _m.Called(size) + + var r0 error + if rf, ok := ret.Get(0).(func(int64) error); ok { + r0 = rf(size) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Write provides a mock function with given fields: p +func (_m *M3u8Writer) Write(p []byte) (int, error) { + ret := _m.Called(p) + + var r0 int + var r1 error + if rf, ok := ret.Get(0).(func([]byte) (int, error)); ok { + return rf(p) + } + if rf, ok := ret.Get(0).(func([]byte) int); ok { + r0 = rf(p) + } else { + r0 = ret.Get(0).(int) + } + + if rf, ok := ret.Get(1).(func([]byte) error); ok { + r1 = rf(p) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewM3u8Writer interface { + mock.TestingT + Cleanup(func()) +} + +// NewM3u8Writer creates a new instance of M3u8Writer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewM3u8Writer(t mockConstructorTestingTNewM3u8Writer) *M3u8Writer { + mock := &M3u8Writer{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/RefEntity.go b/zboxcore/mocks/RefEntity.go index 4e255d3c1..cd62950fc 100644 --- a/zboxcore/mocks/RefEntity.go +++ b/zboxcore/mocks/RefEntity.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/SCRestAPIHandler.go b/zboxcore/mocks/SCRestAPIHandler.go index f07f77d3e..ebccc15fc 100644 --- a/zboxcore/mocks/SCRestAPIHandler.go +++ b/zboxcore/mocks/SCRestAPIHandler.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/SignFunc.go b/zboxcore/mocks/SignFunc.go new file mode 100644 index 000000000..8b657fd3d --- /dev/null +++ b/zboxcore/mocks/SignFunc.go @@ -0,0 +1,49 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// SignFunc is an autogenerated mock type for the SignFunc type +type SignFunc struct { + mock.Mock +} + +// Execute provides a mock function with given fields: hash +func (_m *SignFunc) Execute(hash string) (string, error) { + ret := _m.Called(hash) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(string) (string, error)); ok { + return rf(hash) + } + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(hash) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewSignFunc interface { + mock.TestingT + Cleanup(func()) +} + +// NewSignFunc creates a new instance of SignFunc. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewSignFunc(t mockConstructorTestingTNewSignFunc) *SignFunc { + mock := &SignFunc{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zboxcore/mocks/StatusCallback.go b/zboxcore/mocks/StatusCallback.go index 1baaef7a4..eb2584ff9 100644 --- a/zboxcore/mocks/StatusCallback.go +++ b/zboxcore/mocks/StatusCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/Suite.go b/zboxcore/mocks/Suite.go index 9810840ae..96874b0cb 100644 --- a/zboxcore/mocks/Suite.go +++ b/zboxcore/mocks/Suite.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zboxcore/mocks/codec.go b/zboxcore/mocks/codec.go deleted file mode 100644 index 8a9611e7e..000000000 --- a/zboxcore/mocks/codec.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by mockery v0.0.0-dev. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// codec is an autogenerated mock type for the codec type -type codec struct { - mock.Mock -} - -// Decode provides a mock function with given fields: in -func (_m *codec) Decode(in [][]byte) ([]byte, error) { - ret := _m.Called(in) - - var r0 []byte - if rf, ok := ret.Get(0).(func([][]byte) []byte); ok { - r0 = rf(in) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func([][]byte) error); ok { - r1 = rf(in) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Encode provides a mock function with given fields: in -func (_m *codec) Encode(in []byte) ([][]byte, error) { - ret := _m.Called(in) - - var r0 [][]byte - if rf, ok := ret.Get(0).(func([]byte) [][]byte); ok { - r0 = rf(in) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([][]byte) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func([]byte) error); ok { - r1 = rf(in) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/zboxcore/sdk/allocation.go b/zboxcore/sdk/allocation.go index 0328bbe9a..922350615 100644 --- a/zboxcore/sdk/allocation.go +++ b/zboxcore/sdk/allocation.go @@ -39,9 +39,10 @@ import ( ) var ( - noBLOBBERS = errors.New("", "No Blobbers set in this allocation") - notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") - IsWasm = false + noBLOBBERS = errors.New("", "No Blobbers set in this allocation") + notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object") + IsWasm = false + MultiOpBatchSize = 10 ) const ( @@ -59,6 +60,10 @@ const ( CanRenameMask = uint16(32) // 0010 0000 ) +const ( + emptyFileDataHash = "d41d8cd98f00b204e9800998ecf8427e" +) + // Expected success rate is calculated (NumDataShards)*100/(NumDataShards+NumParityShards) var GetFileInfo = func(localpath string) (os.FileInfo, error) { @@ -103,7 +108,11 @@ type ConsolidatedFileMeta struct { ActualFileSize int64 ActualNumBlocks int64 EncryptedKey string - Collaborators []fileref.Collaborator + + ActualThumbnailSize int64 + ActualThumbnailHash string + + Collaborators []fileref.Collaborator } type AllocationStats struct { @@ -232,6 +241,8 @@ func GetWritePriceRange() (PriceRange, error) { func SetWasm() { IsWasm = true + BatchSize = 5 + MultiOpBatchSize = 7 } func getPriceRange(name string) (PriceRange, error) { @@ -362,45 +373,6 @@ func (a *Allocation) UploadFile(workdir, localpath string, remotepath string, return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", false, false) } -func (a *Allocation) CreateDir(remotePath string) error { - if !a.isInitialized() { - return notInitialized - } - - if remotePath == "" { - return errors.New("invalid_name", "Invalid name for dir") - } - - if !path.IsAbs(remotePath) { - return errors.New("invalid_path", "Path is not absolute") - } - - remotePath = zboxutil.RemoteClean(remotePath) - timestamp := int64(common.Now()) - req := DirRequest{ - allocationObj: a, - allocationID: a.ID, - allocationTx: a.Tx, - blobbers: a.Blobbers, - mu: &sync.Mutex{}, - dirMask: zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1), - connectionID: zboxutil.NewConnectionId(), - remotePath: remotePath, - wg: &sync.WaitGroup{}, - timestamp: timestamp, - alreadyExists: map[uint64]bool{}, - Consensus: Consensus{ - RWMutex: &sync.RWMutex{}, - consensusThresh: a.consensusThreshold, - fullconsensus: a.fullconsensus, - }, - } - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - - err := req.ProcessDir(a) - return err -} - func (a *Allocation) RepairFile(file sys.File, remotepath string, status StatusCallback, mask zboxutil.Uint128, ref *fileref.FileRef) error { @@ -587,6 +559,7 @@ func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileN Workdir: workdir, RemotePath: fileMeta.RemotePath, } + if isUpdate[idx] { operationRequests[idx].OperationType = constants.FileOperationUpdate } @@ -671,6 +644,7 @@ func (a *Allocation) StartChunkedUpload(workdir, localPath string, } connectionId := zboxutil.NewConnectionId() + now := time.Now() ChunkedUpload, err := CreateChunkedUpload(workdir, a, fileMeta, fileReader, isUpdate, isRepair, webStreaming, connectionId, @@ -678,6 +652,9 @@ func (a *Allocation) StartChunkedUpload(workdir, localPath string, if err != nil { return err } + elapsedCreateChunkedUpload := time.Since(now) + logger.Logger.Info("[StartChunkedUpload]", zap.String("allocation_id", a.ID), + zap.Duration("CreateChunkedUpload", elapsedCreateChunkedUpload)) return ChunkedUpload.Start() } @@ -821,10 +798,9 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { return notInitialized } connectionID := zboxutil.NewConnectionId() - + var mo MultiOperation for i := 0; i < len(operations); { // resetting multi operation and previous paths for every batch - var mo MultiOperation mo.allocationObj = a mo.operationMask = zboxutil.NewUint128(0) mo.maskMU = &sync.Mutex{} @@ -835,7 +811,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { consensusThresh: a.consensusThreshold, fullconsensus: a.fullconsensus, } - previousPaths := make(map[string]bool) connectionErrors := make([]error, len(mo.allocationObj.Blobbers)) @@ -866,12 +841,18 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { } for ; i < len(operations); i++ { + if len(mo.operations) >= MultiOpBatchSize { + // max batch size reached, commit + connectionID = zboxutil.NewConnectionId() + break + } op := operations[i] remotePath := op.RemotePath parentPaths := GenerateParentPaths(remotePath) if _, ok := previousPaths[remotePath]; ok { // conflict found, commit + connectionID = zboxutil.NewConnectionId() break } @@ -914,7 +895,6 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { connectionID = newConnectionID break } - err = operation.Verify(a) if err != nil { return err @@ -932,9 +912,9 @@ func (a *Allocation) DoMultiOperation(operations []OperationRequest) error { if err != nil { return err } + mo.operations = nil } } - return nil } @@ -1136,6 +1116,7 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { if a.ReadPriceRange.Max == 0 && a.ReadPriceRange.Min == 0 { isReadFree = true } + now := time.Now() for _, dr := range drs { wg.Add(1) @@ -1154,6 +1135,7 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { }(dr) } wg.Wait() + elapsedProcessDownloadRequest := time.Since(now) // Do not send readmarkers for free reads if isReadFree { @@ -1165,11 +1147,15 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { a.downloadChan <- dr }(dr) } + l.Logger.Info("[processReadMarker]", zap.String("allocation_id", a.ID), + zap.Int("num of download requests", len(drs)), + zap.Duration("processDownloadRequest", elapsedProcessDownloadRequest)) return } successMask := zboxutil.NewUint128(0) var redeemError error + for pos, totalBlocks := range blobberMap { if totalBlocks == 0 { continue @@ -1187,6 +1173,12 @@ func (a *Allocation) processReadMarker(drs []*DownloadRequest) { }(pos, totalBlocks) } wg.Wait() + elapsedSubmitReadmarker := time.Since(now) - elapsedProcessDownloadRequest + + l.Logger.Info("[processReadMarker]", zap.String("allocation_id", a.ID), + zap.Int("num of download requests", len(drs)), + zap.Duration("processDownloadRequest", elapsedProcessDownloadRequest), + zap.Duration("submitReadmarker", elapsedSubmitReadmarker)) for _, dr := range drs { if dr.skip { continue @@ -1506,6 +1498,8 @@ func (a *Allocation) GetFileMeta(path string) (*ConsolidatedFileMeta, error) { result.EncryptedKey = ref.EncryptedKey result.Collaborators = ref.Collaborators result.ActualFileSize = ref.ActualFileSize + result.ActualThumbnailHash = ref.ActualThumbnailHash + result.ActualThumbnailSize = ref.ActualThumbnailSize if result.ActualFileSize > 0 { result.ActualNumBlocks = (ref.ActualFileSize + CHUNK_SIZE - 1) / CHUNK_SIZE } @@ -1561,6 +1555,8 @@ func (a *Allocation) GetFileMetaFromAuthTicket(authTicket string, lookupHash str result.Size = ref.Size result.NumBlocks = ref.NumBlocks result.ActualFileSize = ref.ActualFileSize + result.ActualThumbnailHash = ref.ActualThumbnailHash + result.ActualThumbnailSize = ref.ActualThumbnailSize if result.ActualFileSize > 0 { result.ActualNumBlocks = (result.ActualFileSize + CHUNK_SIZE - 1) / CHUNK_SIZE } @@ -1634,135 +1630,42 @@ func (a *Allocation) deleteFile(path string, threshConsensus, fullConsensus int, return err } -func (a *Allocation) RenameObject(path string, destName string) error { - if !a.isInitialized() { - return notInitialized - } - - if !a.CanRename() { - return constants.ErrFileOptionNotPermitted - } - - if path == "" { - return errors.New("invalid_path", "Invalid path for the list") - } - - if path == "/" { - return errors.New("invalid_operation", "cannot rename root path") - } - - path = zboxutil.RemoteClean(path) - isabs := zboxutil.IsRemoteAbs(path) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") - } - - err := ValidateRemoteFileName(destName) - if err != nil { - return err - } - - req := &RenameRequest{consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - req.newName = destName - req.consensus.fullconsensus = a.fullconsensus - req.consensus.consensusThresh = a.consensusThreshold - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = path - req.renameMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessRename() -} - -func (a *Allocation) MoveObject(srcPath string, destPath string) error { +func (a *Allocation) createDir(remotePath string, threshConsensus, fullConsensus int, mask zboxutil.Uint128) error { if !a.isInitialized() { return notInitialized } - if !a.CanMove() { - return constants.ErrFileOptionNotPermitted - } - - if len(srcPath) == 0 || len(destPath) == 0 { - return errors.New("invalid_path", "Invalid path for copy") - } - srcPath = zboxutil.RemoteClean(srcPath) - isabs := zboxutil.IsRemoteAbs(srcPath) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") + if remotePath == "" { + return errors.New("invalid_name", "Invalid name for dir") } - err := ValidateRemoteFileName(destPath) - if err != nil { - return err + if !path.IsAbs(remotePath) { + return errors.New("invalid_path", "Path is not absolute") } - req := &MoveRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - if destPath != "/" { - destPath = strings.TrimSuffix(destPath, "/") + remotePath = zboxutil.RemoteClean(remotePath) + timestamp := int64(common.Now()) + req := DirRequest{ + allocationObj: a, + allocationID: a.ID, + allocationTx: a.Tx, + blobbers: a.Blobbers, + mu: &sync.Mutex{}, + dirMask: mask, + connectionID: zboxutil.NewConnectionId(), + remotePath: remotePath, + wg: &sync.WaitGroup{}, + timestamp: timestamp, + Consensus: Consensus{ + RWMutex: &sync.RWMutex{}, + consensusThresh: threshConsensus, + fullconsensus: fullConsensus, + }, } - req.destPath = destPath - req.fullconsensus = a.fullconsensus - req.consensusThresh = a.consensusThreshold req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = srcPath - req.moveMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessMove() -} -func (a *Allocation) CopyObject(path string, destPath string) error { - if !a.isInitialized() { - return notInitialized - } - - if !a.CanCopy() { - return constants.ErrFileOptionNotPermitted - } - - if len(path) == 0 || len(destPath) == 0 { - return errors.New("invalid_path", "Invalid path for copy") - } - path = zboxutil.RemoteClean(path) - isabs := zboxutil.IsRemoteAbs(path) - if !isabs { - return errors.New("invalid_path", "Path should be valid and absolute") - } - - err := ValidateRemoteFileName(destPath) - if err != nil { - return err - } - - req := &CopyRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}} - req.allocationObj = a - req.blobbers = a.Blobbers - req.allocationID = a.ID - req.allocationTx = a.Tx - if destPath != "/" { - destPath = strings.TrimSuffix(destPath, "/") - } - req.destPath = destPath - req.fullconsensus = a.fullconsensus - req.consensusThresh = a.consensusThreshold - req.ctx, req.ctxCncl = context.WithCancel(a.ctx) - req.remotefilepath = path - req.copyMask = zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1) - req.maskMU = &sync.Mutex{} - req.connectionID = zboxutil.NewConnectionId() - req.timestamp = int64(common.Now()) - return req.ProcessCopy() + err := req.ProcessDir(a) + return err } func (a *Allocation) GetAuthTicketForShare( @@ -1963,7 +1866,7 @@ func (a *Allocation) UploadAuthTicketToBlobber(authTicket string, clientEncPubKe consensus := Consensus{ RWMutex: &sync.RWMutex{}, consensus: len(success), - consensusThresh: a.consensusThreshold, + consensusThresh: a.DataShards, fullconsensus: a.fullconsensus, } if !consensus.isConsensusOk() { @@ -2478,7 +2381,6 @@ func (a *Allocation) UpdateWithRepair( size int64, extend bool, lock uint64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, statusCB StatusCallback, @@ -2488,7 +2390,7 @@ func (a *Allocation) UpdateWithRepair( } l.Logger.Info("Updating allocation") - hash, _, err := UpdateAllocation(size, extend, a.ID, lock, updateTerms, addBlobberId, removeBlobberId, setThirdPartyExtendable, fileOptionsParams) + hash, _, err := UpdateAllocation(size, extend, a.ID, lock, addBlobberId, removeBlobberId, setThirdPartyExtendable, fileOptionsParams) if err != nil { return "", err } diff --git a/zboxcore/sdk/allocation_file_copy_test.go b/zboxcore/sdk/allocation_file_copy_test.go deleted file mode 100644 index 317e4e580..000000000 --- a/zboxcore/sdk/allocation_file_copy_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_CopyObject(t *testing.T) { - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - createClient := resty.CreateClient - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - defer func() { - zboxutil.Client = rawClient - resty.CreateClient = createClient - }() - - type parameters struct { - path string - destPath string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Uninitialized_Failed", - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Wrong_Path_Or_Destination_Path_Failed", - parameters: parameters{ - path: "", - destPath: "", - }, - wantErr: true, - errMsg: "invalid_path: Invalid path for copy", - }, - { - name: "Test_Invalid_Remote_Absolute_Path", - parameters: parameters{ - path: "abc", - destPath: "/d", - }, - wantErr: true, - errMsg: "invalid_path: Path should be valid and absolute", - }, - { - name: "Test_Success", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_CopyObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_CopyObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockRollback(a, &mockClient) - setupMockCommitRequest(a) - setupMockWriteLockRequest(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - DataShards: numBlobbers, - FileOptions: 63, - } - a.InitAllocation() - - setupMockAllocation(t, a) - - sdkInitialized = true - for i := 0; i < numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_CopyObject" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.CopyObject(tt.parameters.path, tt.parameters.destPath) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} diff --git a/zboxcore/sdk/allocation_file_move_test.go b/zboxcore/sdk/allocation_file_move_test.go deleted file mode 100644 index e1f437992..000000000 --- a/zboxcore/sdk/allocation_file_move_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_MoveObject(t *testing.T) { - - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - - defer func() { - zboxutil.Client = rawClient - }() - - type parameters struct { - path string - destPath string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Cover_Copy_Object", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Cover_Delete_Object", - parameters: parameters{ - path: "/1.txt", - destPath: "/d", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte(`{"status":2}`)) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte(`{"status":2}`)) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockHttpResponse(t, &mockClient, "TestAllocation_MoveObject", testCaseName, a, http.MethodDelete, http.StatusOK, []byte("")) - setupMockCommitRequest(a) - setupMockRollback(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - Tx: "TestAllocation_MoveObject", - DataShards: 2, - ParityShards: 2, - } - - setupMockAllocation(t, a) - - for i := 0; i < numBlobbers; i++ { - - path := "/TestAllocation_MoveObject" + tt.name + mockBlobberUrl + strconv.Itoa(i) - - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: path, - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.MoveObject(tt.parameters.path, tt.parameters.destPath) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} diff --git a/zboxcore/sdk/allocation_file_rename_test.go b/zboxcore/sdk/allocation_file_rename_test.go deleted file mode 100644 index 32a9ec05b..000000000 --- a/zboxcore/sdk/allocation_file_rename_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package sdk - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - "time" - - "github.com/0chain/errors" - "github.com/0chain/gosdk/core/resty" - "github.com/0chain/gosdk/core/zcncrypto" - "github.com/0chain/gosdk/zboxcore/blockchain" - zclient "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/fileref" - "github.com/0chain/gosdk/zboxcore/mocks" - "github.com/0chain/gosdk/zboxcore/zboxutil" - "github.com/stretchr/testify/require" -) - -func TestAllocation_RenameObject(t *testing.T) { - const ( - mockType = "f" - ) - - rawClient := zboxutil.Client - createClient := resty.CreateClient - - var mockClient = mocks.HttpClient{} - zboxutil.Client = &mockClient - - client := zclient.GetClient() - client.Wallet = &zcncrypto.Wallet{ - ClientID: mockClientId, - ClientKey: mockClientKey, - } - - zboxutil.Client = &mockClient - resty.CreateClient = func(t *http.Transport, timeout time.Duration) resty.Client { - return &mockClient - } - - defer func() { - zboxutil.Client = rawClient - resty.CreateClient = createClient - }() - type parameters struct { - path string - destName string - } - tests := []struct { - name string - parameters parameters - setup func(*testing.T, string, *Allocation) (teardown func(*testing.T)) - wantErr bool - errMsg string - }{ - { - name: "Test_Uninitialized_Failed", - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - a.initialized = false - return func(t *testing.T) { - a.initialized = true - } - }, - wantErr: true, - errMsg: "sdk_not_initialized: Please call InitStorageSDK Init and use GetAllocation to get the allocation object", - }, - { - name: "Test_Wrong_Path_Or_Destination_Path_Failed", - parameters: parameters{ - path: "", - destName: "", - }, - wantErr: true, - errMsg: "invalid_path: Invalid path for the list", - }, - { - name: "Test_Invalid_Remote_Absolute_Path", - parameters: parameters{ - path: "abc", - destName: "/2.txt", - }, - wantErr: true, - errMsg: "invalid_path: Path should be valid and absolute", - }, - { - name: "Test_Success", - parameters: parameters{ - path: "/1.txt", - destName: "/2.txt", - }, - setup: func(t *testing.T, testCaseName string, a *Allocation) (teardown func(t *testing.T)) { - body, err := json.Marshal(&fileref.ReferencePath{ - Meta: map[string]interface{}{ - "type": mockType, - }, - }) - require.NoError(t, err) - setupMockHttpResponse(t, &mockClient, "TestAllocation_RenameObject", testCaseName, a, http.MethodGet, http.StatusOK, body) - setupMockHttpResponse(t, &mockClient, "TestAllocation_RenameObject", testCaseName, a, http.MethodPost, http.StatusOK, []byte("")) - setupMockCommitRequest(a) - setupMockRollback(a, &mockClient) - setupMockWriteLockRequest(a, &mockClient) - return nil - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - a := &Allocation{ - DataShards: 2, - ParityShards: 2, - FileOptions: 63, - } - a.InitAllocation() - sdkInitialized = true - for i := 0; i < numBlobbers; i++ { - a.Blobbers = append(a.Blobbers, &blockchain.StorageNode{ - ID: tt.name + mockBlobberId + strconv.Itoa(i), - Baseurl: "http://TestAllocation_RenameObject" + tt.name + mockBlobberUrl + strconv.Itoa(i), - }) - } - if tt.setup != nil { - if teardown := tt.setup(t, tt.name, a); teardown != nil { - defer teardown(t) - } - } - err := a.RenameObject(tt.parameters.path, tt.parameters.destName) - require.EqualValues(tt.wantErr, err != nil) - if err != nil { - require.EqualValues(tt.errMsg, errors.Top(err)) - return - } - require.NoErrorf(err, "unexpected error: %v", err) - }) - } -} diff --git a/zboxcore/sdk/allocation_test.go b/zboxcore/sdk/allocation_test.go index 5570a5f3a..ccf7ab5c3 100644 --- a/zboxcore/sdk/allocation_test.go +++ b/zboxcore/sdk/allocation_test.go @@ -73,6 +73,15 @@ func setupMockHttpResponse( testCaseName string, a *Allocation, httpMethod string, statusCode int, body []byte) { + for i := 0; i < numBlobbers; i++ { + mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { + return req.Method == httpMethod && strings.Contains(req.URL.String(), "list=true") + })).Return(&http.Response{ + StatusCode: statusCode, + Body: io.NopCloser(bytes.NewReader(body)), + }, nil).Once() + } + for i := 0; i < numBlobbers; i++ { url := funcName + testCaseName + mockBlobberUrl + strconv.Itoa(i) mockClient.On("Do", mock.MatchedBy(func(req *http.Request) bool { @@ -80,7 +89,7 @@ func setupMockHttpResponse( strings.Contains(req.URL.String(), url) })).Return(&http.Response{ StatusCode: statusCode, - Body: ioutil.NopCloser(bytes.NewReader(body)), + Body: io.NopCloser(bytes.NewReader(body)), }, nil).Once() } } @@ -122,7 +131,7 @@ func setupMockWriteLockRequest(a *Allocation, mockClient *mocks.HttpClient) { Status: WMLockStatusOK, } respBuf, _ := json.Marshal(resp) - return ioutil.NopCloser(bytes.NewReader(respBuf)) + return io.NopCloser(bytes.NewReader(respBuf)) }(), }, nil) } diff --git a/zboxcore/sdk/blockdownloadworker.go b/zboxcore/sdk/blockdownloadworker.go index 5d496ad70..d79715cd7 100644 --- a/zboxcore/sdk/blockdownloadworker.go +++ b/zboxcore/sdk/blockdownloadworker.go @@ -4,8 +4,9 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" + "strconv" "sync" "time" @@ -151,11 +152,30 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { if resp.Body != nil { defer resp.Body.Close() } - + if req.chunkSize == 0 { + req.chunkSize = CHUNK_SIZE + } var rspData downloadBlock - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err + respLen := resp.Header.Get("Content-Length") + var respBody []byte + if respLen != "" { + len, err := strconv.Atoi(respLen) + zlogger.Logger.Info("respLen", len) + if err != nil { + zlogger.Logger.Error("respLen convert error: ", err) + return err + } + respBody, err = readBody(resp.Body, len) + if err != nil { + zlogger.Logger.Error("respBody read error: ", err) + return err + } + } else { + respBody, err = readBody(resp.Body, int(req.numBlocks)*req.chunkSize) + if err != nil { + zlogger.Logger.Error("respBody read error: ", err) + return err + } } if resp.StatusCode != http.StatusOK { zlogger.Logger.Debug(fmt.Sprintf("downloadBlobberBlock FAIL - blobberID: %v, clientID: %v, blockNum: %d, retry: %d, response: %v", req.blobber.ID, client.GetClientID(), header.BlockNum, retry, string(respBody))) @@ -166,9 +186,14 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { } dR := downloadResponse{} - err = json.Unmarshal(respBody, &dR) - if err != nil { - return err + contentType := resp.Header.Get("Content-Type") + if contentType == "application/json" { + err = json.Unmarshal(respBody, &dR) + if err != nil { + return err + } + } else { + dR.Data = respBody } if req.contentMode == DOWNLOAD_CONTENT_FULL && req.shouldVerify { @@ -232,3 +257,21 @@ func (req *BlockDownloadRequest) downloadBlobberBlock() { func AddBlockDownloadReq(req *BlockDownloadRequest) { downloadBlockChan[req.blobber.ID] <- req } + +func readBody(r io.Reader, size int) ([]byte, error) { + b := make([]byte, 0, size) + for { + if len(b) == cap(b) { + // Add more capacity (let append pick how much). + b = append(b, 0)[:len(b)] + } + n, err := r.Read(b[len(b):cap(b)]) + b = b[:len(b)+n] + if err != nil { + if err == io.EOF { + err = nil + } + return b, err + } + } +} diff --git a/zboxcore/sdk/chunk_upload_vars.go b/zboxcore/sdk/chunk_upload_vars.go new file mode 100644 index 000000000..5a3095822 --- /dev/null +++ b/zboxcore/sdk/chunk_upload_vars.go @@ -0,0 +1,10 @@ +//go:build !windows +// +build !windows + +package sdk + +import "syscall" + +var ( + sysProcAttr = &syscall.SysProcAttr{} +) diff --git a/zboxcore/sdk/chunk_upload_vars_windows.go b/zboxcore/sdk/chunk_upload_vars_windows.go new file mode 100644 index 000000000..4b0d2113b --- /dev/null +++ b/zboxcore/sdk/chunk_upload_vars_windows.go @@ -0,0 +1,10 @@ +//go:build windows +// +build windows + +package sdk + +import "syscall" + +var ( + sysProcAttr = &syscall.SysProcAttr{HideWindow: true} +) diff --git a/zboxcore/sdk/chunked_upload.go b/zboxcore/sdk/chunked_upload.go index 89d082629..e6846cc75 100644 --- a/zboxcore/sdk/chunked_upload.go +++ b/zboxcore/sdk/chunked_upload.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "os" "path/filepath" "strings" "sync" @@ -29,6 +30,7 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/google/uuid" "github.com/klauspost/reedsolomon" + "github.com/remeh/sizedwaitgroup" ) const ( @@ -36,6 +38,7 @@ const ( ) var ( + CmdFFmpeg = "ffmpeg" // DefaultHashFunc default hash method for stream merkle tree DefaultHashFunc = func(left, right string) string { return coreEncryption.Hash(left + right) @@ -101,12 +104,15 @@ func CreateChunkedUpload( } if webStreaming { - newFileReader, newFileMeta, err := TranscodeWebStreaming(fileReader, fileMeta) + newFileReader, newFileMeta, f, err := TranscodeWebStreaming(workdir, fileReader, fileMeta) + defer os.Remove(f) + if err != nil { return nil, thrown.New("upload_failed", err.Error()) } fileMeta = *newFileMeta fileReader = newFileReader + } err := ValidateRemoteFileName(fileMeta.RemoteName) @@ -154,7 +160,7 @@ func CreateChunkedUpload( uploadMask: uploadMask, chunkSize: DefaultChunkSize, - chunkNumber: 1, + chunkNumber: 100, encryptOnUpload: false, webStreaming: false, @@ -165,7 +171,8 @@ func CreateChunkedUpload( opCode: opCode, } - su.ctx, su.ctxCncl = context.WithCancel(allocationObj.ctx) + // su.ctx, su.ctxCncl = context.WithCancel(allocationObj.ctx) + su.ctx, su.ctxCncl = context.WithCancelCause(allocationObj.ctx) if isUpdate { su.httpMethod = http.MethodPut @@ -193,7 +200,7 @@ func CreateChunkedUpload( su.workdir = filepath.Join(workdir, ".zcn") //create upload folder to save progress - err = sys.Files.MkdirAll(filepath.Join(su.workdir, "upload"), 0744) + err = sys.Files.MkdirAll(filepath.Join(su.workdir, "upload"), 0766) if err != nil { return nil, err } @@ -201,6 +208,7 @@ func CreateChunkedUpload( for _, opt := range opts { opt(su) } + if su.progressStorer == nil { su.progressStorer = createFsChunkedUploadProgress(context.Background()) } @@ -212,7 +220,7 @@ func CreateChunkedUpload( // encrypt option has been changed. upload it from scratch // chunkSize has been changed. upload it from scratch // actual size has been changed. upload it from scratch - if su.progress.ChunkSize != su.chunkSize || su.progress.EncryptOnUpload != su.encryptOnUpload || su.progress.ActualSize != su.fileMeta.ActualSize { + if su.progress.ChunkSize != su.chunkSize || su.progress.EncryptOnUpload != su.encryptOnUpload || su.progress.ActualSize != su.fileMeta.ActualSize || su.progress.ChunkNumber != su.chunkNumber || su.progress.ConnectionID == "" { su.progress.ChunkSize = 0 // reset chunk size } @@ -266,7 +274,7 @@ func CreateChunkedUpload( }, } } - cReader, err := createChunkReader(su.fileReader, fileMeta.ActualSize, int64(su.chunkSize), su.allocationObj.DataShards, su.encryptOnUpload, su.uploadMask, su.fileErasureEncoder, su.fileEncscheme, su.fileHasher) + cReader, err := createChunkReader(su.fileReader, fileMeta.ActualSize, int64(su.chunkSize), su.allocationObj.DataShards, su.encryptOnUpload, su.uploadMask, su.fileErasureEncoder, su.fileEncscheme, su.fileHasher, su.chunkNumber) if err != nil { return nil, err @@ -277,76 +285,11 @@ func CreateChunkedUpload( su.formBuilder = CreateChunkedUploadFormBuilder() su.isRepair = isRepair + su.uploadChan = make(chan UploadData, 1) + su.uploadWG.Add(1) + go su.uploadProcessor() return su, nil - -} - -// ChunkedUpload upload manager with chunked upload feature -type ChunkedUpload struct { - consensus Consensus - - workdir string - - allocationObj *Allocation - progress UploadProgress - progressStorer ChunkedUploadProgressStorer - client zboxutil.HttpClient - - uploadMask zboxutil.Uint128 - - // httpMethod POST = Upload File / PUT = Update file - httpMethod string - buildChange func(ref *fileref.FileRef, - uid uuid.UUID, timestamp common.Timestamp) allocationchange.AllocationChange - - fileMeta FileMeta - fileReader io.Reader - fileErasureEncoder reedsolomon.Encoder - fileEncscheme encryption.EncryptionScheme - fileHasher Hasher - - thumbnailBytes []byte - thumbailErasureEncoder reedsolomon.Encoder - - chunkReader ChunkedUploadChunkReader - formBuilder ChunkedUploadFormBuilder - - // encryptOnUpload encrypt data on upload or not. - encryptOnUpload bool - // webStreaming whether data has to be encoded. - webStreaming bool - // chunkSize how much bytes a chunk has. 64KB is default value. - chunkSize int64 - // chunkNumber the number of chunks in a http upload request. 1 is default value - chunkNumber int - - // shardUploadedSize how much bytes a shard has. it is original size - shardUploadedSize int64 - // shardUploadedThumbnailSize how much thumbnail bytes a shard has. it is original size - shardUploadedThumbnailSize int64 - // size of shard - shardSize int64 - - // statusCallback trigger progress on StatusCallback - statusCallback StatusCallback - - blobbers []*ChunkedUploadBlobber - - writeMarkerMutex *WriteMarkerMutex - - // isRepair identifies if upload is repair operation - isRepair bool - - opCode int - uploadTimeOut time.Duration - commitTimeOut time.Duration - maskMu *sync.Mutex - ctx context.Context - ctxCncl context.CancelFunc - addConsensus int32 - encryptedKeyPoint string - encryptedKey string } // progressID build local progress id with [allocationid]_[Hash(LocalPath+"_"+RemotePath)]_[RemoteName] format @@ -395,6 +338,7 @@ func (su *ChunkedUpload) createUploadProgress(connectionId string) { EncryptOnUpload: su.encryptOnUpload, EncryptedKeyPoint: su.encryptedKeyPoint, ActualSize: su.fileMeta.ActualSize, + ChunkNumber: su.chunkNumber, } } su.progress.Blobbers = make([]*UploadBlobberStatus, su.allocationObj.DataShards+su.allocationObj.ParityShards) @@ -445,6 +389,9 @@ func (su *ChunkedUpload) process() error { su.statusCallback.Started(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.fileMeta.ActualSize)+int(su.fileMeta.ActualThumbnailSize)) } alreadyUploadedData := 0 + defer su.chunkReader.Close() + defer close(su.uploadChan) + defer su.ctxCncl(nil) for { chunks, err := su.readChunks(su.chunkNumber) @@ -462,7 +409,9 @@ func (su *ChunkedUpload) process() error { su.progress.UploadLength += chunks.totalReadSize if chunks.isFinal { - su.fileMeta.ActualHash, err = su.fileHasher.GetFileHash() + if su.fileMeta.ActualHash == "" { + su.fileMeta.ActualHash, err = su.chunkReader.GetFileHash() + } if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) @@ -482,7 +431,6 @@ func (su *ChunkedUpload) process() error { //chunk has not be uploaded yet if chunks.chunkEndIndex > su.progress.ChunkIndex { - start := time.Now() err = su.processUpload( chunks.chunkStartIndex, chunks.chunkEndIndex, chunks.fileShards, chunks.thumbnailShards, @@ -494,19 +442,19 @@ func (su *ChunkedUpload) process() error { } return err } - logger.Logger.Info("[processUpload]", time.Since(start).Milliseconds()) } else { // Write data to hashers for i, blobberShard := range chunks.fileShards { + hasher := su.blobbers[i].progress.Hasher for _, chunkBytes := range blobberShard { - err = su.blobbers[i].progress.Hasher.WriteToFixedMT(chunkBytes) + err = hasher.WriteToFixedMT(chunkBytes) if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) } return err } - err = su.blobbers[i].progress.Hasher.WriteToValidationMT(chunkBytes) + err = hasher.WriteToValidationMT(chunkBytes) if err != nil { if su.statusCallback != nil { su.statusCallback.Error(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, err) @@ -520,10 +468,7 @@ func (su *ChunkedUpload) process() error { // last chunk might 0 with io.EOF // https://stackoverflow.com/questions/41208359/how-to-test-eof-on-io-reader-in-go - if chunks.totalReadSize > 0 && chunks.chunkEndIndex > su.progress.ChunkIndex { - su.progress.ChunkIndex = chunks.chunkEndIndex - su.saveProgress() - + if chunks.totalReadSize > 0 && chunks.chunkEndIndex >= su.progress.ChunkIndex { if su.statusCallback != nil { su.statusCallback.InProgress(su.allocationObj.ID, su.fileMeta.RemotePath, su.opCode, int(su.progress.UploadLength)-alreadyUploadedData, nil) } @@ -538,13 +483,15 @@ func (su *ChunkedUpload) process() error { // Start start/resume upload func (su *ChunkedUpload) Start() error { - - defer su.ctxCncl() + now := time.Now() err := su.process() if err != nil { return err } + su.ctx, su.ctxCncl = context.WithCancelCause(su.allocationObj.ctx) + defer su.ctxCncl(nil) + elapsedProcess := time.Since(now) logger.Logger.Info("Completed the upload. Submitting for commit") blobbers := make([]*blockchain.StorageNode, len(su.blobbers)) @@ -566,15 +513,23 @@ func (su *ChunkedUpload) Start() error { } return err } + elapsedLock := time.Since(now) - elapsedProcess defer su.writeMarkerMutex.Unlock( su.ctx, su.uploadMask, blobbers, su.uploadTimeOut, su.progress.ConnectionID) //nolint: errcheck + defer func() { + elapsedProcessCommit := time.Since(now) - elapsedProcess - elapsedLock + logger.Logger.Info("[ChunkedUpload - start] Timings:\n", + fmt.Sprintf("allocation_id: %s", su.allocationObj.ID), + fmt.Sprintf("process: %d ms", elapsedProcess.Milliseconds()), + fmt.Sprintf("Lock: %d ms", elapsedLock.Milliseconds()), + fmt.Sprintf("processCommit: %d ms", elapsedProcessCommit.Milliseconds())) + }() return su.processCommit() } func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { - data := &batchChunksData{ chunkStartIndex: -1, chunkEndIndex: -1, @@ -624,7 +579,6 @@ func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { break } } - return data, nil } @@ -632,14 +586,18 @@ func (su *ChunkedUpload) readChunks(num int) (*batchChunksData, error) { func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, fileShards []blobberShards, thumbnailShards blobberShards, isFinal bool, uploadLength int64) error { - su.consensus.Reset() - - ctx, cancel := context.WithCancel(context.TODO()) - defer cancel() var errCount int32 + blobberUpload := UploadData{ + chunkStartIndex: chunkStartIndex, + chunkEndIndex: chunkEndIndex, + isFinal: isFinal, + encryptedKey: su.encryptedKey, + uploadBody: make([]blobberData, len(su.blobbers)), + saveProgress: uploadLength > 0, + } + wgErrors := make(chan error, len(su.blobbers)) - wgDone := make(chan bool) if len(fileShards) == 0 { return thrown.New("upload_failed", "Upload failed. No data to upload") } @@ -670,51 +628,35 @@ func (su *ChunkedUpload) processUpload(chunkStartIndex, chunkEndIndex int, } return } - - err = b.sendUploadRequest(ctx, su, chunkEndIndex, isFinal, su.encryptedKey, body, formData, pos) - if err != nil { - if strings.Contains(err.Error(), "duplicate") { - su.consensus.Done() - errC := atomic.AddInt32(&su.addConsensus, 1) - if errC >= int32(su.consensus.consensusThresh) { - wgErrors <- err - } - return - } - logger.Logger.Error("error during sendUploadRequest", err) - errC := atomic.AddInt32(&errCount, 1) - if errC > int32(su.allocationObj.ParityShards-1) { // If atleast data shards + 1 number of blobbers can process the upload, it can be repaired later - wgErrors <- err - } - + blobberUpload.uploadBody[pos] = blobberData{ + body: body, + formData: formData, } }(blobber, thumbnailChunkData, pos) } - go func() { - wg.Wait() - close(wgDone) - close(wgErrors) - }() - - if su.addConsensus >= int32(su.consensus.consensusThresh) { - su.removeProgress() - return thrown.New("upload_failed", "Duplicate upload for path "+su.fileMeta.RemotePath) - } + wg.Wait() + close(wgErrors) - select { - case <-wgDone: - break - case err := <-wgErrors: + for err := range wgErrors { su.removeProgress() return thrown.New("upload_failed", fmt.Sprintf("Upload failed. %s", err)) } - if !su.consensus.isConsensusOk() { - return thrown.New("consensus_not_met", fmt.Sprintf("Upload failed File not found for path %s. Required consensus atleast %d, got %d", - su.fileMeta.RemotePath, su.consensus.consensusThresh, su.consensus.getConsensus())) + select { + case <-su.ctx.Done(): + return context.Cause(su.ctx) + default: + } + su.uploadChan <- blobberUpload + if isFinal { + su.uploadWG.Wait() + select { + case <-su.ctx.Done(): + return context.Cause(su.ctx) + default: + } } - return nil } @@ -793,3 +735,67 @@ func getShardSize(dataSize int64, dataShards int, isEncrypted bool) int64 { } return n*DefaultChunkSize + remainderShards } + +func (su *ChunkedUpload) uploadProcessor() { + defer su.uploadWG.Done() + for { + select { + case <-su.ctx.Done(): + return + case uploadData, ok := <-su.uploadChan: + if !ok { + return + } + wgErrors := make(chan error, len(su.blobbers)) + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + su.consensus.Reset() + var pos uint64 + var errCount int32 + swg := sizedwaitgroup.New(BatchSize) + for i := su.uploadMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { + pos = uint64(i.TrailingZeros()) + swg.Add() + go func(pos uint64) { + defer swg.Done() + err := su.blobbers[pos].sendUploadRequest(ctx, su, uploadData.chunkEndIndex, uploadData.isFinal, su.encryptedKey, uploadData.uploadBody[pos].body, uploadData.uploadBody[pos].formData, pos) + + if err != nil { + if strings.Contains(err.Error(), "duplicate") { + su.consensus.Done() + errC := atomic.AddInt32(&su.addConsensus, 1) + if errC >= int32(su.consensus.consensusThresh) { + wgErrors <- err + } + return + } + logger.Logger.Error("error during sendUploadRequest", err) + errC := atomic.AddInt32(&errCount, 1) + if errC > int32(su.allocationObj.ParityShards-1) { // If atleast data shards + 1 number of blobbers can process the upload, it can be repaired later + wgErrors <- err + } + } + }(pos) + } + swg.Wait() + close(wgErrors) + for err := range wgErrors { + su.removeProgress() + su.ctxCncl(thrown.New("upload_failed", fmt.Sprintf("Upload failed. %s", err))) + return + } + if !su.consensus.isConsensusOk() { + su.ctxCncl(thrown.New("consensus_not_met", fmt.Sprintf("Upload failed File not found for path %s. Required consensus atleast %d, got %d", + su.fileMeta.RemotePath, su.consensus.consensusThresh, su.consensus.getConsensus()))) + return + } + if uploadData.saveProgress { + su.progress.ChunkIndex = uploadData.chunkEndIndex + su.saveProgress() + } + if uploadData.isFinal { + return + } + } + } +} diff --git a/zboxcore/sdk/chunked_upload_blobber.go b/zboxcore/sdk/chunked_upload_blobber.go index b03b03200..4e3662a89 100644 --- a/zboxcore/sdk/chunked_upload_blobber.go +++ b/zboxcore/sdk/chunked_upload_blobber.go @@ -84,14 +84,12 @@ func (sb *ChunkedUploadBlobber) sendUploadRequest( for i := 0; i < 3; i++ { err, shouldContinue = func() (err error, shouldContinue bool) { reqCtx, ctxCncl := context.WithTimeout(ctx, su.uploadTimeOut) - start := time.Now() var resp *http.Response err = zboxutil.HttpDo(reqCtx, ctxCncl, req, func(r *http.Response, err error) error { resp = r return err }) defer ctxCncl() - logger.Logger.Info("[sendUploadRequestBlobber] ", time.Since(start).Milliseconds()) if err != nil { logger.Logger.Error("Upload : ", err) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader.go b/zboxcore/sdk/chunked_upload_chunk_reader.go index d3daed0e5..f41d2f1eb 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader.go @@ -4,6 +4,7 @@ import ( "io" "math" "strconv" + "sync" "github.com/0chain/errors" "github.com/0chain/gosdk/constants" @@ -18,6 +19,11 @@ type ChunkedUploadChunkReader interface { // Read read, encode and encrypt all bytes Read(buf []byte) ([][]byte, error) + + //Close Hash Channel + Close() + //GetFileHash get file hash + GetFileHash() (string, error) } // chunkedUploadChunkReader read chunk bytes from io.Reader. see detail on https://github.com/0chain/blobber/wiki/Protocols#what-is-fixedmerkletree @@ -54,11 +60,15 @@ type chunkedUploadChunkReader struct { // encscheme encryption scheme encscheme encryption.EncryptionScheme // hasher to calculate actual file hash, validation root and fixed merkle root - hasher Hasher + hasher Hasher + hasherDataChan chan []byte + hasherError error + hasherWG sync.WaitGroup + closeOnce sync.Once } // createChunkReader create ChunkReader instance -func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards int, encryptOnUpload bool, uploadMask zboxutil.Uint128, erasureEncoder reedsolomon.Encoder, encscheme encryption.EncryptionScheme, hasher Hasher) (ChunkedUploadChunkReader, error) { +func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards int, encryptOnUpload bool, uploadMask zboxutil.Uint128, erasureEncoder reedsolomon.Encoder, encscheme encryption.EncryptionScheme, hasher Hasher, chunkNumber int) (ChunkedUploadChunkReader, error) { if chunkSize <= 0 { return nil, errors.Throw(constants.ErrInvalidParameter, "chunkSize: "+strconv.FormatInt(chunkSize, 10)) @@ -87,6 +97,8 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i erasureEncoder: erasureEncoder, encscheme: encscheme, hasher: hasher, + hasherDataChan: make(chan []byte, 2*chunkNumber), + hasherWG: sync.WaitGroup{}, } if r.encryptOnUpload { @@ -98,7 +110,9 @@ func createChunkReader(fileReader io.Reader, size, chunkSize int64, dataShards i } r.chunkDataSizePerRead = r.chunkDataSize * int64(dataShards) - + // TODO: enable this for concurrent hashing + // r.hasherWG.Add(1) + // go r.hashData() return r, nil } @@ -138,7 +152,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { ReadSize: 0, FragmentSize: 0, } - chunkBytes := make([]byte, r.chunkDataSizePerRead) readLen, err := r.fileReader.Read(chunkBytes) if err != nil { @@ -157,7 +170,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { } chunk.FragmentSize = int64(math.Ceil(float64(readLen)/float64(r.dataShards))) + r.chunkHeaderSize - if readLen < int(r.chunkDataSizePerRead) { chunkBytes = chunkBytes[:readLen] chunk.IsFinal = true @@ -171,11 +183,10 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { } } - err = r.hasher.WriteToFile(chunkBytes) - if err != nil { - return chunk, err + if r.hasherError != nil { + return chunk, r.hasherError } - + _ = r.hasher.WriteToFile(chunkBytes) fragments, err := r.erasureEncoder.Split(chunkBytes) if err != nil { return nil, err @@ -185,7 +196,6 @@ func (r *chunkedUploadChunkReader) Next() (*ChunkData, error) { if err != nil { return nil, err } - var pos uint64 if r.encryptOnUpload { for i := r.uploadMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) { @@ -242,3 +252,29 @@ func (r *chunkedUploadChunkReader) Read(buf []byte) ([][]byte, error) { return fragments, nil } + +func (r *chunkedUploadChunkReader) Close() { + r.closeOnce.Do(func() { + close(r.hasherDataChan) + r.hasherWG.Wait() + }) +} + +func (r *chunkedUploadChunkReader) GetFileHash() (string, error) { + r.Close() + if r.hasherError != nil { + return "", r.hasherError + } + return r.hasher.GetFileHash() +} + +func (r *chunkedUploadChunkReader) hashData() { + defer r.hasherWG.Done() + for data := range r.hasherDataChan { + err := r.hasher.WriteToFile(data) + if err != nil { + r.hasherError = err + return + } + } +} diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go index 57a066f8a..70d0cd111 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_bench_test.go @@ -68,7 +68,7 @@ func BenchmarkChunkedUploadChunkReader(b *testing.B) { int64(bm.ChunkSize), bm.DataShards, bm.EncryptOnUpload, uploadMask, erasureEncoder, encscheme, - CreateHasher(getShardSize(bm.Size, bm.DataShards, bm.EncryptOnUpload)), + CreateHasher(getShardSize(bm.Size, bm.DataShards, bm.EncryptOnUpload)), 100, ) if err != nil { b.Fatal(err) diff --git a/zboxcore/sdk/chunked_upload_chunk_reader_test.go b/zboxcore/sdk/chunked_upload_chunk_reader_test.go index 1cff5032f..d6e756384 100644 --- a/zboxcore/sdk/chunked_upload_chunk_reader_test.go +++ b/zboxcore/sdk/chunked_upload_chunk_reader_test.go @@ -83,7 +83,7 @@ func TestReadChunks(t *testing.T) { int64(test.ChunkSize), test.DataShards, test.EncryptOnUpload, uploadMask, erasureEncoder, encscheme, - CreateHasher(getShardSize(test.Size, test.DataShards, test.EncryptOnUpload)), + CreateHasher(getShardSize(test.Size, test.DataShards, test.EncryptOnUpload)), 100, ) require.Nil(err) diff --git a/zboxcore/sdk/chunked_upload_form_builder.go b/zboxcore/sdk/chunked_upload_form_builder.go index dfb1aa69f..f0637fa7b 100644 --- a/zboxcore/sdk/chunked_upload_form_builder.go +++ b/zboxcore/sdk/chunked_upload_form_builder.go @@ -7,10 +7,8 @@ import ( "io" "mime/multipart" "sync" - "time" "github.com/0chain/gosdk/zboxcore/client" - "github.com/0chain/gosdk/zboxcore/logger" "golang.org/x/crypto/sha3" ) @@ -90,7 +88,6 @@ func (b *chunkedUploadFormBuilder) Build( if err != nil { return nil, metadata, err } - for _, chunkBytes := range fileChunksData { _, err = uploadFile.Write(chunkBytes) if err != nil { @@ -109,7 +106,7 @@ func (b *chunkedUploadFormBuilder) Build( metadata.FileBytesLen += len(chunkBytes) } - start := time.Now() + if isFinal { err = hasher.Finalize() if err != nil { @@ -140,7 +137,6 @@ func (b *chunkedUploadFormBuilder) Build( for err := range errChan { return nil, metadata, err } - logger.Logger.Info("[hasherTime]", time.Since(start).Milliseconds()) actualHashSignature, err := client.Sign(fileMeta.ActualHash) if err != nil { return nil, metadata, err @@ -200,6 +196,5 @@ func (b *chunkedUploadFormBuilder) Build( metadata.FixedMerkleRoot = formData.FixedMerkleRoot metadata.ValidationRoot = formData.ValidationRoot metadata.ThumbnailContentHash = formData.ThumbnailContentHash - return body, metadata, nil } diff --git a/zboxcore/sdk/chunked_upload_hasher.go b/zboxcore/sdk/chunked_upload_hasher.go index f7955934d..93e0de290 100644 --- a/zboxcore/sdk/chunked_upload_hasher.go +++ b/zboxcore/sdk/chunked_upload_hasher.go @@ -1,6 +1,7 @@ package sdk import ( + "crypto/md5" "encoding/hex" "hash" "sync" @@ -8,7 +9,6 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/constants" "github.com/0chain/gosdk/core/util" - "golang.org/x/crypto/sha3" ) type Hasher interface { @@ -38,7 +38,7 @@ type hasher struct { // CreateHasher creat Hasher instance func CreateHasher(dataSize int64) Hasher { return &hasher{ - File: sha3.New256(), + File: md5.New(), FixedMT: util.NewFixedMerkleTree(), ValidationMT: util.NewValidationTree(dataSize), } diff --git a/zboxcore/sdk/chunked_upload_model.go b/zboxcore/sdk/chunked_upload_model.go index 773d43f7e..6626c3136 100644 --- a/zboxcore/sdk/chunked_upload_model.go +++ b/zboxcore/sdk/chunked_upload_model.go @@ -1,13 +1,94 @@ package sdk import ( + "bytes" + "context" "encoding/json" "hash/fnv" + "io" "strconv" - + "sync" + "time" + + "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zboxcore/allocationchange" + "github.com/0chain/gosdk/zboxcore/encryption" + "github.com/0chain/gosdk/zboxcore/fileref" + "github.com/0chain/gosdk/zboxcore/zboxutil" + "github.com/google/uuid" + "github.com/klauspost/reedsolomon" "golang.org/x/crypto/sha3" ) +// ChunkedUpload upload manager with chunked upload feature +type ChunkedUpload struct { + consensus Consensus + + workdir string + + allocationObj *Allocation + progress UploadProgress + progressStorer ChunkedUploadProgressStorer + client zboxutil.HttpClient + + uploadMask zboxutil.Uint128 + + // httpMethod POST = Upload File / PUT = Update file + httpMethod string + buildChange func(ref *fileref.FileRef, + uid uuid.UUID, timestamp common.Timestamp) allocationchange.AllocationChange + + fileMeta FileMeta + fileReader io.Reader + fileErasureEncoder reedsolomon.Encoder + fileEncscheme encryption.EncryptionScheme + fileHasher Hasher + + thumbnailBytes []byte + thumbailErasureEncoder reedsolomon.Encoder + + chunkReader ChunkedUploadChunkReader + formBuilder ChunkedUploadFormBuilder + + // encryptOnUpload encrypt data on upload or not. + encryptOnUpload bool + // webStreaming whether data has to be encoded. + webStreaming bool + // chunkSize how much bytes a chunk has. 64KB is default value. + chunkSize int64 + // chunkNumber the number of chunks in a http upload request. 100 is default value + chunkNumber int + + // shardUploadedSize how much bytes a shard has. it is original size + shardUploadedSize int64 + // shardUploadedThumbnailSize how much thumbnail bytes a shard has. it is original size + shardUploadedThumbnailSize int64 + // size of shard + shardSize int64 + + // statusCallback trigger progress on StatusCallback + statusCallback StatusCallback + + blobbers []*ChunkedUploadBlobber + + writeMarkerMutex *WriteMarkerMutex + + // isRepair identifies if upload is repair operation + isRepair bool + + opCode int + uploadTimeOut time.Duration + commitTimeOut time.Duration + maskMu *sync.Mutex + ctx context.Context + ctxCncl context.CancelCauseFunc + addConsensus int32 + encryptedKeyPoint string + encryptedKey string + uploadChan chan UploadData + uploadWG sync.WaitGroup +} + // FileMeta metadata of stream input/local type FileMeta struct { // Mimetype mime type of source file @@ -88,8 +169,9 @@ type UploadProgress struct { ID string `json:"id"` // ChunkSize size of chunk - ChunkSize int64 `json:"chunk_size,omitempty"` - ActualSize int64 `json:"actual_size,omitempty"` + ChunkSize int64 `json:"chunk_size,omitempty"` + ActualSize int64 `json:"actual_size,omitempty"` + ChunkNumber int `json:"chunk_number,omitempty"` // EncryptOnUpload encrypt data on upload or not EncryptOnUpload bool `json:"is_encrypted,omitempty"` EncryptPrivateKey string `json:"-"` @@ -113,6 +195,22 @@ type UploadBlobberStatus struct { UploadLength int64 `json:"upload_length,omitempty"` } +// err = b.sendUploadRequest(ctx, su, chunkEndIndex, isFinal, su.encryptedKey, body, formData, pos) + +type UploadData struct { + chunkStartIndex int + chunkEndIndex int + isFinal bool + saveProgress bool + encryptedKey string + uploadBody []blobberData +} + +type blobberData struct { + body *bytes.Buffer + formData ChunkedUploadFormMetadata +} + type status struct { Hasher hasher UploadLength int64 `json:"upload_length,omitempty"` diff --git a/zboxcore/sdk/chunked_upload_option.go b/zboxcore/sdk/chunked_upload_option.go index 9a97e5654..a3fc3d850 100644 --- a/zboxcore/sdk/chunked_upload_option.go +++ b/zboxcore/sdk/chunked_upload_option.go @@ -1,6 +1,7 @@ package sdk import ( + "crypto/md5" "encoding/hex" "math" "os" @@ -8,7 +9,6 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" - "golang.org/x/crypto/sha3" ) // ChunkedUploadOption set stream option @@ -26,7 +26,7 @@ func WithThumbnail(buf []byte) ChunkedUploadOption { su.thumbnailBytes = buf su.fileMeta.ActualThumbnailSize = int64(len(buf)) - thumbnailHasher := sha3.New256() + thumbnailHasher := md5.New() thumbnailHasher.Write(buf) su.fileMeta.ActualThumbnailHash = hex.EncodeToString(thumbnailHasher.Sum(nil)) @@ -97,3 +97,9 @@ func WithEncryptedPoint(point string) ChunkedUploadOption { su.encryptedKeyPoint = point } } + +func WithActualHash(hash string) ChunkedUploadOption { + return func(su *ChunkedUpload) { + su.fileMeta.ActualHash = hash + } +} diff --git a/zboxcore/sdk/chunked_upload_web_streaming.go b/zboxcore/sdk/chunked_upload_web_streaming.go index cc4eac65a..ea09ae558 100644 --- a/zboxcore/sdk/chunked_upload_web_streaming.go +++ b/zboxcore/sdk/chunked_upload_web_streaming.go @@ -4,8 +4,10 @@ import ( "bufio" "bytes" "io" + "os" "os/exec" "path" + "path/filepath" "strings" thrown "github.com/0chain/errors" @@ -13,51 +15,75 @@ import ( ) // Converting the video file to fmp4 format for web streaming -func TranscodeWebStreaming(fileReader io.Reader, fileMeta FileMeta) (io.Reader, *FileMeta, error) { - var stdOut bytes.Buffer +func TranscodeWebStreaming(workdir string, fileReader io.Reader, fileMeta FileMeta) (io.Reader, *FileMeta, string, error) { var stdErr bytes.Buffer - args := []string{"-i", fileMeta.Path, "-g", "30", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1"} - cmdFfmpeg := exec.Command("ffmpeg", args...) + outDir := filepath.Join(workdir, ".zcn", "transcode") + // create ./zcn/transcode folder if it doesn't exists + os.MkdirAll(outDir, 0766) //nolint: errcheck - cmdFfmpeg.Stdout = bufio.NewWriter(&stdOut) - cmdFfmpeg.Stderr = bufio.NewWriter(&stdErr) + remoteName, remotePath := GetTranscodeFile(fileMeta.RemotePath) - err := cmdFfmpeg.Run() + fileName := filepath.Join(outDir, remoteName) + + logger.Logger.Info("transcode: start ", fileName) + + args := []string{"-i", fileMeta.Path, "-f", "mp4", "-movflags", "frag_keyframe+empty_moov+default_base_moof", fileName, "-y"} + cmd := exec.Command(CmdFFmpeg, args...) + cmd.Stderr = bufio.NewWriter(&stdErr) + cmd.SysProcAttr = sysProcAttr + err := cmd.Run() + + defer func() { + // w.Close() + err = cmd.Process.Kill() + if err != nil { + logger.Logger.Error(err) + } + }() if err != nil { - logger.Logger.Error(err) - return nil, nil, thrown.New("Transcoding Failed: ", err.Error()) + logger.Logger.Error(err, stdErr.String()) + return nil, nil, "", thrown.New("Transcoding Failed: ", err.Error()) } - trascodedBufSlice := stdOut.Bytes() - transcodedFileReader := bytes.NewReader(trascodedBufSlice) + // open file reader with readonly + r, err := os.Open(fileName) - remoteName, remotePath := getRemoteNameAndRemotePath(fileMeta.RemoteName, fileMeta.RemotePath) + if err != nil { + return nil, nil, fileName, err + } + + logger.Logger.Info("transcode: done ", fileName) + + fi, err := r.Stat() + if err != nil { + return nil, nil, fileName, err + } - transcodedFileMeta := &FileMeta{ - MimeType: "video/fmp4", + fm := &FileMeta{ + MimeType: "video/mp4", Path: fileMeta.Path, ThumbnailPath: fileMeta.ThumbnailPath, ActualHash: fileMeta.ActualHash, - ActualSize: int64(len(trascodedBufSlice)), + ActualSize: fi.Size(), ActualThumbnailSize: fileMeta.ActualThumbnailSize, ActualThumbnailHash: fileMeta.ActualThumbnailHash, RemoteName: remoteName, RemotePath: remotePath, } - return transcodedFileReader, transcodedFileMeta, nil + return r, fm, fileName, nil } -func getRemoteNameAndRemotePath(remoteName string, remotePath string) (string, string) { +func GetTranscodeFile(remotePath string) (string, string) { newRemotePath, newRemoteName := path.Split(remotePath) newRemoteNameSlice := strings.Split(newRemoteName, ".") if len(newRemoteNameSlice) > 0 { newRemoteNameSlice = newRemoteNameSlice[:len(newRemoteNameSlice)-1] } newRemoteNameWithoutType := strings.Join(newRemoteNameSlice, ".") - newRemoteName = "raw." + newRemoteNameWithoutType + ".mp4" + newRemoteName = newRemoteNameWithoutType + ".mp4" newRemotePath = newRemotePath + newRemoteName return newRemoteName, newRemotePath } diff --git a/zboxcore/sdk/commitworker.go b/zboxcore/sdk/commitworker.go index 81dab2470..2f3f22bb8 100644 --- a/zboxcore/sdk/commitworker.go +++ b/zboxcore/sdk/commitworker.go @@ -92,7 +92,7 @@ func startCommitWorker(blobberChan chan *CommitRequest, blobberID string) { func (commitreq *CommitRequest) processCommit() { defer commitreq.wg.Done() - + start := time.Now() l.Logger.Info("received a commit request") paths := make([]string, 0) for _, change := range commitreq.changes { @@ -187,6 +187,7 @@ func (commitreq *CommitRequest) processCommit() { commitreq.result = ErrorCommitResult(err.Error()) return } + l.Logger.Info("[commitBlobber]", time.Since(start).Milliseconds()) commitreq.result = SuccessCommitResult() } @@ -207,7 +208,10 @@ func (req *CommitRequest) commitBlobber( } else { wm.PreviousAllocationRoot = "" } - + if wm.AllocationRoot == wm.PreviousAllocationRoot { + l.Logger.Error("Allocation root and previous allocation root are same") + return thrown.New("commit_error", "Allocation root and previous allocation root are same") + } wm.FileMetaRoot = rootRef.FileMetaHash wm.AllocationID = req.allocationID wm.Size = size diff --git a/zboxcore/sdk/dirworker.go b/zboxcore/sdk/dirworker.go index c19ba468e..6ec68becd 100644 --- a/zboxcore/sdk/dirworker.go +++ b/zboxcore/sdk/dirworker.go @@ -96,25 +96,6 @@ func (req *DirRequest) ProcessDir(a *Allocation) error { } defer writeMarkerMU.Unlock(req.ctx, req.dirMask, a.Blobbers, time.Minute, req.connectionID) //nolint: errcheck - //Check if the allocation is to be repaired or rolled back - status, err := req.allocationObj.CheckAllocStatus() - l.Logger.Info("Allocation status: ", status) - if err != nil { - l.Logger.Error("Error checking allocation status: ", err) - return fmt.Errorf("directory creation failed: %s", err.Error()) - } - - if status == Repair { - l.Logger.Info("Repairing allocation") - //TODO: Need status callback to call repair allocation - // err = req.allocationObj.RepairAlloc() - // if err != nil { - // return err - // } - } - if status != Commit { - return ErrRetryOperation - } return req.commitRequest(existingDirCount) } diff --git a/zboxcore/sdk/download_reqeust_header.go b/zboxcore/sdk/download_reqeust_header.go index cd0e24e52..3606e4618 100644 --- a/zboxcore/sdk/download_reqeust_header.go +++ b/zboxcore/sdk/download_reqeust_header.go @@ -1,6 +1,7 @@ package sdk import ( + "encoding/base64" "fmt" "net/http" "strconv" @@ -38,7 +39,8 @@ func (h *DownloadRequestHeader) ToHeader(req *http.Request) { } if h.AuthToken != nil { - req.Header.Set("X-Auth-Token", string(h.AuthToken)) + token := base64.StdEncoding.EncodeToString(h.AuthToken) + req.Header.Set("X-Auth-Token", token) } if h.DownloadMode != "" { diff --git a/zboxcore/sdk/downloadworker.go b/zboxcore/sdk/downloadworker.go index 4359d46a2..3281a83e8 100644 --- a/zboxcore/sdk/downloadworker.go +++ b/zboxcore/sdk/downloadworker.go @@ -3,6 +3,7 @@ package sdk import ( "bytes" "context" + "crypto/md5" "encoding/hex" "encoding/json" "fmt" @@ -30,7 +31,6 @@ import ( "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/klauspost/reedsolomon" "go.dedis.ch/kyber/v3/group/edwards25519" - "golang.org/x/crypto/sha3" "golang.org/x/sync/errgroup" ) @@ -284,6 +284,10 @@ func (req *DownloadRequest) fillShards(shards [][][]byte, result *downloadBlock) } else { data = result.BlockChunks[i] } + if i >= len(shards) || len(shards[i]) <= result.idx { + l.Logger.Error("Invalid shard index", result.idx, len(shards), len(shards[i])) + return errors.New("invalid_shard_index", fmt.Sprintf("Invalid shard index %d shard len: %d shard block len: %d", result.idx, len(shards), i)) + } shards[i][result.idx] = data } return @@ -368,6 +372,13 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { op = opThumbnailDownload } fRef := req.fRef + if fRef != nil && fRef.ActualFileHash == emptyFileDataHash { + if req.statusCallback != nil { + req.statusCallback.Completed( + req.allocationID, remotePathCB, fRef.Name, "", len(emptyFileDataHash), op) + } + return + } size, chunksPerShard, blocksPerShard := req.size, req.chunksPerShard, req.blocksPerShard logger.Logger.Info( @@ -375,6 +386,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { "Blocks per blobber: %d", size, req.startBlock, req.endBlock, blocksPerShard), ) + now := time.Now() err := req.initEC() if err != nil { logger.Logger.Error(err) @@ -383,6 +395,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { err), remotePathCB) return } + elapsedInitEC := time.Since(now) if req.encryptedKey != "" { err = req.initEncryption() if err != nil { @@ -392,6 +405,7 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { return } } + elapsedInitEncryption := time.Since(now) - elapsedInitEC var downloaded int startBlock, endBlock, numBlocks := req.startBlock, req.endBlock, req.numBlocks @@ -410,21 +424,31 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { req.shouldVerify = false } } - var actualFileHasher hash.Hash - var isPREAndWholeFile bool - if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) { - actualFileHasher = sha3.New256() - isPREAndWholeFile = true - } - n := int((endBlock - startBlock + numBlocks - 1) / numBlocks) // Buffered channel to hold the blocks as they are downloaded blocks := make(chan blockData, n) + var ( + actualFileHasher hash.Hash + isPREAndWholeFile bool + closeOnce *sync.Once + hashDataChan chan []byte + hashWg *sync.WaitGroup + ) + + if !req.shouldVerify && (startBlock == 0 && endBlock == chunksPerShard) { + actualFileHasher = md5.New() + hashDataChan = make(chan []byte, n) + hashWg = &sync.WaitGroup{} + hashWg.Add(1) + closeOnce = &sync.Once{} + go processHashData(hashDataChan, hashWg, actualFileHasher) + isPREAndWholeFile = true + } + var wg sync.WaitGroup wg.Add(1) - // Handle writing the blocks in order as soon as they are downloaded go func() { buffer := make(map[int][]byte) @@ -433,8 +457,12 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { // If the block we need to write next is already in the buffer, write it numBytes := int64(math.Min(float64(remainingSize), float64(len(data)))) if isPREAndWholeFile { - actualFileHasher.Write(data[:numBytes]) + hashDataChan <- data[:numBytes] if i == n-1 { + closeOnce.Do(func() { + close(hashDataChan) + }) + hashWg.Wait() if calculatedFileHash, ok := checkHash(actualFileHasher, fRef, req.contentMode); !ok { req.errorCB(fmt.Errorf("Expected actual file hash %s, calculated file hash %s", fRef.ActualFileHash, calculatedFileHash), remotePathCB) @@ -465,8 +493,12 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { // Write the data numBytes := int64(math.Min(float64(remainingSize), float64(len(block.data)))) if isPREAndWholeFile { - actualFileHasher.Write(block.data[:numBytes]) + hashDataChan <- block.data[:numBytes] if i == n-1 { + closeOnce.Do(func() { + close(hashDataChan) + }) + hashWg.Wait() if calculatedFileHash, ok := checkHash(actualFileHasher, fRef, req.contentMode); !ok { req.errorCB(fmt.Errorf("Expected actual file hash %s, calculated file hash %s", fRef.ActualFileHash, calculatedFileHash), remotePathCB) @@ -475,7 +507,6 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { } } _, err = req.fileHandler.Write(block.data[:numBytes]) - if err != nil { req.errorCB(errors.Wrap(err, "Write file failed"), remotePathCB) return @@ -521,12 +552,25 @@ func (req *DownloadRequest) processDownload(ctx context.Context) { }) } if err := eg.Wait(); err != nil { + if isPREAndWholeFile { + closeOnce.Do(func() { + close(hashDataChan) + }) + } req.errorCB(err, remotePathCB) return } close(blocks) wg.Wait() + elapsedGetBlocksAndWrite := time.Since(now) - elapsedInitEC - elapsedInitEncryption + l.Logger.Info(fmt.Sprintf("[processDownload] Timings:\n allocation_id: %s,\n remotefilepath: %s,\n initEC: %d ms,\n initEncryption: %d ms,\n getBlocks and writes: %d ms", + req.allocationID, + req.remotefilepath, + elapsedInitEC.Milliseconds(), + elapsedInitEncryption.Milliseconds(), + elapsedGetBlocksAndWrite.Milliseconds(), + )) if req.statusCallback != nil { req.statusCallback.Completed( @@ -543,6 +587,13 @@ func checkHash(actualFileHasher hash.Hash, fref *fileref.FileRef, contentMode st } } +func processHashData(hashDataChan chan []byte, hashWg *sync.WaitGroup, actualFileHasher hash.Hash) { + defer hashWg.Done() + for data := range hashDataChan { + actualFileHasher.Write(data) + } +} + func (req *DownloadRequest) submitReadMarker(blobber *blockchain.StorageNode, readCount int64) (err error) { var retryCount = 3 for retryCount > 0 { diff --git a/zboxcore/sdk/listworker.go b/zboxcore/sdk/listworker.go index daeec0bcd..b7ae67cf3 100644 --- a/zboxcore/sdk/listworker.go +++ b/zboxcore/sdk/listworker.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io/ioutil" + "math/rand" "net/http" "strings" "sync" @@ -31,6 +32,7 @@ type ListRequest struct { ctx context.Context wg *sync.WaitGroup forRepair bool + listOnly bool Consensus } @@ -42,23 +44,28 @@ type listResponse struct { } type ListResult struct { - Name string `json:"name"` - Path string `json:"path,omitempty"` - Type string `json:"type"` - Size int64 `json:"size"` - Hash string `json:"hash,omitempty"` - FileMetaHash string `json:"file_meta_hash,omitempty"` - MimeType string `json:"mimetype,omitempty"` - NumBlocks int64 `json:"num_blocks"` - LookupHash string `json:"lookup_hash"` - EncryptionKey string `json:"encryption_key"` - ActualSize int64 `json:"actual_size"` - ActualNumBlocks int64 `json:"actual_num_blocks"` - CreatedAt common.Timestamp `json:"created_at"` - UpdatedAt common.Timestamp `json:"updated_at"` - Children []*ListResult `json:"list"` - Consensus `json:"-"` - deleteMask zboxutil.Uint128 `json:"-"` + Name string `json:"name"` + Path string `json:"path,omitempty"` + Type string `json:"type"` + Size int64 `json:"size"` + Hash string `json:"hash,omitempty"` + FileMetaHash string `json:"file_meta_hash,omitempty"` + MimeType string `json:"mimetype,omitempty"` + NumBlocks int64 `json:"num_blocks"` + LookupHash string `json:"lookup_hash"` + EncryptionKey string `json:"encryption_key"` + ActualSize int64 `json:"actual_size"` + ActualNumBlocks int64 `json:"actual_num_blocks"` + ThumbnailHash string `json:"thumbnail_hash"` + ThumbnailSize int64 `json:"thumbnail_size"` + ActualThumbnailHash string `json:"actual_thumbnail_hash"` + ActualThumbnailSize int64 `json:"actual_thumbnail_size"` + + CreatedAt common.Timestamp `json:"created_at"` + UpdatedAt common.Timestamp `json:"updated_at"` + Children []*ListResult `json:"list"` + Consensus `json:"-"` + deleteMask zboxutil.Uint128 `json:"-"` } func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, blobberIdx int, rspCh chan<- *listResponse) { @@ -91,7 +98,10 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, } //formWriter.Close() - httpreq, err := zboxutil.NewListRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.remotefilepath, req.remotefilepathhash, string(authTokenBytes)) + if req.forRepair { + req.listOnly = true + } + httpreq, err := zboxutil.NewListRequest(blobber.Baseurl, req.allocationID, req.allocationTx, req.remotefilepath, req.remotefilepathhash, string(authTokenBytes), req.listOnly) if err != nil { l.Logger.Error("List info request error: ", err.Error()) return @@ -110,7 +120,6 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, return errors.Wrap(err, "Error: Resp") } s.WriteString(string(resp_body)) - l.Logger.Debug("List result from Blobber:", string(resp_body)) if resp.StatusCode == http.StatusOK { listResult := &fileref.ListResult{} err = json.Unmarshal(resp_body, listResult) @@ -129,7 +138,7 @@ func (req *ListRequest) getListInfoFromBlobber(blobber *blockchain.StorageNode, }) } -func (req *ListRequest) getlistFromBlobbers() []*listResponse { +func (req *ListRequest) getlistFromBlobbers() ([]*listResponse, error) { numList := len(req.blobbers) req.wg = &sync.WaitGroup{} req.wg.Add(numList) @@ -142,24 +151,60 @@ func (req *ListRequest) getlistFromBlobbers() []*listResponse { for i := 0; i < numList; i++ { listInfos[i] = <-rspCh } - return listInfos + if req.listOnly { + return listInfos, nil + } + consensusMap := make(map[string][]*blockchain.StorageNode) + var consensusHash string + for i := 0; i < numList; i++ { + if listInfos[i].err != nil || listInfos[i].ref == nil { + continue + } + hash := listInfos[i].ref.FileMetaHash + consensusMap[hash] = append(consensusMap[hash], req.blobbers[listInfos[i].blobberIdx]) + if len(consensusMap[hash]) >= req.consensusThresh { + consensusHash = hash + } + } + var err error + req.listOnly = true + listLen := len(consensusMap[consensusHash]) + if listLen < req.consensusThresh { + return listInfos, listInfos[0].err + } + for i := 0; i < listLen; i++ { + var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) + num := rnd.Intn(listLen) + randomBlobber := consensusMap[consensusHash][num] + req.wg.Add(1) + go req.getListInfoFromBlobber(randomBlobber, 0, rspCh) + req.wg.Wait() + listInfos[0] = <-rspCh + if listInfos[0].err == nil { + return listInfos, nil + } + err = listInfos[0].err + } + return listInfos, err } func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { - lR := req.getlistFromBlobbers() + l.Logger.Debug("Getting list info from blobbers") + lR, err := req.getlistFromBlobbers() + if err != nil { + return nil, err + } result := &ListResult{ deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), } selected := make(map[string]*ListResult) childResultMap := make(map[string]*ListResult) - var err error - var errNum int - req.consensus = 0 + if !req.forRepair { + req.consensusThresh = 1 + } for i := 0; i < len(lR); i++ { ti := lR[i] if ti.err != nil { - err = ti.err - errNum++ result.deleteMask = result.deleteMask.And(zboxutil.NewUint128(1).Lsh(uint64(ti.blobberIdx)).Not()) continue } @@ -175,6 +220,11 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { result.LookupHash = ti.ref.LookupHash result.FileMetaHash = ti.ref.FileMetaHash result.ActualSize = ti.ref.ActualSize + result.ThumbnailHash = ti.ref.ThumbnailHash + result.ThumbnailSize = ti.ref.ThumbnailSize + result.ActualThumbnailHash = ti.ref.ActualThumbnailHash + result.ActualThumbnailSize = ti.ref.ActualThumbnailSize + if ti.ref.ActualSize > 0 { result.ActualNumBlocks = (ti.ref.ActualSize + CHUNK_SIZE - 1) / CHUNK_SIZE } @@ -197,10 +247,6 @@ func (req *ListRequest) GetListFromBlobbers() (*ListResult, error) { } } - if errNum >= req.consensusThresh && !req.forRepair { - return nil, err - } - return result, nil } @@ -235,6 +281,10 @@ func (lr *ListResult) populateChildren(children []fileref.RefEntity, childResult childResult.MimeType = (child.(*fileref.FileRef)).MimeType childResult.EncryptionKey = (child.(*fileref.FileRef)).EncryptedKey childResult.ActualSize = (child.(*fileref.FileRef)).ActualFileSize + childResult.ThumbnailHash = (child.(*fileref.FileRef)).ThumbnailHash + childResult.ThumbnailSize = (child.(*fileref.FileRef)).ThumbnailSize + childResult.ActualThumbnailHash = (child.(*fileref.FileRef)).ActualThumbnailHash + childResult.ActualThumbnailSize = (child.(*fileref.FileRef)).ActualThumbnailSize } else { childResult.ActualSize = (child.(*fileref.Ref)).ActualSize } diff --git a/zboxcore/sdk/listworker_test.go b/zboxcore/sdk/listworker_test.go index 4efbacefd..85890520c 100644 --- a/zboxcore/sdk/listworker_test.go +++ b/zboxcore/sdk/listworker_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "io/ioutil" "net/http" @@ -233,9 +234,11 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { jsonFR, err := json.Marshal(&fileref.ListResult{ AllocationRoot: mockAllocationRoot, Meta: map[string]interface{}{ - "type": mockType, + "type": mockType, + "file_meta_hash": "mock file meta hash", }, }) + fmt.Println("returned", string(jsonFR)) require.NoError(t, err) return ioutil.NopCloser(bytes.NewReader([]byte(jsonFR))) }(), @@ -291,6 +294,7 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { fullconsensus: tt.fullconsensus, RWMutex: &sync.RWMutex{}, }, + listOnly: true, } for i := 0; i < tt.numBlobbers; i++ { req.blobbers = append(req.blobbers, &blockchain.StorageNode{ @@ -299,9 +303,10 @@ func TestListRequest_GetListFromBlobbers(t *testing.T) { } got, _ := req.GetListFromBlobbers() expectedResult := &ListResult{ - Type: mockType, - Size: 0, - deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), + Type: mockType, + Size: 0, + deleteMask: zboxutil.NewUint128(1).Lsh(uint64(len(req.blobbers))).Sub64(1), + FileMetaHash: "mock file meta hash", } if !tt.wantErr { require.EqualValues(expectedResult, got) diff --git a/zboxcore/sdk/moveworker.go b/zboxcore/sdk/moveworker.go index 4487437b7..2380cd542 100644 --- a/zboxcore/sdk/moveworker.go +++ b/zboxcore/sdk/moveworker.go @@ -345,6 +345,7 @@ func (mo *MoveOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) [] moveChange.NumBlocks = 0 moveChange.Operation = constants.FileOperationMove moveChange.Size = 0 + moveChange.Uuid = uid changes[idx] = moveChange } return changes diff --git a/zboxcore/sdk/multi_operation_worker.go b/zboxcore/sdk/multi_operation_worker.go index f9ef35d61..b24f25992 100644 --- a/zboxcore/sdk/multi_operation_worker.go +++ b/zboxcore/sdk/multi_operation_worker.go @@ -11,6 +11,7 @@ import ( "time" "github.com/0chain/errors" + "github.com/remeh/sizedwaitgroup" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/util" @@ -28,6 +29,8 @@ const ( DefaultCreateConnectionTimeOut = 2 * time.Minute ) +var BatchSize = 6 + type Operationer interface { Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange @@ -88,8 +91,10 @@ func (mo *MultiOperation) createConnectionObj(blobberIdx int) (err error) { httpreq.Header.Add("Content-Type", formWriter.FormDataContentType()) ctx, cncl := context.WithTimeout(mo.ctx, DefaultCreateConnectionTimeOut) defer cncl() - resp, err = zboxutil.Client.Do(httpreq.WithContext(ctx)) - + err = zboxutil.HttpDo(ctx, cncl, httpreq, func(r *http.Response, err error) error { + resp = r + return err + }) if err != nil { logger.Logger.Error("Create Connection: ", err) return @@ -150,14 +155,14 @@ func (mo *MultiOperation) Process() error { ctx := mo.ctx ctxCncl := mo.ctxCncl defer ctxCncl() - + swg := sizedwaitgroup.New(BatchSize) errsSlice := make([]error, len(mo.operations)) mo.operationMask = zboxutil.NewUint128(0) for idx, op := range mo.operations { uid := util.GetNewUUID() - wg.Add(1) + swg.Add() go func(op Operationer, idx int) { - defer wg.Done() + defer swg.Done() // Check for other goroutines signal select { @@ -177,11 +182,10 @@ func (mo *MultiOperation) Process() error { mo.operationMask = mo.operationMask.Or(mask) mo.maskMU.Unlock() changes := op.buildChange(refs, uid) - mo.changes[idx] = changes }(op, idx) } - wg.Wait() + swg.Wait() // Check consensus if mo.operationMask.CountOnes() < mo.consensusThresh || ctx.Err() != nil { @@ -200,6 +204,7 @@ func (mo *MultiOperation) Process() error { // in row instead of column. Currently mo.change[0] contains allocationChange for operation 1 and so on. // But we want mo.changes[0] to have allocationChange for blobber 1 and mo.changes[1] to have allocationChange for // blobber 2 and so on. + start := time.Now() mo.changes = zboxutil.Transpose(mo.changes) writeMarkerMutex, err := CreateWriteMarkerMutex(client.GetClient(), mo.allocationObj) @@ -213,8 +218,8 @@ func (mo *MultiOperation) Process() error { if err != nil { return fmt.Errorf("Operation failed: %s", err.Error()) } - l.Logger.Info("WriteMarker locked") - + logger.Logger.Info("[writemarkerLocked]", time.Since(start).Milliseconds()) + start = time.Now() status, err := mo.allocationObj.CheckAllocStatus() if err != nil { logger.Logger.Error("Error checking allocation status", err) @@ -226,6 +231,9 @@ func (mo *MultiOperation) Process() error { writeMarkerMutex.Unlock(mo.ctx, mo.operationMask, mo.allocationObj.Blobbers, time.Minute, mo.connectionID) //nolint: errcheck statusBar := NewRepairBar(mo.allocationObj.ID) if statusBar == nil { + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } statusBar.wg.Add(1) @@ -239,17 +247,23 @@ func (mo *MultiOperation) Process() error { } else { l.Logger.Error("Repair failed") } + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } defer writeMarkerMutex.Unlock(mo.ctx, mo.operationMask, mo.allocationObj.Blobbers, time.Minute, mo.connectionID) //nolint: errcheck if status != Commit { + for _, op := range mo.operations { + op.Error(mo.allocationObj, 0, ErrRetryOperation) + } return ErrRetryOperation } - + logger.Logger.Info("[checkAllocStatus]", time.Since(start).Milliseconds()) mo.Consensus.Reset() activeBlobbers := mo.operationMask.CountOnes() commitReqs := make([]*CommitRequest, activeBlobbers) - + start = time.Now() wg.Add(activeBlobbers) var pos uint64 var counter = 0 @@ -273,6 +287,7 @@ func (mo *MultiOperation) Process() error { counter++ } wg.Wait() + logger.Logger.Info("[commitRequests]", time.Since(start).Milliseconds()) rollbackMask := zboxutil.NewUint128(0) for _, commitReq := range commitReqs { if commitReq.result != nil { @@ -293,16 +308,17 @@ func (mo *MultiOperation) Process() error { fmt.Sprintf("Commit failed. Required consensus %d, got %d", mo.Consensus.consensusThresh, mo.Consensus.consensus)) if mo.getConsensus() != 0 { + l.Logger.Info("Rolling back changes on minority blobbers") mo.allocationObj.RollbackWithMask(rollbackMask) } for _, op := range mo.operations { op.Error(mo.allocationObj, mo.getConsensus(), err) } return err - } - - for _, op := range mo.operations { - op.Completed(mo.allocationObj) + } else { + for _, op := range mo.operations { + op.Completed(mo.allocationObj) + } } return nil diff --git a/zboxcore/sdk/networkworker.go b/zboxcore/sdk/networkworker.go index efc809e5a..276fca806 100644 --- a/zboxcore/sdk/networkworker.go +++ b/zboxcore/sdk/networkworker.go @@ -3,13 +3,13 @@ package sdk import ( "context" "encoding/json" - "github.com/0chain/gosdk/core/transaction" "io/ioutil" "net/http" "reflect" "strconv" "time" + "github.com/0chain/gosdk/core/node" l "github.com/0chain/gosdk/zboxcore/logger" "go.uber.org/zap" @@ -54,22 +54,36 @@ func UpdateNetworkDetails() error { shouldUpdate := UpdateRequired(networkDetails) if shouldUpdate { - sdkInitialized = false - blockchain.SetMiners(networkDetails.Miners) - blockchain.SetSharders(networkDetails.Sharders) - transaction.InitCache(networkDetails.Sharders) - conf.InitChainNetwork(&conf.Network{ - Sharders: networkDetails.Sharders, - Miners: networkDetails.Miners, - }) - sdkInitialized = true + forceUpdateNetworkDetails(networkDetails) } return nil } +func InitNetworkDetails() error { + networkDetails, err := GetNetworkDetails() + if err != nil { + l.Logger.Error("Failed to update network details ", zap.Error(err)) + return err + } + forceUpdateNetworkDetails(networkDetails) + return nil +} + +func forceUpdateNetworkDetails(networkDetails *Network) { + sdkInitialized = false + blockchain.SetMiners(networkDetails.Miners) + blockchain.SetSharders(networkDetails.Sharders) + node.InitCache(blockchain.Sharders) + conf.InitChainNetwork(&conf.Network{ + Sharders: networkDetails.Sharders, + Miners: networkDetails.Miners, + }) + sdkInitialized = true +} + func UpdateRequired(networkDetails *Network) bool { miners := blockchain.GetMiners() - sharders := blockchain.GetSharders() + sharders := blockchain.GetAllSharders() if len(miners) == 0 || len(sharders) == 0 { return true } diff --git a/zboxcore/sdk/playlist.go b/zboxcore/sdk/playlist.go index 83788338d..52c464ff6 100644 --- a/zboxcore/sdk/playlist.go +++ b/zboxcore/sdk/playlist.go @@ -17,14 +17,15 @@ import ( ) type PlaylistFile struct { - LookupHash string `gorm:"column:lookup_hash" json:"lookup_hash"` - Name string `gorm:"column:name" json:"name"` - Path string `gorm:"column:path" json:"path"` - NumBlocks int64 `gorm:"column:num_of_blocks" json:"num_of_blocks"` - ParentPath string `gorm:"column:parent_path" json:"parent_path"` - Size int64 `gorm:"column:size;" json:"size"` - MimeType string `gorm:"column:mimetype" json:"mimetype"` - Type string `gorm:"column:type" json:"type"` + LookupHash string `gorm:"column:lookup_hash" json:"lookup_hash"` + Name string `gorm:"column:name" json:"name"` + Path string `gorm:"column:path" json:"path"` + NumBlocks int64 `gorm:"column:num_of_blocks" json:"num_of_blocks"` + ParentPath string `gorm:"column:parent_path" json:"parent_path"` + Size int64 `gorm:"column:size;" json:"size"` + ActualFileSize int64 + MimeType string `gorm:"column:mimetype" json:"mimetype"` + Type string `gorm:"column:type" json:"type"` } func GetPlaylist(ctx context.Context, alloc *Allocation, path, since string) ([]PlaylistFile, error) { diff --git a/zboxcore/sdk/repairworker.go b/zboxcore/sdk/repairworker.go index ea999d34c..57c279db2 100644 --- a/zboxcore/sdk/repairworker.go +++ b/zboxcore/sdk/repairworker.go @@ -7,6 +7,7 @@ import ( "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/fileref" l "github.com/0chain/gosdk/zboxcore/logger" + "github.com/0chain/gosdk/zboxcore/zboxutil" "go.uber.org/zap" ) @@ -88,6 +89,20 @@ func (r *RepairRequest) iterateDir(a *Allocation, dir *ListResult) { err := a.deleteFile(dir.Path, 0, consensus, dir.deleteMask) if err != nil { l.Logger.Error("repair_file_failed", zap.Error(err)) + if r.statusCB != nil { + r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + } + return + } + r.filesRepaired++ + } else if consensus < len(a.Blobbers) { + createMask := dir.deleteMask.Not().And(zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)) + err := a.createDir(dir.Path, 0, createMask.CountOnes(), createMask) + if err != nil { + l.Logger.Error("repair_file_failed", zap.Error(err)) + if r.statusCB != nil { + r.statusCB.Error(a.ID, dir.Path, OpRepair, err) + } return } r.filesRepaired++ diff --git a/zboxcore/sdk/rollback.go b/zboxcore/sdk/rollback.go index 1b50772a3..dd5151655 100644 --- a/zboxcore/sdk/rollback.go +++ b/zboxcore/sdk/rollback.go @@ -116,7 +116,11 @@ func (rb *RollbackBlobber) processRollback(ctx context.Context, tx string) error wm.AllocationRoot = rb.lpm.PrevWM.AllocationRoot wm.PreviousAllocationRoot = rb.lpm.PrevWM.AllocationRoot wm.FileMetaRoot = rb.lpm.PrevWM.FileMetaRoot + if wm.AllocationRoot == rb.lpm.LatestWM.AllocationRoot { + return nil + } } + err := wm.Sign() if err != nil { l.Logger.Error("Signing writemarker failed: ", err) @@ -265,7 +269,7 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { latestVersion = version } - if prevVersion == "" { + if prevVersion == "" && version != latestVersion { prevVersion = version } @@ -276,7 +280,6 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { versionMap[version] = append(versionMap[version], rb) } - l.Logger.Info("versionMap", zap.Any("versionMap", versionMap)) if len(versionMap) < 2 { return Commit, nil } @@ -290,13 +293,15 @@ func (a *Allocation) CheckAllocStatus() (AllocStatus, error) { if len(versionMap[latestVersion]) >= req || len(versionMap[prevVersion]) >= req || len(versionMap) > 2 { // TODO: Return Repair after refactoring the repair function return Repair, nil + } else { + l.Logger.Info("versionMapLen", zap.Int("versionMapLen", len(versionMap)), zap.Int("latestLen", len(versionMap[latestVersion])), zap.Int("prevLen", len(versionMap[prevVersion]))) } // rollback to previous version l.Logger.Info("Rolling back to previous version") fullConsensus := len(versionMap[latestVersion]) - (req - len(versionMap[prevVersion])) errCnt = 0 - + l.Logger.Info("fullConsensus", zap.Int32("fullConsensus", int32(fullConsensus)), zap.Int("latestLen", len(versionMap[latestVersion])), zap.Int("prevLen", len(versionMap[prevVersion]))) for _, rb := range versionMap[latestVersion] { wg.Add(1) diff --git a/zboxcore/sdk/sdk.go b/zboxcore/sdk/sdk.go index 9cfcad208..04601f146 100644 --- a/zboxcore/sdk/sdk.go +++ b/zboxcore/sdk/sdk.go @@ -8,16 +8,18 @@ import ( "io/ioutil" "math" "net/http" - "os" "strconv" + "strings" "time" "github.com/0chain/common/core/currency" "github.com/0chain/errors" "github.com/0chain/gosdk/core/conf" "github.com/0chain/gosdk/core/logger" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/sys" "go.uber.org/zap" + "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/transaction" @@ -54,6 +56,7 @@ type StatusCallback interface { var numBlockDownloads = 10 var sdkInitialized = false var networkWorkerTimerInHours = 1 +var shouldVerifyHash = true // GetVersion - returns version string func GetVersion() string { @@ -70,11 +73,16 @@ func SetLogLevel(lvl int) { // logFile - Log file // verbose - true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + var ioWriter = &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - l.Logger.SetLogFile(f, verbose) + + l.Logger.SetLogFile(ioWriter, verbose) l.Logger.Info("******* Storage SDK Version: ", version.VERSIONSTR, " *******") } @@ -92,19 +100,19 @@ func InitStorageSDK(walletJSON string, return err } - client.SetClientNonce(nonce) - if len(fee) > 0 { - client.SetTxnFee(fee[0]) - } - blockchain.SetChainID(chainID) blockchain.SetBlockWorker(blockWorker) - err = UpdateNetworkDetails() + err = InitNetworkDetails() if err != nil { return err } + client.SetClientNonce(nonce) + if len(fee) > 0 { + client.SetTxnFee(fee[0]) + } + go UpdateNetworkDetailsWorker(context.Background()) sdkInitialized = true return nil @@ -113,7 +121,7 @@ func InitStorageSDK(walletJSON string, func GetNetwork() *Network { return &Network{ Miners: blockchain.GetMiners(), - Sharders: blockchain.GetSharders(), + Sharders: blockchain.GetAllSharders(), } } @@ -147,7 +155,7 @@ func SetMinConfirmation(num int) { func SetNetwork(miners []string, sharders []string) { blockchain.SetMiners(miners) blockchain.SetSharders(sharders) - transaction.InitCache(sharders) + node.InitCache(blockchain.Sharders) } // @@ -216,7 +224,7 @@ func ReadPoolLock(tokens, fee uint64) (hash string, nonce int64, err error) { Name: transaction.STORAGESC_READ_POOL_LOCK, InputArgs: nil, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, tokens, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, tokens, fee) return } @@ -230,7 +238,7 @@ func ReadPoolUnlock(fee uint64) (hash string, nonce int64, err error) { Name: transaction.STORAGESC_READ_POOL_UNLOCK, InputArgs: nil, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, 0, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee) return } @@ -372,7 +380,7 @@ func StakePoolLock(providerType ProviderType, providerID string, value, fee uint Name: transaction.STORAGESC_STAKE_POOL_LOCK, InputArgs: &spr, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, value, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, value, fee) return } @@ -415,7 +423,7 @@ func StakePoolUnlock(providerType ProviderType, providerID string, fee uint64) ( } var out string - if _, out, nonce, _, err = smartContractTxnValueFee(sn, 0, fee); err != nil { + if _, out, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee); err != nil { return // an error } @@ -448,7 +456,7 @@ func WritePoolLock(allocID string, tokens, fee uint64) (hash string, nonce int64 Name: transaction.STORAGESC_WRITE_POOL_LOCK, InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, tokens, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, tokens, fee) return } @@ -469,7 +477,7 @@ func WritePoolUnlock(allocID string, fee uint64) (hash string, nonce int64, err Name: transaction.STORAGESC_WRITE_POOL_UNLOCK, InputArgs: &req, } - hash, _, nonce, _, err = smartContractTxnValueFee(sn, 0, fee) + hash, _, nonce, _, err = smartContractTxnValueFeeWithRetry(sn, 0, fee) return } @@ -885,11 +893,15 @@ func GetAllocationUpdates(allocation *Allocation) error { } func SetNumBlockDownloads(num int) { - if num > 0 && num <= 100 { + if num > 0 && num <= 500 { numBlockDownloads = num } } +func SetVerifyHash(verify bool) { + shouldVerifyHash = verify +} + func GetAllocations() ([]*Allocation, error) { return GetAllocationsForClient(client.GetClientID()) } @@ -989,6 +1001,10 @@ func CreateAllocationForOwner( return "", 0, nil, errors.New("invalid_lock", "int64 overflow on lock value") } + if datashards < 1 || parityshards < 1 { + return "", 0, nil, errors.New("allocation_validation_failed", "atleast 1 data and 1 parity shards are required") + } + allocationRequest, err := getNewAllocationBlobbers( datashards, parityshards, size, readPrice, writePrice, preferredBlobberIds) if err != nil { @@ -1016,6 +1032,7 @@ func GetAllocationBlobbers( datashards, parityshards int, size int64, readPrice, writePrice PriceRange, + force ...bool, ) ([]string, error) { var allocationRequest = map[string]interface{}{ "data_shards": datashards, @@ -1029,6 +1046,9 @@ func GetAllocationBlobbers( params := make(map[string]string) params["allocation_data"] = string(allocationData) + if len(force) > 0 && force[0] { + params["force"] = strconv.FormatBool(force[0]) + } allocBlobber, err := zboxutil.MakeSCRestAPICall(STORAGE_SCADDRESS, "/alloc_blobbers", params, nil) if err != nil { @@ -1179,7 +1199,6 @@ func UpdateAllocation( extend bool, allocationID string, lock uint64, - updateTerms bool, addBlobberId, removeBlobberId string, setThirdPartyExtendable bool, fileOptionsParams *FileOptionsParameters, ) (hash string, nonce int64, err error) { @@ -1203,7 +1222,6 @@ func UpdateAllocation( updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size updateAllocationRequest["extend"] = extend - updateAllocationRequest["update_terms"] = updateTerms updateAllocationRequest["add_blobber_id"] = addBlobberId updateAllocationRequest["remove_blobber_id"] = removeBlobberId updateAllocationRequest["set_third_party_extendable"] = setThirdPartyExtendable @@ -1217,24 +1235,6 @@ func UpdateAllocation( return } -func CreateFreeUpdateAllocation(marker, allocationId string, value uint64) (string, int64, error) { - if !sdkInitialized { - return "", 0, sdkNotInitialized - } - - var input = map[string]interface{}{ - "allocation_id": allocationId, - "marker": marker, - } - - var sn = transaction.SmartContractTxnData{ - Name: transaction.FREE_UPDATE_ALLOCATION, - InputArgs: input, - } - hash, _, n, _, err := smartContractTxnValue(sn, value) - return hash, n, err -} - func FinalizeAllocation(allocID string) (hash string, nonce int64, err error) { if !sdkInitialized { return "", 0, sdkNotInitialized @@ -1402,7 +1402,17 @@ func smartContractTxnValue(sn transaction.SmartContractTxnData, value uint64) ( hash, out string, nonce int64, txn *transaction.Transaction, err error) { // Fee is set during sdk initialization. - return smartContractTxnValueFee(sn, value, client.TxnFee()) + return smartContractTxnValueFeeWithRetry(sn, value, client.TxnFee()) +} + +func smartContractTxnValueFeeWithRetry(sn transaction.SmartContractTxnData, + value, fee uint64) (hash, out string, nonce int64, t *transaction.Transaction, err error) { + hash, out, nonce, t, err = smartContractTxnValueFee(sn, value, fee) + + if err != nil && strings.Contains(err.Error(), "invalid transaction nonce") { + return smartContractTxnValueFee(sn, value, fee) + } + return } func smartContractTxnValueFee(sn transaction.SmartContractTxnData, @@ -1435,7 +1445,7 @@ func smartContractTxnValueFee(sn transaction.SmartContractTxnData, } if txn.TransactionNonce == 0 { - txn.TransactionNonce = transaction.Cache.GetNextNonce(txn.ClientID) + txn.TransactionNonce = node.Cache.GetNextNonce(txn.ClientID) } if err = txn.ComputeHashAndSign(client.Sign); err != nil { @@ -1446,7 +1456,13 @@ func smartContractTxnValueFee(sn transaction.SmartContractTxnData, l.Logger.Info(msg) l.Logger.Info("estimated txn fee: ", txn.TransactionFee) - transaction.SendTransactionSync(txn, blockchain.GetMiners()) + err = transaction.SendTransactionSync(txn, blockchain.GetStableMiners()) + if err != nil { + l.Logger.Info("transaction submission failed", zap.Error(err)) + node.Cache.Evict(txn.ClientID) + blockchain.ResetStableMiners() + return + } var ( querySleepTime = time.Duration(blockchain.GetQuerySleepTime()) * time.Second @@ -1466,7 +1482,7 @@ func smartContractTxnValueFee(sn transaction.SmartContractTxnData, if err != nil { l.Logger.Error("Error verifying the transaction", err.Error(), txn.Hash) - transaction.Cache.Evict(txn.ClientID) + node.Cache.Evict(txn.ClientID) return } @@ -1553,32 +1569,14 @@ func CommitToFabric(metaTxnData, fabricConfigJSON string) (string, error) { func GetAllocationMinLock( datashards, parityshards int, size int64, - readPrice, writePrice PriceRange, + writePrice PriceRange, ) (int64, error) { baSize := int64(math.Ceil(float64(size) / float64(datashards))) totalSize := baSize * int64(datashards+parityshards) - config, err := GetStorageSCConfig() - if err != nil { - return 0, err - } - t := config.Fields["time_unit"] - timeunitStr, ok := t.(string) - if !ok { - return 0, fmt.Errorf("bad time_unit type") - } - timeunit, err := time.ParseDuration(timeunitStr) - if err != nil { - return 0, fmt.Errorf("bad time_unit format") - } - - expiry := common.Timestamp(time.Now().Add(timeunit).Unix()) - duration := expiry / common.Timestamp(timeunit.Milliseconds()) - if expiry%common.Timestamp(timeunit.Milliseconds()) != 0 { - duration++ - } sizeInGB := float64(totalSize) / GB - cost := float64(duration) * (sizeInGB*float64(writePrice.Max) + sizeInGB*float64(readPrice.Max)) + + cost := sizeInGB * float64(writePrice.Max) coin, err := currency.Float64ToCoin(cost) if err != nil { return 0, err @@ -1594,7 +1592,6 @@ func GetUpdateAllocationMinLock( allocationID string, size int64, extend bool, - updateTerms bool, addBlobberId, removeBlobberId string) (int64, error) { updateAllocationRequest := make(map[string]interface{}) @@ -1603,7 +1600,6 @@ func GetUpdateAllocationMinLock( updateAllocationRequest["id"] = allocationID updateAllocationRequest["size"] = size updateAllocationRequest["extend"] = extend - updateAllocationRequest["update_terms"] = updateTerms updateAllocationRequest["add_blobber_id"] = addBlobberId updateAllocationRequest["remove_blobber_id"] = removeBlobberId diff --git a/zboxcore/sdk/sync.go b/zboxcore/sdk/sync.go index 80907a7ab..6f38d47e6 100644 --- a/zboxcore/sdk/sync.go +++ b/zboxcore/sdk/sync.go @@ -17,7 +17,7 @@ import ( "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/fileref" l "github.com/0chain/gosdk/zboxcore/logger" - "golang.org/x/crypto/sha3" + "github.com/minio/sha256-simd" ) // For sync app @@ -106,7 +106,7 @@ func calcFileHash(filePath string) string { } defer fp.Close() - h := sha3.New256() + h := sha256.New() if _, err := io.Copy(h, fp); err != nil { log.Fatal(err) } diff --git a/zboxcore/sdk/upload_worker.go b/zboxcore/sdk/upload_worker.go index bb062e719..b14552361 100644 --- a/zboxcore/sdk/upload_worker.go +++ b/zboxcore/sdk/upload_worker.go @@ -1,6 +1,7 @@ package sdk import ( + "bytes" "io" thrown "github.com/0chain/errors" @@ -10,6 +11,7 @@ import ( l "github.com/0chain/gosdk/zboxcore/logger" "github.com/0chain/gosdk/zboxcore/zboxutil" "github.com/google/uuid" + "go.uber.org/zap" ) type UploadOperation struct { @@ -22,10 +24,9 @@ type UploadOperation struct { func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) { err := uo.chunkedUpload.process() if err != nil { - uo.chunkedUpload.ctxCncl() + l.Logger.Error("UploadOperation Failed", zap.String("name", uo.chunkedUpload.fileMeta.RemoteName), zap.Error(err)) return nil, uo.chunkedUpload.uploadMask, err } - var pos uint64 numList := len(uo.chunkedUpload.blobbers) uo.refs = make([]*fileref.FileRef, numList) @@ -34,8 +35,7 @@ func (uo *UploadOperation) Process(allocObj *Allocation, connectionID string) ([ uo.refs[pos] = uo.chunkedUpload.blobbers[pos].fileRef uo.refs[pos].ChunkSize = uo.chunkedUpload.chunkSize } - - l.Logger.Info("Completed the upload") + l.Logger.Info("UploadOperation Success", zap.String("name", uo.chunkedUpload.fileMeta.RemoteName)) return nil, uo.chunkedUpload.uploadMask, nil } @@ -119,7 +119,13 @@ func (uo *UploadOperation) Error(allocObj *Allocation, consensus int, err error) func NewUploadOperation(workdir string, allocObj *Allocation, connectionID string, fileMeta FileMeta, fileReader io.Reader, isUpdate, isWebstreaming bool, opts ...ChunkedUploadOption) (*UploadOperation, string, error) { uo := &UploadOperation{} - + if fileMeta.ActualSize == 0 { + byteReader := bytes.NewReader([]byte( + emptyFileDataHash)) + fileReader = byteReader + opts = append(opts, WithActualHash(emptyFileDataHash)) + fileMeta.ActualSize = int64(len(emptyFileDataHash)) + } cu, err := CreateChunkedUpload(workdir, allocObj, fileMeta, fileReader, isUpdate, false, isWebstreaming, connectionID, opts...) if err != nil { return nil, "", err @@ -128,6 +134,5 @@ func NewUploadOperation(workdir string, allocObj *Allocation, connectionID strin uo.chunkedUpload = cu uo.opCode = cu.opCode uo.isUpdate = isUpdate - return uo, cu.progress.ConnectionID, nil } diff --git a/zboxcore/sdk/writemarker_mutex.go b/zboxcore/sdk/writemarker_mutex.go index f761ab389..bbf4046be 100644 --- a/zboxcore/sdk/writemarker_mutex.go +++ b/zboxcore/sdk/writemarker_mutex.go @@ -290,6 +290,11 @@ func (wmMu *WriteMarkerMutex) lockBlobber( var resp *http.Response var shouldContinue bool for retry := 0; retry < 3; retry++ { + select { + case <-ctx.Done(): + return + default: + } err, shouldContinue = func() (err error, shouldContinue bool) { reqCtx, ctxCncl := context.WithTimeout(ctx, timeOut) defer ctxCncl() diff --git a/zboxcore/zboxutil/http.go b/zboxcore/zboxutil/http.go index b5f9e90bb..d4c2c7dd6 100644 --- a/zboxcore/zboxutil/http.go +++ b/zboxcore/zboxutil/http.go @@ -20,7 +20,6 @@ import ( "github.com/0chain/gosdk/core/conf" "github.com/0chain/gosdk/core/encryption" "github.com/0chain/gosdk/core/logger" - "github.com/0chain/gosdk/core/util" "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/0chain/gosdk/zboxcore/client" ) @@ -147,7 +146,16 @@ func init() { } func NewHTTPRequest(method string, url string, data []byte) (*http.Request, context.Context, context.CancelFunc, error) { - req, err := http.NewRequest(method, url, bytes.NewBuffer(data)) + var ( + req *http.Request + err error + ) + if len(data) > 0 { + req, err = http.NewRequest(method, url, bytes.NewBuffer(data)) + } else { + req, err = http.NewRequest(method, url, nil) + } + req.Header.Set("Content-Type", "application/json; charset=utf-8") req.Header.Set("Access-Control-Allow-Origin", "*") ctx, cncl := context.WithTimeout(context.Background(), time.Second*10) @@ -437,7 +445,7 @@ func NewFileStatsRequest(baseUrl string, allocationID string, allocationTx strin return req, nil } -func NewListRequest(baseUrl, allocationID string, allocationTx string, path, pathHash string, auth_token string) (*http.Request, error) { +func NewListRequest(baseUrl, allocationID string, allocationTx string, path, pathHash string, auth_token string, list bool) (*http.Request, error) { nurl, err := joinUrl(baseUrl, LIST_ENDPOINT, allocationTx) if err != nil { return nil, err @@ -446,6 +454,9 @@ func NewListRequest(baseUrl, allocationID string, allocationTx string, path, pat params.Add("path", path) params.Add("path_hash", pathHash) params.Add("auth_token", auth_token) + if list { + params.Add("list", "true") + } nurl.RawQuery = params.Encode() // Escape Query Parameters req, err := http.NewRequest(http.MethodGet, nurl.String(), nil) if err != nil { @@ -806,19 +817,16 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] return nil, err } - sharderConsensous := cfg.SharderConsensous - if sharderConsensous < 1 { - sharderConsensous = conf.DefaultSharderConsensous - } - if numSharders > sharderConsensous { - sharders = util.Shuffle(sharders)[:sharderConsensous] - } for _, sharder := range sharders { wg.Add(1) go func(sharder string) { defer wg.Done() urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath) - urlObj, _ := url.Parse(urlString) + urlObj, err := url.Parse(urlString) + if err != nil { + log.Error(err) + return + } q := urlObj.Query() for k, v := range params { q.Add(k, v) @@ -826,29 +834,37 @@ func MakeSCRestAPICall(scAddress string, relativePath string, params map[string] urlObj.RawQuery = q.Encode() client := &http.Client{Transport: DefaultTransport} response, err := client.Get(urlObj.String()) + if err != nil { + blockchain.Sharders.Fail(sharder) + return + } + + defer response.Body.Close() + entityBytes, _ := ioutil.ReadAll(response.Body) + mu.Lock() + if response.StatusCode > http.StatusBadRequest { + blockchain.Sharders.Fail(sharder) + } else { + blockchain.Sharders.Success(sharder) + } + responses[response.StatusCode]++ + if responses[response.StatusCode] > maxCount { + maxCount = responses[response.StatusCode] + } - if err == nil { - defer response.Body.Close() - entityBytes, _ := ioutil.ReadAll(response.Body) - mu.Lock() - responses[response.StatusCode]++ - if responses[response.StatusCode] > maxCount { - maxCount = responses[response.StatusCode] - } - - if isCurrentDominantStatus(response.StatusCode, responses, maxCount) { - dominant = response.StatusCode - retObj = entityBytes - } - - entityResult[sharder] = entityBytes - mu.Unlock() + if isCurrentDominantStatus(response.StatusCode, responses, maxCount) { + dominant = response.StatusCode + retObj = entityBytes } + + entityResult[sharder] = entityBytes + blockchain.Sharders.Success(sharder) + mu.Unlock() }(sharder) } wg.Wait() - rate := float32(maxCount*100) / float32(sharderConsensous) + rate := float32(maxCount*100) / float32(cfg.SharderConsensous) if rate < consensusThresh { err = errors.New("consensus_failed", "consensus failed on sharders") } diff --git a/zboxcore/zboxutil/transport.go b/zboxcore/zboxutil/transport.go index 829c2888a..09bc4337d 100644 --- a/zboxcore/zboxutil/transport.go +++ b/zboxcore/zboxutil/transport.go @@ -21,4 +21,5 @@ var DefaultTransport = &http.Transport{ TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, MaxIdleConnsPerHost: 100, + WriteBufferSize: 256 * 1024, } diff --git a/zboxcore/zboxutil/uint128_test.go b/zboxcore/zboxutil/uint128_test.go index 006a85222..d43294d22 100644 --- a/zboxcore/zboxutil/uint128_test.go +++ b/zboxcore/zboxutil/uint128_test.go @@ -1,10 +1,11 @@ package zboxutil import ( - "github.com/stretchr/testify/assert" "math" "reflect" "testing" + + "github.com/stretchr/testify/assert" ) func TestNewUint128(t *testing.T) { diff --git a/zboxcore/zboxutil/util.go b/zboxcore/zboxutil/util.go index 2efea4081..11701a02e 100644 --- a/zboxcore/zboxutil/util.go +++ b/zboxcore/zboxutil/util.go @@ -22,9 +22,9 @@ import ( "github.com/0chain/gosdk/zboxcore/blockchain" "github.com/h2non/filetype" "github.com/lithammer/shortuuid/v3" + "github.com/minio/sha256-simd" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/scrypt" - "golang.org/x/crypto/sha3" ) const EncryptedFolderName = "encrypted" @@ -205,7 +205,7 @@ func Decrypt(key, text []byte) ([]byte, error) { } func GetRefsHash(r []byte) string { - hash := sha3.New256() + hash := sha256.New() hash.Write(r) var buf []byte buf = hash.Sum(buf) diff --git a/zcnbridge/bridge.go b/zcnbridge/bridge.go index d46000e6a..9c9d9457b 100644 --- a/zcnbridge/bridge.go +++ b/zcnbridge/bridge.go @@ -3,21 +3,30 @@ package zcnbridge import ( "context" "encoding/hex" + "encoding/json" "fmt" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancortoken" + "io" "math/big" - "os" - "path" + "strconv" "time" + "github.com/0chain/common/core/currency" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancornetwork" + "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" + h "github.com/0chain/gosdk/zcnbridge/http" + hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" + "github.com/spf13/viper" + + "gopkg.in/natefinch/lumberjack.v2" + "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/zcnbridge/ethereum" "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" - binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" - "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" + "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" + "github.com/0chain/gosdk/zcnbridge/ethereum/nftconfig" "github.com/0chain/gosdk/zcnbridge/log" "github.com/0chain/gosdk/zcncore" - hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/spf13/viper" "github.com/0chain/gosdk/zcnbridge/transaction" "github.com/0chain/gosdk/zcnbridge/wallet" @@ -25,7 +34,6 @@ import ( eth "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" @@ -33,10 +41,6 @@ import ( "go.uber.org/zap" ) -type ( - Wei int64 -) - var Logger logger.Logger var defaultLogLevel = logger.DEBUG @@ -44,11 +48,15 @@ func init() { Logger.Init(defaultLogLevel, "zcnbridge-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return - } - Logger.SetLogFile(f, true) + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default + } + Logger.SetLogFile(ioWriter, true) } var ( @@ -61,51 +69,51 @@ var ( } ) -func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, nil, errors.Wrap(err, "failed to create etherClient") - } +func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client EthereumClient, gasLimitUnits uint64) *bind.TransactOpts { + var ( + signerAddress = common.HexToAddress(b.EthereumAddress) + password = b.Password + ) - // To (contract) - contractAddress := common.HexToAddress(b.AuthorizersAddress) + signer := accounts.Account{ + Address: signerAddress, + } - // Get ABI of the contract - abi, err := authorizers.AuthorizersMetaData.GetAbi() + signerAcc, err := b.keyStore.Find(signer) if err != nil { - return nil, nil, errors.Wrap(err, "failed to get ABI") + Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) } - // Pack the method argument - pack, err := abi.Pack(method, params...) + chainID, err := client.ChainID(context.Background()) if err != nil { - return nil, nil, errors.Wrap(err, "failed to pack arguments") + Logger.Fatal(errors.Wrap(err, "failed to get chain ID")) } - from := common.HexToAddress(b.EthereumAddress) - - // Gas limits in units - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ - To: &contractAddress, - From: from, - Data: pack, - }) + nonce, err := client.PendingNonceAt(context.Background(), signerAddress) if err != nil { - return nil, nil, errors.Wrap(err, "failed to estimate gas") + Logger.Fatal(err) } - // Update gas limits + 10% - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + gasPriceWei, err := client.SuggestGasPrice(context.Background()) + if err != nil { + Logger.Fatal(err) + } - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + err = b.keyStore.TimedUnlock(signer, password, time.Second*2) + if err != nil { + Logger.Fatal(err) + } - // Authorizers instance - authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, etherClient) + opts, err := bind.NewKeyStoreTransactorWithChainID(b.keyStore.GetEthereumKeyStore(), signerAcc, chainID) if err != nil { - return nil, nil, errors.Wrap(err, "failed to create authorizers instance") + Logger.Fatal(err) } - return authorizersInstance, transactOpts, nil + opts.Nonce = big.NewInt(int64(nonce)) + opts.GasLimit = gasLimitUnits // in units + opts.GasPrice = gasPriceWei // wei + + return opts } // AddEthereumAuthorizer Adds authorizer to Ethereum bridge. Only contract deployer can call this method @@ -184,86 +192,198 @@ func (b *BridgeClient) AddEthereumAuthorizers(configDir string) { } } -// IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer -// WZCN tokens on behalf of the token owner to the Burn TokenPool -// During the burn the script transfers amount from token owner to the bridge burn token pool -// Example: owner wants to burn some amount. -// The contract will transfer some amount from owner address to the pool. -// So the owner must call IncreaseAllowance of the WZCN token with 2 parameters: -// spender address which is the bridge contract and amount to be burned (transferred) -// ERC20 signature: "increaseAllowance(address,uint256)" -// -//nolint:funlen -func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei Wei) (*types.Transaction, error) { - if amountWei <= 0 { - return nil, errors.New("amount must be greater than zero") +func (b *BridgeClient) prepareNFTConfig(ctx context.Context, method string, params ...interface{}) (*nftconfig.NFTConfig, *bind.TransactOpts, error) { + // To (contract) + contractAddress := common.HexToAddress(b.NFTConfigAddress) + + // Get ABI of the contract + abi, err := nftconfig.NFTConfigMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get nftconfig ABI") } - etherClient, err := b.CreateEthClient() + // Pack the method argument + pack, err := abi.Pack(method, params...) if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") + return nil, nil, errors.Wrap(err, "failed to pack arguments") } - // 1. Data Parameter (spender) - spenderAddress := common.HexToAddress(b.BridgeAddress) + from := common.HexToAddress(b.EthereumAddress) - // 2. Data Parameter (amount) - amount := big.NewInt(int64(amountWei)) + // Gas limits in units + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas") + } - tokenAddress := common.HexToAddress(b.TokenAddress) - fromAddress := common.HexToAddress(b.EthereumAddress) + // Update gas limits + 10% + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - abi, err := erc20.ERC20MetaData.GetAbi() + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + // NFTConfig instance + cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) if err != nil { - return nil, errors.Wrap(err, "failed to get erc20 abi") + return nil, nil, errors.Wrap(err, "failed to create nftconfig instance") + } + + return cfg, transactOpts, nil +} + +// EncodePackInt do abi.encodedPack(string, int), it is used for setting plan id for royalty +func EncodePackInt64(key string, param int64) common.Hash { + return crypto.Keccak256Hash( + []byte(key), + common.LeftPadBytes(big.NewInt(param).Bytes(), 32), + ) +} + +// NFTConfigSetUint256 call setUint256 method of NFTConfig contract +func (b *BridgeClient) NFTConfigSetUint256(ctx context.Context, key string, value int64) (*types.Transaction, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + return b.NFTConfigSetUint256Raw(ctx, kkey, value) +} + +func (b *BridgeClient) NFTConfigSetUint256Raw(ctx context.Context, key common.Hash, value int64) (*types.Transaction, error) { + if value < 0 { + return nil, errors.New("value must be greater than zero") } - pack, err := abi.Pack("increaseAllowance", spenderAddress, amount) + v := big.NewInt(value) + Logger.Debug("NFT config setUint256", zap.String("key", key.String()), zap.Any("value", v)) + instance, transactOpts, err := b.prepareNFTConfig(ctx, "setUint256", key, v) if err != nil { - return nil, errors.Wrap(err, "failed to pack arguments") + return nil, errors.Wrap(err, "failed to prepare bridge") } - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ - To: &tokenAddress, - From: fromAddress, - Data: pack, - }) + tran, err := instance.SetUint256(transactOpts, key, v) if err != nil { - return nil, errors.Wrap(err, "failed to estimate gas limit") + msg := "failed to execute setUint256 transaction to ClientID = %s with key = %s, value = %v" + return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, v) } - gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + return tran, err +} + +func (b *BridgeClient) NFTConfigGetUint256(ctx context.Context, key string, keyParam ...int64) (string, int64, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + if len(keyParam) > 0 { + kkey = EncodePackInt64(key, keyParam[0]) + } + + contractAddress := common.HexToAddress(b.NFTConfigAddress) - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) + if err != nil { + return "", 0, errors.Wrap(err, "failed to create NFT config instance") + } - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, etherClient) + v, err := cfg.GetUint256(nil, kkey) if err != nil { - return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") + Logger.Error("NFTConfig GetUint256 FAILED", zap.Error(err)) + msg := "failed to execute getUint256 call, key = %s" + return "", 0, errors.Wrapf(err, msg, kkey) + } + return kkey.String(), v.Int64(), err +} + +func (b *BridgeClient) NFTConfigSetAddress(ctx context.Context, key, address string) (*types.Transaction, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + // return b.NFTConfigSetAddress(ctx, kkey, address) + + Logger.Debug("NFT config setAddress", + zap.String("key", kkey.String()), + zap.String("address", address)) + + addr := common.HexToAddress(address) + instance, transactOpts, err := b.prepareNFTConfig(ctx, "setAddress", kkey, addr) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bridge") + } + + tran, err := instance.SetAddress(transactOpts, kkey, addr) + if err != nil { + msg := "failed to execute setAddress transaction to ClientID = %s with key = %s, value = %v" + return nil, errors.Wrapf(err, msg, zcncore.GetClientWalletID(), key, address) + } + + return tran, err +} + +func (b *BridgeClient) NFTConfigGetAddress(ctx context.Context, key string) (string, string, error) { + kkey := crypto.Keccak256Hash([]byte(key)) + + contractAddress := common.HexToAddress(b.NFTConfigAddress) + + cfg, err := nftconfig.NewNFTConfig(contractAddress, b.ethereumClient) + if err != nil { + return "", "", errors.Wrap(err, "failed to create NFT config instance") + } + + v, err := cfg.GetAddress(nil, kkey) + if err != nil { + Logger.Error("NFTConfig GetAddress FAILED", zap.Error(err)) + msg := "failed to execute getAddress call, key = %s" + return "", "", errors.Wrapf(err, msg, kkey) + } + return kkey.String(), v.String(), err +} + +// IncreaseBurnerAllowance Increases allowance for bridge contract address to transfer +// ERC-20 tokens on behalf of the zcntoken owner to the Burn TokenPool +// During the burn the script transfers amount from zcntoken owner to the bridge burn zcntoken pool +// Example: owner wants to burn some amount. +// The contract will transfer some amount from owner address to the pool. +// So the owner must call IncreaseAllowance of the WZCN zcntoken with 2 parameters: +// spender address which is the bridge contract and amount to be burned (transferred) +// Token signature: "increaseApproval(address,uint256)" +// +//nolint:funlen +func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, allowanceAmount uint64) (*types.Transaction, error) { + if allowanceAmount <= 0 { + return nil, errors.New("amount must be greater than zero") + } + + // 1. Data Parameter (spender) + spenderAddress := common.HexToAddress(b.BridgeAddress) + + // 2. Data Parameter (amount) + amount := big.NewInt(int64(allowanceAmount)) + + tokenAddress := common.HexToAddress(b.TokenAddress) + + tokenInstance, transactOpts, err := b.prepareToken(ctx, "increaseApproval", tokenAddress, spenderAddress, amount) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare zcntoken") } Logger.Info( - "Starting IncreaseAllowance", - zap.String("token", tokenAddress.String()), + "Starting IncreaseApproval", + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), ) - tran, err := wzcnTokenInstance.IncreaseAllowance(transactOpts, spenderAddress, amount) + tran, err := tokenInstance.IncreaseApproval(transactOpts, spenderAddress, amount) if err != nil { Logger.Error( - "IncreaseAllowance FAILED", - zap.String("token", tokenAddress.String()), + "IncreaseApproval FAILED", + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), zap.Error(err)) - return nil, errors.Wrapf(err, "failed to send `IncreaseAllowance` transaction") + return nil, errors.Wrapf(err, "failed to send `IncreaseApproval` transaction") } Logger.Info( - "Posted IncreaseAllowance", + "Posted IncreaseApproval", zap.String("hash", tran.Hash().String()), - zap.String("token", tokenAddress.String()), + zap.String("zcntoken", tokenAddress.String()), zap.String("spender", spenderAddress.String()), zap.Int64("amount", amount.Int64()), ) @@ -271,22 +391,20 @@ func (b *BridgeClient) IncreaseBurnerAllowance(ctx context.Context, amountWei We return tran, nil } -// GetBalance returns balance of the current client -func (b *BridgeClient) GetBalance() (*big.Int, error) { - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") - } +// GetTokenBalance returns balance of the current client for the zcntoken address +func (b *BridgeClient) GetTokenBalance() (*big.Int, error) { + // 1. Token address parameter + of := common.HexToAddress(b.TokenAddress) - tokenAddress := common.HexToAddress(b.TokenAddress) - fromAddress := common.HexToAddress(b.EthereumAddress) + // 2. User's Ethereum wallet address parameter + from := common.HexToAddress(b.EthereumAddress) - wzcnTokenInstance, err := erc20.NewERC20(tokenAddress, etherClient) + tokenInstance, err := zcntoken.NewToken(of, b.ethereumClient) if err != nil { - return nil, errors.Wrap(err, "failed to initialize WZCN-ERC20 instance") + return nil, errors.Wrap(err, "failed to initialize zcntoken instance") } - wei, err := wzcnTokenInstance.BalanceOf(&bind.CallOpts{}, fromAddress) + wei, err := tokenInstance.BalanceOf(&bind.CallOpts{}, from) if err != nil { return nil, errors.Wrapf(err, "failed to call `BalanceOf` for %s", b.EthereumAddress) } @@ -295,7 +413,7 @@ func (b *BridgeClient) GetBalance() (*big.Int, error) { } // VerifyZCNTransaction verifies 0CHain transaction -func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (*transaction.Transaction, error) { +func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (transaction.Transaction, error) { return transaction.Verify(ctx, hash) } @@ -303,21 +421,20 @@ func (b *BridgeClient) VerifyZCNTransaction(ctx context.Context, hash string) (* func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { hash := crypto.Keccak256Hash([]byte(message)) - keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) signer := accounts.Account{ Address: common.HexToAddress(b.EthereumAddress), } - signerAcc, err := ks.Find(signer) + signerAcc, err := b.keyStore.Find(signer) if err != nil { Logger.Fatal(err) } - signature, err := ks.SignHash(signerAcc, hash.Bytes()) + signature, err := b.keyStore.SignHash(signerAcc, hash.Bytes()) if err != nil { return nil, err } + if err != nil { return []byte{}, errors.Wrap(err, "failed to sign the message") } @@ -328,15 +445,11 @@ func (b *BridgeClient) SignWithEthereumChain(message string) ([]byte, error) { // GetUserNonceMinted Returns nonce for a specified Ethereum address func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddress string) (*big.Int, error) { ethereumAddress := common.HexToAddress(rawEthereumAddress) - etherClient, err := b.CreateEthClient() - if err != nil { - return nil, errors.Wrap(err, "failed to create etherClient") - } contractAddress := common.HexToAddress(b.BridgeAddress) - var bridgeInstance *binding.Bridge - bridgeInstance, err = binding.NewBridge(contractAddress, etherClient) + var bridgeInstance *bridge.Bridge + bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, errors.Wrap(err, "failed to create bridge instance") } @@ -351,6 +464,28 @@ func (b *BridgeClient) GetUserNonceMinted(ctx context.Context, rawEthereumAddres return nonce, err } +// ResetUserNonceMinted Resets nonce for a specified Ethereum address +func (b *BridgeClient) ResetUserNonceMinted(ctx context.Context) (*types.Transaction, error) { + bridgeInstance, transactOpts, err := b.prepareBridge(ctx, b.EthereumAddress, "resetUserNonceMinted") + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bridge") + } + + tran, err := bridgeInstance.ResetUserNonceMinted(transactOpts) + if err != nil { + Logger.Error("ResetUserNonceMinted FAILED", zap.Error(err)) + msg := "failed to execute ResetUserNonceMinted call, ethereumAddress = %s" + return nil, errors.Wrapf(err, msg, b.EthereumAddress) + } + + Logger.Info( + "Posted ResetUserMintedNonce", + zap.String("ethereumWallet", b.EthereumAddress), + ) + + return tran, err +} + // MintWZCN Mint ZCN tokens on behalf of the 0ZCN client // payload: received from authorizers func (b *BridgeClient) MintWZCN(ctx context.Context, payload *ethereum.MintPayload) (*types.Transaction, error) { @@ -453,7 +588,7 @@ func (b *BridgeClient) BurnWZCN(ctx context.Context, amountTokens uint64) (*type // MintZCN mints ZCN tokens after receiving proof-of-burn of WZCN tokens func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) (string, error) { - trx, err := transaction.NewTransactionEntity(0) + trx, err := b.transactionProvider.NewTransactionEntity(0) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -484,12 +619,12 @@ func (b *BridgeClient) MintZCN(ctx context.Context, payload *zcnsc.MintPayload) } // BurnZCN burns ZCN tokens before conversion from ZCN to WZCN as a first step -func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (*transaction.Transaction, error) { +func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (transaction.Transaction, error) { payload := zcnsc.BurnPayload{ - EthereumAddress: b.EthereumAddress, // TODO: this should be receiver address not the bridge + EthereumAddress: b.EthereumAddress, } - trx, err := transaction.NewTransactionEntity(txnfee) + trx, err := b.transactionProvider.NewTransactionEntity(txnfee) if err != nil { log.Logger.Fatal("failed to create new transaction", zap.Error(err)) } @@ -530,17 +665,299 @@ func (b *BridgeClient) BurnZCN(ctx context.Context, amount, txnfee uint64) (*tra return trx, nil } -func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*binding.Bridge, *bind.TransactOpts, error) { - etherClient, err := b.CreateEthClient() +// FetchZCNToETHRate retrieves latest ZCN to ETH rate using Bancor API +func (b *BridgeClient) FetchZCNToSourceTokenRate(sourceTokenAddress string) (*big.Float, error) { + client = h.CleanClient() + + resp, err := client.Get(fmt.Sprintf("%s/tokens?dlt_id=%s", b.BancorAPIURL, b.TokenAddress)) + if err != nil { + return nil, err + } + + var body []byte + body, err = io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var bancorTokenDetails *BancorTokenDetails + err = json.Unmarshal(body, &bancorTokenDetails) + if err != nil { + return nil, err + } + + var zcnSourceTokenRateFloat float64 + + switch sourceTokenAddress { + case SourceTokenETHAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.ETH, 64) + case SourceTokenBNTAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.BNT, 64) + case SourceTokenUSDCAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.USDC, 64) + case SourceTokenEURCAddress: + zcnSourceTokenRateFloat, err = strconv.ParseFloat(bancorTokenDetails.Data.Rate.EURC, 64) + } + + if err != nil { + return nil, err + } + + return big.NewFloat(zcnSourceTokenRateFloat), nil +} + +// GetMaxBancorTargetAmount retrieves max amount of a given source token for Bancor swap +func (b *BridgeClient) GetMaxBancorTargetAmount(sourceTokenAddress string, amountSwap uint64) (*big.Int, error) { + amountSwapZCN, err := currency.Coin(amountSwap).ToZCN() + if err != nil { + return nil, errors.Wrap(err, "failed to convert current zcntoken balance to ZCN") + } + + var zcnEthRate *big.Float + zcnEthRate, err = b.FetchZCNToSourceTokenRate(sourceTokenAddress) + if err != nil { + return nil, errors.Wrap(err, "failed to retrieve ZCN to source zcntoken rate using Bancor API") + } + + zcnEthRateFloat, _ := zcnEthRate.Float64() + + return big.NewInt(int64(amountSwapZCN * zcnEthRateFloat * 1.5 * 1e18)), nil +} + +// ApproveSwap provides opportunity to approve swap operation for ERC20 tokens +func (b *BridgeClient) ApproveSwap(ctx context.Context, sourceTokenAddress string, maxAmountSwap *big.Int) (*types.Transaction, error) { + // 1. Token source token address parameter + tokenAddress := common.HexToAddress(sourceTokenAddress) + + // 2. Spender source token address parameter + spender := common.HexToAddress(BancorNetworkAddress) + + bancorTokenInstance, transactOpts, err := b.prepareBancorToken(ctx, "approve", tokenAddress, spender, maxAmountSwap) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bancor token") + } + + Logger.Info( + "Starting ApproveSwap", + zap.Int64("amount", maxAmountSwap.Int64()), + zap.String("spender", spender.String()), + ) + + tran, err := bancorTokenInstance.Approve(transactOpts, spender, maxAmountSwap) + if err != nil { + return nil, errors.Wrap(err, "failed to execute Approve transaction") + } + + return tran, nil +} + +// Swap provides opportunity to perform zcntoken swap operation. +func (b *BridgeClient) Swap(ctx context.Context, sourceTokenAddress string, amountSwap uint64, maxAmountSwap *big.Int, deadlinePeriod time.Time) (*types.Transaction, error) { + // 1. Swap amount parameter. + amount := big.NewInt(int64(amountSwap)) + + // 2. User's Ethereum wallet address. + beneficiary := common.HexToAddress(b.EthereumAddress) + + // 3. Trade deadline + deadline := big.NewInt(deadlinePeriod.Unix()) + + // 4. Value of the Ethereum transaction + var value *big.Int + + if sourceTokenAddress == SourceTokenETHAddress { + value = maxAmountSwap + } else { + value = big.NewInt(0) + } + + // 6. Source zcntoken address parameter + from := common.HexToAddress(sourceTokenAddress) + + // 7. Target zcntoken address parameter + to := common.HexToAddress(b.TokenAddress) + + bancorInstance, transactOpts, err := b.prepareBancor(ctx, value, "tradeByTargetAmount", from, to, amount, maxAmountSwap, deadline, beneficiary) + if err != nil { + return nil, errors.Wrap(err, "failed to prepare bancornetwork") + } + + Logger.Info( + "Starting Swap", + zap.Int64("amount", amount.Int64()), + zap.String("sourceToken", sourceTokenAddress), + ) + + tran, err := bancorInstance.TradeByTargetAmount(transactOpts, from, to, amount, maxAmountSwap, deadline, beneficiary) + if err != nil { + return nil, errors.Wrap(err, "failed to execute TradeByTargetAmount transaction") + } + + return tran, nil +} + +func (b *BridgeClient) prepareBancor(ctx context.Context, value *big.Int, method string, params ...interface{}) (*bancornetwork.Bancor, *bind.TransactOpts, error) { + // 1. Bancor network smart contract address + contractAddress := common.HexToAddress(BancorNetworkAddress) + + abi, err := bancornetwork.BancorMetaData.GetAbi() if err != nil { - return nil, nil, errors.Wrap(err, "failed to create etherClient") + return nil, nil, errors.Wrap(err, "failed to get bancornetwork abi") } + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + opts := eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + } + + if value.Int64() != 0 { + opts.Value = value + } + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, opts) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + if value.Int64() != 0 { + transactOpts.Value = value + } + + bancorInstance, err := bancornetwork.NewBancor(contractAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize bancornetwork instance") + } + + return bancorInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareBancorToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*bancortoken.Bancortoken, *bind.TransactOpts, error) { + abi, err := zcntoken.TokenMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get zcntoken abi") + } + + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &tokenAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + bancorTokenInstance, err := bancortoken.NewBancortoken(tokenAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize zcntoken instance") + } + + return bancorTokenInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareToken(ctx context.Context, method string, tokenAddress common.Address, params ...interface{}) (*zcntoken.Token, *bind.TransactOpts, error) { + abi, err := zcntoken.TokenMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get zcntoken abi") + } + + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &tokenAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas limit") + } + + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + tokenInstance, err := zcntoken.NewToken(tokenAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to initialize zcntoken instance") + } + + return tokenInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareAuthorizers(ctx context.Context, method string, params ...interface{}) (*authorizers.Authorizers, *bind.TransactOpts, error) { + // To (contract) + contractAddress := common.HexToAddress(b.AuthorizersAddress) + + // Get ABI of the contract + abi, err := authorizers.AuthorizersMetaData.GetAbi() + if err != nil { + return nil, nil, errors.Wrap(err, "failed to get ABI") + } + + // Pack the method argument + pack, err := abi.Pack(method, params...) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to pack arguments") + } + + from := common.HexToAddress(b.EthereumAddress) + + // Gas limits in units + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ + To: &contractAddress, + From: from, + Data: pack, + }) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to estimate gas") + } + + // Update gas limits + 10% + gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() + + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) + + // Authorizers instance + authorizersInstance, err := authorizers.NewAuthorizers(contractAddress, b.ethereumClient) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to create authorizers instance") + } + + return authorizersInstance, transactOpts, nil +} + +func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, method string, params ...interface{}) (*bridge.Bridge, *bind.TransactOpts, error) { // To (contract) contractAddress := common.HexToAddress(b.BridgeAddress) //Get ABI of the contract - abi, err := binding.BridgeMetaData.GetAbi() + abi, err := bridge.BridgeMetaData.GetAbi() if err != nil { return nil, nil, errors.Wrap(err, "failed to get ABI") } @@ -554,7 +971,7 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Gas limits in units fromAddress := common.HexToAddress(ethereumAddress) - gasLimitUnits, err := etherClient.EstimateGas(ctx, eth.CallMsg{ + gasLimitUnits, err := b.ethereumClient.EstimateGas(ctx, eth.CallMsg{ To: &contractAddress, From: fromAddress, Data: pack, @@ -566,10 +983,10 @@ func (b *BridgeClient) prepareBridge(ctx context.Context, ethereumAddress, metho //Update gas limits + 10% gasLimitUnits = addPercents(gasLimitUnits, 10).Uint64() - transactOpts := b.CreateSignedTransactionFromKeyStore(etherClient, gasLimitUnits) + transactOpts := b.CreateSignedTransactionFromKeyStore(b.ethereumClient, gasLimitUnits) // BridgeClient instance - bridgeInstance, err := binding.NewBridge(contractAddress, etherClient) + bridgeInstance, err := bridge.NewBridge(contractAddress, b.ethereumClient) if err != nil { return nil, nil, errors.Wrap(err, "failed to create bridge instance") } diff --git a/zcnbridge/bridge_helper.go b/zcnbridge/bridge_helper.go index ffa7c25be..729fec2e2 100644 --- a/zcnbridge/bridge_helper.go +++ b/zcnbridge/bridge_helper.go @@ -10,6 +10,18 @@ import ( "github.com/pkg/errors" ) +// BancorTokenDetails describes Bancor ZCN zcntoken pool details +type BancorTokenDetails struct { + Data struct { + Rate struct { + ETH string `json:"eth"` + BNT string `json:"bnt"` + USDC string `json:"usd"` + EURC string `json:"eur"` + } + } `json:"data"` +} + func GetTransactionStatus(hash string) (int, error) { _, err := zcncore.GetEthClient() if err != nil { diff --git a/zcnbridge/bridge_test.go b/zcnbridge/bridge_test.go index 7f9120aa3..d2b8d4f13 100644 --- a/zcnbridge/bridge_test.go +++ b/zcnbridge/bridge_test.go @@ -1,35 +1,137 @@ package zcnbridge import ( + "context" "encoding/json" + "fmt" + "github.com/0chain/gosdk/zcnbridge/ethereum/bancornetwork" + "github.com/0chain/gosdk/zcnbridge/ethereum/zcntoken" + "log" + "math/big" + "net/http" + "net/http/httptest" + "os" + "os/signal" + "path" "strconv" + "syscall" "testing" + "time" - "github.com/0chain/gosdk/core/common" + sdkcommon "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/zcnbridge/ethereum" + "github.com/0chain/gosdk/zcnbridge/ethereum/authorizers" + binding "github.com/0chain/gosdk/zcnbridge/ethereum/bridge" + bridgemocks "github.com/0chain/gosdk/zcnbridge/mocks" + "github.com/0chain/gosdk/zcnbridge/transaction" + transactionmocks "github.com/0chain/gosdk/zcnbridge/transaction/mocks" + "github.com/0chain/gosdk/zcnbridge/wallet" + "github.com/0chain/gosdk/zcnbridge/zcnsc" + "github.com/0chain/gosdk/zcncore" + eth "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/common" + "github.com/spf13/viper" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) -type AuthorizerConfigTarget struct { - Fee common.Balance `json:"fee"` +const ( + ethereumAddress = "0xD8c9156e782C68EE671C09b6b92de76C97948432" + password = "02289b9" + + authorizerDelegatedAddress = "0xa149B58b7e1390D152383BB03dBc79B390F648e2" + + bridgeAddress = "0x7bbbEa24ac1751317D7669f05558632c4A9113D7" + tokenAddress = "0xb9EF770B6A5e12E45983C5D80545258aA38F3B78" + authorizersAddress = "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61" + + sourceAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" + + zcnTxnID = "b26abeb31fcee5d2e75b26717722938a06fa5ce4a5b5e68ddad68357432caace" + amount = 1 + txnFee = 1 + nonce = 1 + + ethereumTxnID = "0x3b59971c2aa294739cd73912f0c5a7996aafb796238cf44408b0eb4af0fbac82" + + clientId = "d6e9b3222434faa043c683d1a939d6a0fa2818c4d56e794974d64a32005330d3" +) + +var ( + testKeyStoreLocation = path.Join(".", EthereumWalletStorageDir) +) + +var ( + ethereumSignatures = []*ethereum.AuthorizerSignature{ + { + ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", + Signature: []byte("0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61"), + }, + } + + zcnScSignatures = []*zcnsc.AuthorizerSignature{ + { + ID: "0x2ec8F26ccC678c9faF0Df20208aEE3AF776160CD", + Signature: "0xEAe8229c0E457efBA1A1769e7F8c20110fF68E61", + }, + } +) + +type ethereumClientMock struct { + mock.TestingT +} + +func (ecm *ethereumClientMock) Cleanup(callback func()) { + callback() +} + +type transactionMock struct { + mock.TestingT +} + +func (tem *transactionMock) Cleanup(callback func()) { + callback() +} + +type transactionProviderMock struct { + mock.TestingT +} + +func (tem *transactionProviderMock) Cleanup(callback func()) { + callback() +} + +type keyStoreMock struct { + mock.TestingT +} + +func (ksm *keyStoreMock) Cleanup(callback func()) { + callback() +} + +type authorizerConfigTarget struct { + Fee sdkcommon.Balance `json:"fee"` } -type AuthorizerNodeTarget struct { +type authorizerNodeTarget struct { ID string `json:"id"` PublicKey string `json:"public_key"` URL string `json:"url"` - Config *AuthorizerConfigTarget `json:"config"` + Config *authorizerConfigTarget `json:"config"` } -type AuthorizerConfigSource struct { +type authorizerConfigSource struct { Fee string `json:"fee"` } -type AuthorizerNodeSource struct { +type authorizerNodeSource struct { ID string `json:"id"` - Config *AuthorizerConfigSource `json:"config"` + Config *authorizerConfigSource `json:"config"` } -func (an *AuthorizerNodeTarget) Decode(input []byte) error { +func (an *authorizerNodeTarget) decode(input []byte) error { var objMap map[string]*json.RawMessage err := json.Unmarshal(input, &objMap) if err != nil { @@ -68,8 +170,8 @@ func (an *AuthorizerNodeTarget) Decode(input []byte) error { rawCfg, ok := objMap["config"] if ok { - var cfg = &AuthorizerConfigTarget{} - err = cfg.Decode(*rawCfg) + var cfg = &authorizerConfigTarget{} + err = cfg.decode(*rawCfg) if err != nil { return err } @@ -80,7 +182,7 @@ func (an *AuthorizerNodeTarget) Decode(input []byte) error { return nil } -func (c *AuthorizerConfigTarget) Decode(input []byte) (err error) { +func (c *authorizerConfigTarget) decode(input []byte) (err error) { const ( Fee = "fee" ) @@ -104,29 +206,418 @@ func (c *AuthorizerConfigTarget) Decode(input []byte) (err error) { return err } - c.Fee = common.Balance(balance) + c.Fee = sdkcommon.Balance(balance) } return nil } -func Test_UpdateAuthorizerConfigTest(t *testing.T) { - source := &AuthorizerNodeSource{ - ID: "12345678", - Config: &AuthorizerConfigSource{ - Fee: "999", - }, +func getEthereumClient(t mock.TestingT) *bridgemocks.EthereumClient { + return bridgemocks.NewEthereumClient(ðereumClientMock{t}) +} + +func getBridgeClient(bancorAPIURL string, ethereumClient EthereumClient, transactionProvider transaction.TransactionProvider, keyStore KeyStore) *BridgeClient { + cfg := viper.New() + + tempConfigFile, err := os.CreateTemp(".", "config.yaml") + if err != nil { + log.Fatalln(err) } - target := &AuthorizerNodeTarget{} - bytes, err := json.Marshal(source) - require.NoError(t, err) + defer func(name string) { + err := os.Remove(name) + if err != nil { + log.Fatalln(err) + } + }(tempConfigFile.Name()) + + cfg.SetConfigFile(tempConfigFile.Name()) + + cfg.SetDefault("bridge.bridge_address", bridgeAddress) + cfg.SetDefault("bridge.token_address", tokenAddress) + cfg.SetDefault("bridge.authorizers_address", authorizersAddress) + cfg.SetDefault("bridge.ethereum_address", ethereumAddress) + cfg.SetDefault("bridge.password", password) + cfg.SetDefault("bridge.gas_limit", 0) + cfg.SetDefault("bridge.consensus_threshold", 0) + + return NewBridgeClient( + cfg.GetString("bridge.bridge_address"), + cfg.GetString("bridge.token_address"), + cfg.GetString("bridge.authorizers_address"), + cfg.GetString("bridge.ethereum_address"), + cfg.GetString("bridge.password"), + cfg.GetUint64("bridge.gas_limit"), + cfg.GetFloat64("bridge.consensus_threshold"), + bancorAPIURL, + ethereumClient, + transactionProvider, + keyStore, + ) +} + +func prepareEthereumClientGeneralMockCalls(ethereumClient *mock.Mock) { + ethereumClient.On("EstimateGas", mock.Anything, mock.Anything).Return(uint64(400000), nil) + ethereumClient.On("ChainID", mock.Anything).Return(big.NewInt(400000), nil) + ethereumClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(nonce), nil) + ethereumClient.On("SuggestGasPrice", mock.Anything).Return(big.NewInt(400000), nil) + ethereumClient.On("SendTransaction", mock.Anything, mock.Anything).Return(nil) +} + +func getTransaction(t mock.TestingT) *transactionmocks.Transaction { + return transactionmocks.NewTransaction(&transactionMock{t}) +} + +func prepareTransactionGeneralMockCalls(transaction *mock.Mock) { + transaction.On("ExecuteSmartContract", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(zcnTxnID, nil) + transaction.On("Verify", mock.Anything).Return(nil) +} + +func getTransactionProvider(t mock.TestingT) *transactionmocks.TransactionProvider { + return transactionmocks.NewTransactionProvider(&transactionProviderMock{t}) +} + +func prepareTransactionProviderGeneralMockCalls(transactionProvider *mock.Mock, transaction *transactionmocks.Transaction) { + transactionProvider.On("NewTransactionEntity", mock.Anything).Return(transaction, nil) +} + +func getKeyStore(t mock.TestingT) *bridgemocks.KeyStore { + return bridgemocks.NewKeyStore(&keyStoreMock{t}) +} + +func prepareKeyStoreGeneralMockCalls(keyStore *bridgemocks.KeyStore) { + ks := keystore.NewKeyStore(testKeyStoreLocation, keystore.StandardScryptN, keystore.StandardScryptP) + + keyStore.On("Find", mock.Anything).Return(accounts.Account{Address: common.HexToAddress(ethereumAddress)}, nil) + keyStore.On("TimedUnlock", mock.Anything, mock.Anything, mock.Anything).Run( + func(args mock.Arguments) { + err := ks.TimedUnlock(args.Get(0).(accounts.Account), args.Get(1).(string), args.Get(2).(time.Duration)) + if err != nil { + log.Fatalln(err) + } + }, + ).Return(nil) + keyStore.On("SignHash", mock.Anything, mock.Anything).Return([]byte(ethereumAddress), nil) + + keyStore.On("GetEthereumKeyStore").Return(ks) +} + +func prepareBancorMockServer() string { + ts := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := fmt.Fprintln(w, `{"data":{"dltId":"0xb9EF770B6A5e12E45983C5D80545258aA38F3B78","symbol":"ZCN","decimals":10,"rate":{"bnt":"0.175290404525335519","usd":"0.100266","eur":"0.094499","eth":"1"},"rate24hAgo":{"bnt":"0.175290404525335519","usd":"0.100266","eur":"0.094499","eth":"0.000064086171894462"}},"timestamp":{"ethereum":{"block":18333798,"timestamp":1697107211}}}`) + if err != nil { + log.Fatalln(err) + } + })) + + sigs := make(chan os.Signal, 1) + + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + + go func() { + load := time.NewTicker(time.Millisecond * 500) + + for range load.C { + select { + case <-sigs: + load.Stop() + + ts.Close() + + close(sigs) + default: + } + } + }() + + return ts.URL +} + +func Test_ZCNBridge(t *testing.T) { + ethereumClient := getEthereumClient(t) + prepareEthereumClientGeneralMockCalls(ðereumClient.Mock) + + tx := getTransaction(t) + prepareTransactionGeneralMockCalls(&tx.Mock) + + transactionProvider := getTransactionProvider(t) + prepareTransactionProviderGeneralMockCalls(&transactionProvider.Mock, tx) + + keyStore := getKeyStore(t) + prepareKeyStoreGeneralMockCalls(keyStore) + + bancorMockServerURL := prepareBancorMockServer() + + bridgeClient := getBridgeClient(bancorMockServerURL, ethereumClient, transactionProvider, keyStore) + + t.Run("should update authorizer config.", func(t *testing.T) { + source := &authorizerNodeSource{ + ID: "12345678", + Config: &authorizerConfigSource{ + Fee: "999", + }, + } + target := &authorizerNodeTarget{} + + bytes, err := json.Marshal(source) + require.NoError(t, err) + + err = target.decode(bytes) + require.NoError(t, err) + + require.Equal(t, "", target.URL) + require.Equal(t, "", target.PublicKey) + require.Equal(t, "12345678", target.ID) + require.Equal(t, sdkcommon.Balance(999), target.Config.Fee) + }) + + t.Run("should check configuration formating in MintWZCN", func(t *testing.T) { + _, err := bridgeClient.MintWZCN(context.Background(), ðereum.MintPayload{ + ZCNTxnID: zcnTxnID, + Amount: amount, + To: ethereumAddress, + Nonce: nonce, + Signatures: ethereumSignatures, + }) + require.NoError(t, err) + + var sigs [][]byte + for _, signature := range ethereumSignatures { + sigs = append(sigs, signature.Signature) + } + + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := binding.BridgeMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("mint", common.HexToAddress(ethereumAddress), + big.NewInt(amount), + DefaultClientIDEncoder(zcnTxnID), + big.NewInt(nonce), + sigs) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration formating in BurnWZCN", func(t *testing.T) { + _, err := bridgeClient.BurnWZCN(context.Background(), amount) + require.NoError(t, err) + + to := common.HexToAddress(bridgeAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := binding.BridgeMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("burn", big.NewInt(amount), DefaultClientIDEncoder(zcncore.GetClientWalletID())) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration used by MintZCN", func(t *testing.T) { + payload := &zcnsc.MintPayload{ + EthereumTxnID: ethereumTxnID, + Amount: sdkcommon.Balance(amount), + Nonce: nonce, + Signatures: zcnScSignatures, + ReceivingClientID: clientId, + } + + _, err := bridgeClient.MintZCN(context.Background(), payload) + require.NoError(t, err) + + require.True(t, tx.AssertCalled( + t, + "ExecuteSmartContract", + context.Background(), + wallet.ZCNSCSmartContractAddress, + wallet.MintFunc, + payload, + uint64(0), + )) + }) + + t.Run("should check configuration used by BurnZCN", func(t *testing.T) { + _, err := bridgeClient.BurnZCN(context.Background(), amount, txnFee) + require.NoError(t, err) + + require.True(t, tx.AssertCalled( + t, + "ExecuteSmartContract", + context.Background(), + wallet.ZCNSCSmartContractAddress, + wallet.BurnFunc, + zcnsc.BurnPayload{ + EthereumAddress: ethereumAddress, + }, + uint64(amount), + )) + }) + + t.Run("should check configuration used by AddEthereumAuthorizer", func(t *testing.T) { + _, err := bridgeClient.AddEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + to := common.HexToAddress(authorizersAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := authorizers.AuthorizersMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("addAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration used by RemoveAuthorizer", func(t *testing.T) { + _, err := bridgeClient.RemoveEthereumAuthorizer(context.Background(), common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + to := common.HexToAddress(authorizersAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := authorizers.AuthorizersMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("removeAuthorizers", common.HexToAddress(authorizerDelegatedAddress)) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration used by IncreaseBurnerAllowance", func(t *testing.T) { + _, err := bridgeClient.IncreaseBurnerAllowance(context.Background(), amount) + require.NoError(t, err) + + spenderAddress := common.HexToAddress(bridgeAddress) + + to := common.HexToAddress(tokenAddress) + fromAddress := common.HexToAddress(ethereumAddress) + + abi, err := zcntoken.TokenMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("increaseApproval", spenderAddress, big.NewInt(amount)) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &to, + From: fromAddress, + Data: pack, + }, + )) + }) + + t.Run("should check configuration used by Swap", func(t *testing.T) { + // 1. Predefined deadline period + deadlinePeriod := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) + + _, err := bridgeClient.Swap(context.Background(), SourceTokenETHAddress, amount, big.NewInt(amount), deadlinePeriod) + require.NoError(t, err) + + // 2. Trade deadline + deadline := big.NewInt(deadlinePeriod.Unix()) + + // 3. Swap amount parameter + swapAmount := big.NewInt(amount) + + // 4. User's Ethereum wallet address. + beneficiary := common.HexToAddress(ethereumAddress) + + // 5. Source zcntoken address parameter + from := common.HexToAddress(sourceAddress) + + // 6. Target zcntoken address parameter + to := common.HexToAddress(tokenAddress) + + // 7. Max trade zcntoken amount + maxAmount := big.NewInt(amount) + + // 8. Bancor network smart contract address + contractAddress := common.HexToAddress(BancorNetworkAddress) + + abi, err := bancornetwork.BancorMetaData.GetAbi() + require.NoError(t, err) + + pack, err := abi.Pack("tradeByTargetAmount", from, to, swapAmount, maxAmount, deadline, beneficiary) + require.NoError(t, err) + + require.True(t, ethereumClient.AssertCalled( + t, + "EstimateGas", + context.Background(), + eth.CallMsg{ + To: &contractAddress, + From: beneficiary, + Data: pack, + Value: maxAmount, + }, + )) + }) + + t.Run("should check configuration used by CreateSignedTransactionFromKeyStore", func(t *testing.T) { + bridgeClient.CreateSignedTransactionFromKeyStore(ethereumClient, 400000) - err = target.Decode(bytes) - require.NoError(t, err) + require.True(t, ethereumClient.AssertCalled( + t, + "PendingNonceAt", + context.Background(), + common.HexToAddress(ethereumAddress))) - require.Equal(t, "", target.URL) - require.Equal(t, "", target.PublicKey) - require.Equal(t, "12345678", target.ID) - require.Equal(t, common.Balance(999), target.Config.Fee) + require.True(t, keyStore.AssertCalled( + t, + "TimedUnlock", + accounts.Account{ + Address: common.HexToAddress(ethereumAddress), + }, + password, + time.Second*2, + )) + }) } diff --git a/zcnbridge/config.go b/zcnbridge/config.go index 7d5e06e72..d871eb653 100644 --- a/zcnbridge/config.go +++ b/zcnbridge/config.go @@ -1,10 +1,15 @@ package zcnbridge import ( + "context" "fmt" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "math/big" "path" "github.com/0chain/gosdk/zcnbridge/log" + "github.com/0chain/gosdk/zcnbridge/transaction" + "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" ) @@ -15,6 +20,16 @@ const ( EthereumWalletStorageDir = "wallets" ) +const ( + BancorNetworkAddress = "0xeEF417e1D5CC832e619ae18D2F140De2999dD4fB" + SourceTokenETHAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" + SourceTokenUSDCAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + SourceTokenEURCAddress = "0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c" + SourceTokenBNTAddress = "0x1f573d6fb3f13d689ff844b4ce37794d79a7ff1c" +) + +const BancorAPIURL = "https://api-v3.bancor.network" + type BridgeSDKConfig struct { LogLevel *string LogPath *string @@ -23,47 +38,59 @@ type BridgeSDKConfig struct { Development *bool } +// EthereumClient describes Ethereum JSON-RPC client generealized interface +type EthereumClient interface { + bind.ContractBackend + + ChainID(ctx context.Context) (*big.Int, error) +} + type BridgeClient struct { + keyStore KeyStore + transactionProvider transaction.TransactionProvider + ethereumClient EthereumClient + BridgeAddress, TokenAddress, AuthorizersAddress, + NFTConfigAddress, EthereumAddress, - Password, - EthereumNodeURL, - Homedir string + Password string + + BancorAPIURL string ConsensusThreshold float64 GasLimit uint64 } -func CreateBridgeClient(cfg *viper.Viper) *BridgeClient { - - homedir := path.Dir(cfg.ConfigFileUsed()) - if homedir == "" { - log.Logger.Fatal("homedir is required") - } - +// NewBridgeClient creates BridgeClient with the given parameters. +func NewBridgeClient( + bridgeAddress, + tokenAddress, + authorizersAddress, + ethereumAddress, + password string, + gasLimit uint64, + consensusThreshold float64, + bancorAPIURL string, + ethereumClient EthereumClient, + transactionProvider transaction.TransactionProvider, + keyStore KeyStore) *BridgeClient { return &BridgeClient{ - BridgeAddress: cfg.GetString("bridge.bridge_address"), - TokenAddress: cfg.GetString("bridge.token_address"), - AuthorizersAddress: cfg.GetString("bridge.authorizers_address"), - EthereumAddress: cfg.GetString("bridge.ethereum_address"), - Password: cfg.GetString("bridge.password"), - EthereumNodeURL: cfg.GetString("ethereum_node_url"), - GasLimit: cfg.GetUint64("bridge.gas_limit"), - ConsensusThreshold: cfg.GetFloat64("bridge.consensus_threshold"), - Homedir: homedir, + BridgeAddress: bridgeAddress, + TokenAddress: tokenAddress, + AuthorizersAddress: authorizersAddress, + EthereumAddress: ethereumAddress, + Password: password, + GasLimit: gasLimit, + ConsensusThreshold: consensusThreshold, + BancorAPIURL: bancorAPIURL, + ethereumClient: ethereumClient, + transactionProvider: transactionProvider, + keyStore: keyStore, } } -// SetupBridgeClientSDK Use this from standalone application -// 0Chain SDK initialization is required -func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { - log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) - bridgeClient := CreateBridgeClient(initChainConfig(cfg)) - return bridgeClient -} - func initChainConfig(sdkConfig *BridgeSDKConfig) *viper.Viper { cfg := readConfig(sdkConfig, func() string { return *sdkConfig.ConfigChainFile @@ -85,3 +112,39 @@ func readConfig(sdkConfig *BridgeSDKConfig, getConfigName func() string) *viper. } return cfg } + +// SetupBridgeClientSDK initializes new bridge client. +// Meant to be used from standalone application with 0chain SDK initialized. +func SetupBridgeClientSDK(cfg *BridgeSDKConfig) *BridgeClient { + log.InitLogging(*cfg.Development, *cfg.LogPath, *cfg.LogLevel) + + chainCfg := initChainConfig(cfg) + + ethereumClient, err := ethclient.Dial(chainCfg.GetString("ethereum_node_url")) + if err != nil { + Logger.Error(err) + } + + transactionProvider := transaction.NewTransactionProvider() + + homedir := path.Dir(chainCfg.ConfigFileUsed()) + if homedir == "" { + log.Logger.Fatal("err happened during home directory retrieval") + } + + keyStore := NewKeyStore(path.Join(homedir, EthereumWalletStorageDir)) + + return NewBridgeClient( + chainCfg.GetString("bridge.bridge_address"), + chainCfg.GetString("bridge.token_address"), + chainCfg.GetString("bridge.authorizers_address"), + chainCfg.GetString("bridge.ethereum_address"), + chainCfg.GetString("bridge.password"), + chainCfg.GetUint64("bridge.gas_limit"), + chainCfg.GetFloat64("bridge.consensus_threshold"), + BancorAPIURL, + ethereumClient, + transactionProvider, + keyStore, + ) +} diff --git a/zcnbridge/ethereum/bancornetwork/bancornetwork.go b/zcnbridge/ethereum/bancornetwork/bancornetwork.go new file mode 100755 index 000000000..6c432375d --- /dev/null +++ b/zcnbridge/ethereum/bancornetwork/bancornetwork.go @@ -0,0 +1,3757 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package bancornetwork + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// BancorMetaData contains all meta data concerning the Bancor contract. +var BancorMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"contractITokenGovernance\",\"name\":\"initBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractITokenGovernance\",\"name\":\"initVBNTGovernance\",\"type\":\"address\"},{\"internalType\":\"contractINetworkSettings\",\"name\":\"initNetworkSettings\",\"type\":\"address\"},{\"internalType\":\"contractIMasterVault\",\"name\":\"initMasterVault\",\"type\":\"address\"},{\"internalType\":\"contractIExternalProtectionVault\",\"name\":\"initExternalProtectionVault\",\"type\":\"address\"},{\"internalType\":\"contractIPoolToken\",\"name\":\"initBNTPoolToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"bancorArbitrage\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"carbonPOL\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyInitialized\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DeadlineExpired\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DepositingDisabled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DoesNotExist\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientFlashLoanReturn\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidFee\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidPool\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidToken\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NativeTokenAmountMismatch\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotEmpty\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelisted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotWhitelistedForPOL\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"Overflow\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"PoolNotInSurplus\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroValue\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeAmount\",\"type\":\"uint256\"}],\"name\":\"FlashLoanCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"FundsMigrated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"NetworkFeesWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"oldRewardsPPM\",\"type\":\"uint32\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"POLRewardsPPMUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"polTokenAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"userReward\",\"type\":\"uint256\"}],\"name\":\"POLWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"poolType\",\"type\":\"uint16\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCollectionRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"PoolRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"contextId\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"targetFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bntFeeAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"trader\",\"type\":\"address\"}],\"name\":\"TokensTraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"cancelWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"collectionByPool\",\"outputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"tokens\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"createPools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenAmount\",\"type\":\"uint256\"}],\"name\":\"depositFor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositingEnabled\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bool\",\"name\":\"status\",\"type\":\"bool\"}],\"name\":\"enableDepositing\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"contractIFlashLoanRecipient\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"flashLoan\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"getRoleMember\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleMemberCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolToken\",\"name\":\"poolToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"poolTokenAmount\",\"type\":\"uint256\"}],\"name\":\"initWithdrawal\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIBNTPool\",\"name\":\"initBNTPool\",\"type\":\"address\"},{\"internalType\":\"contractIPendingWithdrawals\",\"name\":\"initPendingWithdrawals\",\"type\":\"address\"},{\"internalType\":\"contractIPoolMigrator\",\"name\":\"initPoolMigrator\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"liquidityPools\",\"outputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"zcntoken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"availableAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"originalAmount\",\"type\":\"uint256\"}],\"name\":\"migrateLiquidity\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken[]\",\"name\":\"pools\",\"type\":\"address[]\"},{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"migratePools\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingNetworkFeeAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"polRewardsPPM\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolCollections\",\"outputs\":[{\"internalType\":\"contractIPoolCollection[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"postUpgrade\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"newPoolCollection\",\"type\":\"address\"}],\"name\":\"registerPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"resume\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleEmergencyStopper\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleMigrationManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"roleNetworkFeeManager\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"newRewardsPPM\",\"type\":\"uint32\"}],\"name\":\"setPOLRewardsPPM\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturnAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeBySourceAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractToken\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"targetAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"maxSourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"tradeByTargetAmountArb\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractIPoolCollection\",\"name\":\"poolCollection\",\"type\":\"address\"}],\"name\":\"unregisterPoolCollection\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint16\",\"name\":\"\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"withdrawNetworkFees\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contractToken\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"withdrawPOL\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// BancorABI is the input ABI used to generate the binding from. +// Deprecated: Use BancorMetaData.ABI instead. +var BancorABI = BancorMetaData.ABI + +// Bancor is an auto generated Go binding around an Ethereum contract. +type Bancor struct { + BancorCaller // Read-only binding to the contract + BancorTransactor // Write-only binding to the contract + BancorFilterer // Log filterer for contract events +} + +// BancorCaller is an auto generated read-only Go binding around an Ethereum contract. +type BancorCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorTransactor is an auto generated write-only Go binding around an Ethereum contract. +type BancorTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type BancorFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancorSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type BancorSession struct { + Contract *Bancor // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancorCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type BancorCallerSession struct { + Contract *BancorCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// BancorTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type BancorTransactorSession struct { + Contract *BancorTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancorRaw is an auto generated low-level Go binding around an Ethereum contract. +type BancorRaw struct { + Contract *Bancor // Generic contract binding to access the raw methods on +} + +// BancorCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type BancorCallerRaw struct { + Contract *BancorCaller // Generic read-only contract binding to access the raw methods on +} + +// BancorTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type BancorTransactorRaw struct { + Contract *BancorTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewBancor creates a new instance of Bancor, bound to a specific deployed contract. +func NewBancor(address common.Address, backend bind.ContractBackend) (*Bancor, error) { + contract, err := bindBancor(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Bancor{BancorCaller: BancorCaller{contract: contract}, BancorTransactor: BancorTransactor{contract: contract}, BancorFilterer: BancorFilterer{contract: contract}}, nil +} + +// NewBancorCaller creates a new read-only instance of Bancor, bound to a specific deployed contract. +func NewBancorCaller(address common.Address, caller bind.ContractCaller) (*BancorCaller, error) { + contract, err := bindBancor(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &BancorCaller{contract: contract}, nil +} + +// NewBancorTransactor creates a new write-only instance of Bancor, bound to a specific deployed contract. +func NewBancorTransactor(address common.Address, transactor bind.ContractTransactor) (*BancorTransactor, error) { + contract, err := bindBancor(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &BancorTransactor{contract: contract}, nil +} + +// NewBancorFilterer creates a new log filterer instance of Bancor, bound to a specific deployed contract. +func NewBancorFilterer(address common.Address, filterer bind.ContractFilterer) (*BancorFilterer, error) { + contract, err := bindBancor(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &BancorFilterer{contract: contract}, nil +} + +// bindBancor binds a generic wrapper to an already deployed contract. +func bindBancor(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := BancorMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancor *BancorRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancor.Contract.BancorCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancor *BancorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.Contract.BancorTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancor *BancorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancor.Contract.BancorTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancor *BancorCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancor.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancor *BancorTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancor *BancorTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancor.Contract.contract.Transact(opts, method, params...) +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorCaller) DEFAULTADMINROLE(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "DEFAULT_ADMIN_ROLE") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorSession) DEFAULTADMINROLE() ([32]byte, error) { + return _Bancor.Contract.DEFAULTADMINROLE(&_Bancor.CallOpts) +} + +// DEFAULTADMINROLE is a free data retrieval call binding the contract method 0xa217fddf. +// +// Solidity: function DEFAULT_ADMIN_ROLE() view returns(bytes32) +func (_Bancor *BancorCallerSession) DEFAULTADMINROLE() ([32]byte, error) { + return _Bancor.Contract.DEFAULTADMINROLE(&_Bancor.CallOpts) +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorCaller) CollectionByPool(opts *bind.CallOpts, pool common.Address) (common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "collectionByPool", pool) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorSession) CollectionByPool(pool common.Address) (common.Address, error) { + return _Bancor.Contract.CollectionByPool(&_Bancor.CallOpts, pool) +} + +// CollectionByPool is a free data retrieval call binding the contract method 0x9bca0e70. +// +// Solidity: function collectionByPool(address pool) view returns(address) +func (_Bancor *BancorCallerSession) CollectionByPool(pool common.Address) (common.Address, error) { + return _Bancor.Contract.CollectionByPool(&_Bancor.CallOpts, pool) +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorCaller) DepositingEnabled(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "depositingEnabled") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorSession) DepositingEnabled() (bool, error) { + return _Bancor.Contract.DepositingEnabled(&_Bancor.CallOpts) +} + +// DepositingEnabled is a free data retrieval call binding the contract method 0x71f43f9a. +// +// Solidity: function depositingEnabled() view returns(bool) +func (_Bancor *BancorCallerSession) DepositingEnabled() (bool, error) { + return _Bancor.Contract.DepositingEnabled(&_Bancor.CallOpts) +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorCaller) GetRoleAdmin(opts *bind.CallOpts, role [32]byte) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleAdmin", role) + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorSession) GetRoleAdmin(role [32]byte) ([32]byte, error) { + return _Bancor.Contract.GetRoleAdmin(&_Bancor.CallOpts, role) +} + +// GetRoleAdmin is a free data retrieval call binding the contract method 0x248a9ca3. +// +// Solidity: function getRoleAdmin(bytes32 role) view returns(bytes32) +func (_Bancor *BancorCallerSession) GetRoleAdmin(role [32]byte) ([32]byte, error) { + return _Bancor.Contract.GetRoleAdmin(&_Bancor.CallOpts, role) +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorCaller) GetRoleMember(opts *bind.CallOpts, role [32]byte, index *big.Int) (common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleMember", role, index) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorSession) GetRoleMember(role [32]byte, index *big.Int) (common.Address, error) { + return _Bancor.Contract.GetRoleMember(&_Bancor.CallOpts, role, index) +} + +// GetRoleMember is a free data retrieval call binding the contract method 0x9010d07c. +// +// Solidity: function getRoleMember(bytes32 role, uint256 index) view returns(address) +func (_Bancor *BancorCallerSession) GetRoleMember(role [32]byte, index *big.Int) (common.Address, error) { + return _Bancor.Contract.GetRoleMember(&_Bancor.CallOpts, role, index) +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorCaller) GetRoleMemberCount(opts *bind.CallOpts, role [32]byte) (*big.Int, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "getRoleMemberCount", role) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorSession) GetRoleMemberCount(role [32]byte) (*big.Int, error) { + return _Bancor.Contract.GetRoleMemberCount(&_Bancor.CallOpts, role) +} + +// GetRoleMemberCount is a free data retrieval call binding the contract method 0xca15c873. +// +// Solidity: function getRoleMemberCount(bytes32 role) view returns(uint256) +func (_Bancor *BancorCallerSession) GetRoleMemberCount(role [32]byte) (*big.Int, error) { + return _Bancor.Contract.GetRoleMemberCount(&_Bancor.CallOpts, role) +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorCaller) HasRole(opts *bind.CallOpts, role [32]byte, account common.Address) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "hasRole", role, account) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorSession) HasRole(role [32]byte, account common.Address) (bool, error) { + return _Bancor.Contract.HasRole(&_Bancor.CallOpts, role, account) +} + +// HasRole is a free data retrieval call binding the contract method 0x91d14854. +// +// Solidity: function hasRole(bytes32 role, address account) view returns(bool) +func (_Bancor *BancorCallerSession) HasRole(role [32]byte, account common.Address) (bool, error) { + return _Bancor.Contract.HasRole(&_Bancor.CallOpts, role, account) +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorCaller) LiquidityPools(opts *bind.CallOpts) ([]common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "liquidityPools") + + if err != nil { + return *new([]common.Address), err + } + + out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + + return out0, err + +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorSession) LiquidityPools() ([]common.Address, error) { + return _Bancor.Contract.LiquidityPools(&_Bancor.CallOpts) +} + +// LiquidityPools is a free data retrieval call binding the contract method 0xd6efd7c3. +// +// Solidity: function liquidityPools() view returns(address[]) +func (_Bancor *BancorCallerSession) LiquidityPools() ([]common.Address, error) { + return _Bancor.Contract.LiquidityPools(&_Bancor.CallOpts) +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorCaller) Paused(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "paused") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorSession) Paused() (bool, error) { + return _Bancor.Contract.Paused(&_Bancor.CallOpts) +} + +// Paused is a free data retrieval call binding the contract method 0x5c975abb. +// +// Solidity: function paused() view returns(bool) +func (_Bancor *BancorCallerSession) Paused() (bool, error) { + return _Bancor.Contract.Paused(&_Bancor.CallOpts) +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorCaller) PendingNetworkFeeAmount(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "pendingNetworkFeeAmount") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorSession) PendingNetworkFeeAmount() (*big.Int, error) { + return _Bancor.Contract.PendingNetworkFeeAmount(&_Bancor.CallOpts) +} + +// PendingNetworkFeeAmount is a free data retrieval call binding the contract method 0x7bf6a425. +// +// Solidity: function pendingNetworkFeeAmount() view returns(uint256) +func (_Bancor *BancorCallerSession) PendingNetworkFeeAmount() (*big.Int, error) { + return _Bancor.Contract.PendingNetworkFeeAmount(&_Bancor.CallOpts) +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorCaller) PolRewardsPPM(opts *bind.CallOpts) (uint32, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "polRewardsPPM") + + if err != nil { + return *new(uint32), err + } + + out0 := *abi.ConvertType(out[0], new(uint32)).(*uint32) + + return out0, err + +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorSession) PolRewardsPPM() (uint32, error) { + return _Bancor.Contract.PolRewardsPPM(&_Bancor.CallOpts) +} + +// PolRewardsPPM is a free data retrieval call binding the contract method 0x1329db29. +// +// Solidity: function polRewardsPPM() view returns(uint32) +func (_Bancor *BancorCallerSession) PolRewardsPPM() (uint32, error) { + return _Bancor.Contract.PolRewardsPPM(&_Bancor.CallOpts) +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorCaller) PoolCollections(opts *bind.CallOpts) ([]common.Address, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "poolCollections") + + if err != nil { + return *new([]common.Address), err + } + + out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + + return out0, err + +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorSession) PoolCollections() ([]common.Address, error) { + return _Bancor.Contract.PoolCollections(&_Bancor.CallOpts) +} + +// PoolCollections is a free data retrieval call binding the contract method 0x39fadf98. +// +// Solidity: function poolCollections() view returns(address[]) +func (_Bancor *BancorCallerSession) PoolCollections() ([]common.Address, error) { + return _Bancor.Contract.PoolCollections(&_Bancor.CallOpts) +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleAdmin(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleAdmin") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorSession) RoleAdmin() ([32]byte, error) { + return _Bancor.Contract.RoleAdmin(&_Bancor.CallOpts) +} + +// RoleAdmin is a free data retrieval call binding the contract method 0x93867fb5. +// +// Solidity: function roleAdmin() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleAdmin() ([32]byte, error) { + return _Bancor.Contract.RoleAdmin(&_Bancor.CallOpts) +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleEmergencyStopper(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleEmergencyStopper") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorSession) RoleEmergencyStopper() ([32]byte, error) { + return _Bancor.Contract.RoleEmergencyStopper(&_Bancor.CallOpts) +} + +// RoleEmergencyStopper is a free data retrieval call binding the contract method 0x41f435b3. +// +// Solidity: function roleEmergencyStopper() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleEmergencyStopper() ([32]byte, error) { + return _Bancor.Contract.RoleEmergencyStopper(&_Bancor.CallOpts) +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleMigrationManager(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleMigrationManager") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorSession) RoleMigrationManager() ([32]byte, error) { + return _Bancor.Contract.RoleMigrationManager(&_Bancor.CallOpts) +} + +// RoleMigrationManager is a free data retrieval call binding the contract method 0xe6aac07e. +// +// Solidity: function roleMigrationManager() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleMigrationManager() ([32]byte, error) { + return _Bancor.Contract.RoleMigrationManager(&_Bancor.CallOpts) +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorCaller) RoleNetworkFeeManager(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "roleNetworkFeeManager") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorSession) RoleNetworkFeeManager() ([32]byte, error) { + return _Bancor.Contract.RoleNetworkFeeManager(&_Bancor.CallOpts) +} + +// RoleNetworkFeeManager is a free data retrieval call binding the contract method 0xc8447487. +// +// Solidity: function roleNetworkFeeManager() pure returns(bytes32) +func (_Bancor *BancorCallerSession) RoleNetworkFeeManager() ([32]byte, error) { + return _Bancor.Contract.RoleNetworkFeeManager(&_Bancor.CallOpts) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "supportsInterface", interfaceId) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _Bancor.Contract.SupportsInterface(&_Bancor.CallOpts, interfaceId) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) view returns(bool) +func (_Bancor *BancorCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _Bancor.Contract.SupportsInterface(&_Bancor.CallOpts, interfaceId) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorCaller) Version(opts *bind.CallOpts) (uint16, error) { + var out []interface{} + err := _Bancor.contract.Call(opts, &out, "version") + + if err != nil { + return *new(uint16), err + } + + out0 := *abi.ConvertType(out[0], new(uint16)).(*uint16) + + return out0, err + +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorSession) Version() (uint16, error) { + return _Bancor.Contract.Version(&_Bancor.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() pure returns(uint16) +func (_Bancor *BancorCallerSession) Version() (uint16, error) { + return _Bancor.Contract.Version(&_Bancor.CallOpts) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorTransactor) CancelWithdrawal(opts *bind.TransactOpts, id *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "cancelWithdrawal", id) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorSession) CancelWithdrawal(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.CancelWithdrawal(&_Bancor.TransactOpts, id) +} + +// CancelWithdrawal is a paid mutator transaction binding the contract method 0x3efcfda4. +// +// Solidity: function cancelWithdrawal(uint256 id) returns(uint256) +func (_Bancor *BancorTransactorSession) CancelWithdrawal(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.CancelWithdrawal(&_Bancor.TransactOpts, id) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorTransactor) CreatePools(opts *bind.TransactOpts, tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "createPools", tokens, poolCollection) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorSession) CreatePools(tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.CreatePools(&_Bancor.TransactOpts, tokens, poolCollection) +} + +// CreatePools is a paid mutator transaction binding the contract method 0x42659964. +// +// Solidity: function createPools(address[] tokens, address poolCollection) returns() +func (_Bancor *BancorTransactorSession) CreatePools(tokens []common.Address, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.CreatePools(&_Bancor.TransactOpts, tokens, poolCollection) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactor) Deposit(opts *bind.TransactOpts, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "deposit", pool, tokenAmount) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorSession) Deposit(pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Deposit(&_Bancor.TransactOpts, pool, tokenAmount) +} + +// Deposit is a paid mutator transaction binding the contract method 0x47e7ef24. +// +// Solidity: function deposit(address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactorSession) Deposit(pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Deposit(&_Bancor.TransactOpts, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactor) DepositFor(opts *bind.TransactOpts, provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "depositFor", provider, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorSession) DepositFor(provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.DepositFor(&_Bancor.TransactOpts, provider, pool, tokenAmount) +} + +// DepositFor is a paid mutator transaction binding the contract method 0xb3db428b. +// +// Solidity: function depositFor(address provider, address pool, uint256 tokenAmount) payable returns(uint256) +func (_Bancor *BancorTransactorSession) DepositFor(provider common.Address, pool common.Address, tokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.DepositFor(&_Bancor.TransactOpts, provider, pool, tokenAmount) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorTransactor) EnableDepositing(opts *bind.TransactOpts, status bool) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "enableDepositing", status) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorSession) EnableDepositing(status bool) (*types.Transaction, error) { + return _Bancor.Contract.EnableDepositing(&_Bancor.TransactOpts, status) +} + +// EnableDepositing is a paid mutator transaction binding the contract method 0x26e6b697. +// +// Solidity: function enableDepositing(bool status) returns() +func (_Bancor *BancorTransactorSession) EnableDepositing(status bool) (*types.Transaction, error) { + return _Bancor.Contract.EnableDepositing(&_Bancor.TransactOpts, status) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorTransactor) FlashLoan(opts *bind.TransactOpts, token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "flashLoan", token, amount, recipient, data) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) +} + +// FlashLoan is a paid mutator transaction binding the contract method 0xadf51de1. +// +// Solidity: function flashLoan(address zcntoken, uint256 amount, address recipient, bytes data) returns() +func (_Bancor *BancorTransactorSession) FlashLoan(token common.Address, amount *big.Int, recipient common.Address, data []byte) (*types.Transaction, error) { + return _Bancor.Contract.FlashLoan(&_Bancor.TransactOpts, token, amount, recipient, data) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) GrantRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "grantRole", role, account) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) GrantRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.GrantRole(&_Bancor.TransactOpts, role, account) +} + +// GrantRole is a paid mutator transaction binding the contract method 0x2f2ff15d. +// +// Solidity: function grantRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) GrantRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.GrantRole(&_Bancor.TransactOpts, role, account) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorTransactor) InitWithdrawal(opts *bind.TransactOpts, poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "initWithdrawal", poolToken, poolTokenAmount) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorSession) InitWithdrawal(poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.InitWithdrawal(&_Bancor.TransactOpts, poolToken, poolTokenAmount) +} + +// InitWithdrawal is a paid mutator transaction binding the contract method 0x357a0333. +// +// Solidity: function initWithdrawal(address poolToken, uint256 poolTokenAmount) returns(uint256) +func (_Bancor *BancorTransactorSession) InitWithdrawal(poolToken common.Address, poolTokenAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.InitWithdrawal(&_Bancor.TransactOpts, poolToken, poolTokenAmount) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorTransactor) Initialize(opts *bind.TransactOpts, initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "initialize", initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorSession) Initialize(initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.Contract.Initialize(&_Bancor.TransactOpts, initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// Initialize is a paid mutator transaction binding the contract method 0xc0c53b8b. +// +// Solidity: function initialize(address initBNTPool, address initPendingWithdrawals, address initPoolMigrator) returns() +func (_Bancor *BancorTransactorSession) Initialize(initBNTPool common.Address, initPendingWithdrawals common.Address, initPoolMigrator common.Address) (*types.Transaction, error) { + return _Bancor.Contract.Initialize(&_Bancor.TransactOpts, initBNTPool, initPendingWithdrawals, initPoolMigrator) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorTransactor) MigrateLiquidity(opts *bind.TransactOpts, token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "migrateLiquidity", token, provider, amount, availableAmount, originalAmount) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) +} + +// MigrateLiquidity is a paid mutator transaction binding the contract method 0x3d1c24e7. +// +// Solidity: function migrateLiquidity(address zcntoken, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) payable returns() +func (_Bancor *BancorTransactorSession) MigrateLiquidity(token common.Address, provider common.Address, amount *big.Int, availableAmount *big.Int, originalAmount *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.MigrateLiquidity(&_Bancor.TransactOpts, token, provider, amount, availableAmount, originalAmount) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorTransactor) MigratePools(opts *bind.TransactOpts, pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "migratePools", pools, newPoolCollection) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorSession) MigratePools(pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.MigratePools(&_Bancor.TransactOpts, pools, newPoolCollection) +} + +// MigratePools is a paid mutator transaction binding the contract method 0xc109ba13. +// +// Solidity: function migratePools(address[] pools, address newPoolCollection) returns() +func (_Bancor *BancorTransactorSession) MigratePools(pools []common.Address, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.MigratePools(&_Bancor.TransactOpts, pools, newPoolCollection) +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorTransactor) Pause(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "pause") +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorSession) Pause() (*types.Transaction, error) { + return _Bancor.Contract.Pause(&_Bancor.TransactOpts) +} + +// Pause is a paid mutator transaction binding the contract method 0x8456cb59. +// +// Solidity: function pause() returns() +func (_Bancor *BancorTransactorSession) Pause() (*types.Transaction, error) { + return _Bancor.Contract.Pause(&_Bancor.TransactOpts) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorTransactor) PostUpgrade(opts *bind.TransactOpts, data []byte) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "postUpgrade", data) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorSession) PostUpgrade(data []byte) (*types.Transaction, error) { + return _Bancor.Contract.PostUpgrade(&_Bancor.TransactOpts, data) +} + +// PostUpgrade is a paid mutator transaction binding the contract method 0x8cd2403d. +// +// Solidity: function postUpgrade(bytes data) returns() +func (_Bancor *BancorTransactorSession) PostUpgrade(data []byte) (*types.Transaction, error) { + return _Bancor.Contract.PostUpgrade(&_Bancor.TransactOpts, data) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorTransactor) RegisterPoolCollection(opts *bind.TransactOpts, newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "registerPoolCollection", newPoolCollection) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorSession) RegisterPoolCollection(newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RegisterPoolCollection(&_Bancor.TransactOpts, newPoolCollection) +} + +// RegisterPoolCollection is a paid mutator transaction binding the contract method 0xa8bf9046. +// +// Solidity: function registerPoolCollection(address newPoolCollection) returns() +func (_Bancor *BancorTransactorSession) RegisterPoolCollection(newPoolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RegisterPoolCollection(&_Bancor.TransactOpts, newPoolCollection) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) RenounceRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "renounceRole", role, account) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) RenounceRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RenounceRole(&_Bancor.TransactOpts, role, account) +} + +// RenounceRole is a paid mutator transaction binding the contract method 0x36568abe. +// +// Solidity: function renounceRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) RenounceRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RenounceRole(&_Bancor.TransactOpts, role, account) +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorTransactor) Resume(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "resume") +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorSession) Resume() (*types.Transaction, error) { + return _Bancor.Contract.Resume(&_Bancor.TransactOpts) +} + +// Resume is a paid mutator transaction binding the contract method 0x046f7da2. +// +// Solidity: function resume() returns() +func (_Bancor *BancorTransactorSession) Resume() (*types.Transaction, error) { + return _Bancor.Contract.Resume(&_Bancor.TransactOpts) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactor) RevokeRole(opts *bind.TransactOpts, role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "revokeRole", role, account) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorSession) RevokeRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RevokeRole(&_Bancor.TransactOpts, role, account) +} + +// RevokeRole is a paid mutator transaction binding the contract method 0xd547741f. +// +// Solidity: function revokeRole(bytes32 role, address account) returns() +func (_Bancor *BancorTransactorSession) RevokeRole(role [32]byte, account common.Address) (*types.Transaction, error) { + return _Bancor.Contract.RevokeRole(&_Bancor.TransactOpts, role, account) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorTransactor) SetPOLRewardsPPM(opts *bind.TransactOpts, newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "setPOLRewardsPPM", newRewardsPPM) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorSession) SetPOLRewardsPPM(newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.Contract.SetPOLRewardsPPM(&_Bancor.TransactOpts, newRewardsPPM) +} + +// SetPOLRewardsPPM is a paid mutator transaction binding the contract method 0x53300772. +// +// Solidity: function setPOLRewardsPPM(uint32 newRewardsPPM) returns() +func (_Bancor *BancorTransactorSession) SetPOLRewardsPPM(newRewardsPPM uint32) (*types.Transaction, error) { + return _Bancor.Contract.SetPOLRewardsPPM(&_Bancor.TransactOpts, newRewardsPPM) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeBySourceAmount(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeBySourceAmount", sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeBySourceAmount(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmount(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmount is a paid mutator transaction binding the contract method 0xd3a4acd3. +// +// Solidity: function tradeBySourceAmount(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeBySourceAmount(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmount(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeBySourceAmountArb(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeBySourceAmountArb", sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeBySourceAmountArb(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeBySourceAmountArb is a paid mutator transaction binding the contract method 0xd895feee. +// +// Solidity: function tradeBySourceAmountArb(address sourceToken, address targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeBySourceAmountArb(sourceToken common.Address, targetToken common.Address, sourceAmount *big.Int, minReturnAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeBySourceAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, sourceAmount, minReturnAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeByTargetAmount(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeByTargetAmount", sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeByTargetAmount(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmount(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmount is a paid mutator transaction binding the contract method 0x45d6602c. +// +// Solidity: function tradeByTargetAmount(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeByTargetAmount(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmount(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactor) TradeByTargetAmountArb(opts *bind.TransactOpts, sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "tradeByTargetAmountArb", sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorSession) TradeByTargetAmountArb(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// TradeByTargetAmountArb is a paid mutator transaction binding the contract method 0xd0d14581. +// +// Solidity: function tradeByTargetAmountArb(address sourceToken, address targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary) payable returns(uint256) +func (_Bancor *BancorTransactorSession) TradeByTargetAmountArb(sourceToken common.Address, targetToken common.Address, targetAmount *big.Int, maxSourceAmount *big.Int, deadline *big.Int, beneficiary common.Address) (*types.Transaction, error) { + return _Bancor.Contract.TradeByTargetAmountArb(&_Bancor.TransactOpts, sourceToken, targetToken, targetAmount, maxSourceAmount, deadline, beneficiary) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorTransactor) UnregisterPoolCollection(opts *bind.TransactOpts, poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "unregisterPoolCollection", poolCollection) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorSession) UnregisterPoolCollection(poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.UnregisterPoolCollection(&_Bancor.TransactOpts, poolCollection) +} + +// UnregisterPoolCollection is a paid mutator transaction binding the contract method 0x230df83a. +// +// Solidity: function unregisterPoolCollection(address poolCollection) returns() +func (_Bancor *BancorTransactorSession) UnregisterPoolCollection(poolCollection common.Address) (*types.Transaction, error) { + return _Bancor.Contract.UnregisterPoolCollection(&_Bancor.TransactOpts, poolCollection) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorTransactor) Withdraw(opts *bind.TransactOpts, id *big.Int) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdraw", id) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorSession) Withdraw(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Withdraw(&_Bancor.TransactOpts, id) +} + +// Withdraw is a paid mutator transaction binding the contract method 0x2e1a7d4d. +// +// Solidity: function withdraw(uint256 id) returns(uint256) +func (_Bancor *BancorTransactorSession) Withdraw(id *big.Int) (*types.Transaction, error) { + return _Bancor.Contract.Withdraw(&_Bancor.TransactOpts, id) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorTransactor) WithdrawNetworkFees(opts *bind.TransactOpts, recipient common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdrawNetworkFees", recipient) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorSession) WithdrawNetworkFees(recipient common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawNetworkFees(&_Bancor.TransactOpts, recipient) +} + +// WithdrawNetworkFees is a paid mutator transaction binding the contract method 0x3cd11924. +// +// Solidity: function withdrawNetworkFees(address recipient) returns(uint256) +func (_Bancor *BancorTransactorSession) WithdrawNetworkFees(recipient common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawNetworkFees(&_Bancor.TransactOpts, recipient) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorTransactor) WithdrawPOL(opts *bind.TransactOpts, pool common.Address) (*types.Transaction, error) { + return _Bancor.contract.Transact(opts, "withdrawPOL", pool) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorSession) WithdrawPOL(pool common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawPOL(&_Bancor.TransactOpts, pool) +} + +// WithdrawPOL is a paid mutator transaction binding the contract method 0x8ffcca07. +// +// Solidity: function withdrawPOL(address pool) returns(uint256) +func (_Bancor *BancorTransactorSession) WithdrawPOL(pool common.Address) (*types.Transaction, error) { + return _Bancor.Contract.WithdrawPOL(&_Bancor.TransactOpts, pool) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancor.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorSession) Receive() (*types.Transaction, error) { + return _Bancor.Contract.Receive(&_Bancor.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_Bancor *BancorTransactorSession) Receive() (*types.Transaction, error) { + return _Bancor.Contract.Receive(&_Bancor.TransactOpts) +} + +// BancorFlashLoanCompletedIterator is returned from FilterFlashLoanCompleted and is used to iterate over the raw logs and unpacked data for FlashLoanCompleted events raised by the Bancor contract. +type BancorFlashLoanCompletedIterator struct { + Event *BancorFlashLoanCompleted // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorFlashLoanCompletedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorFlashLoanCompleted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorFlashLoanCompleted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorFlashLoanCompletedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorFlashLoanCompletedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorFlashLoanCompleted represents a FlashLoanCompleted event raised by the Bancor contract. +type BancorFlashLoanCompleted struct { + Token common.Address + Borrower common.Address + Amount *big.Int + FeeAmount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterFlashLoanCompleted is a free log retrieval operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) FilterFlashLoanCompleted(opts *bind.FilterOpts, token []common.Address, borrower []common.Address) (*BancorFlashLoanCompletedIterator, error) { + + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var borrowerRule []interface{} + for _, borrowerItem := range borrower { + borrowerRule = append(borrowerRule, borrowerItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "FlashLoanCompleted", tokenRule, borrowerRule) + if err != nil { + return nil, err + } + return &BancorFlashLoanCompletedIterator{contract: _Bancor.contract, event: "FlashLoanCompleted", logs: logs, sub: sub}, nil +} + +// WatchFlashLoanCompleted is a free log subscription operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) WatchFlashLoanCompleted(opts *bind.WatchOpts, sink chan<- *BancorFlashLoanCompleted, token []common.Address, borrower []common.Address) (event.Subscription, error) { + + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var borrowerRule []interface{} + for _, borrowerItem := range borrower { + borrowerRule = append(borrowerRule, borrowerItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "FlashLoanCompleted", tokenRule, borrowerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorFlashLoanCompleted) + if err := _Bancor.contract.UnpackLog(event, "FlashLoanCompleted", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseFlashLoanCompleted is a log parse operation binding the contract event 0x0da3485ef1bb570df7bb888887eae5aa01d81b83cd8ccc80c0ea0922a677ecef. +// +// Solidity: event FlashLoanCompleted(address indexed zcntoken, address indexed borrower, uint256 amount, uint256 feeAmount) +func (_Bancor *BancorFilterer) ParseFlashLoanCompleted(log types.Log) (*BancorFlashLoanCompleted, error) { + event := new(BancorFlashLoanCompleted) + if err := _Bancor.contract.UnpackLog(event, "FlashLoanCompleted", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorFundsMigratedIterator is returned from FilterFundsMigrated and is used to iterate over the raw logs and unpacked data for FundsMigrated events raised by the Bancor contract. +type BancorFundsMigratedIterator struct { + Event *BancorFundsMigrated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorFundsMigratedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorFundsMigrated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorFundsMigrated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorFundsMigratedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorFundsMigratedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorFundsMigrated represents a FundsMigrated event raised by the Bancor contract. +type BancorFundsMigrated struct { + ContextId [32]byte + Token common.Address + Provider common.Address + Amount *big.Int + AvailableAmount *big.Int + OriginalAmount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterFundsMigrated is a free log retrieval operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) FilterFundsMigrated(opts *bind.FilterOpts, contextId [][32]byte, token []common.Address, provider []common.Address) (*BancorFundsMigratedIterator, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var providerRule []interface{} + for _, providerItem := range provider { + providerRule = append(providerRule, providerItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "FundsMigrated", contextIdRule, tokenRule, providerRule) + if err != nil { + return nil, err + } + return &BancorFundsMigratedIterator{contract: _Bancor.contract, event: "FundsMigrated", logs: logs, sub: sub}, nil +} + +// WatchFundsMigrated is a free log subscription operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) WatchFundsMigrated(opts *bind.WatchOpts, sink chan<- *BancorFundsMigrated, contextId [][32]byte, token []common.Address, provider []common.Address) (event.Subscription, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var providerRule []interface{} + for _, providerItem := range provider { + providerRule = append(providerRule, providerItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "FundsMigrated", contextIdRule, tokenRule, providerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorFundsMigrated) + if err := _Bancor.contract.UnpackLog(event, "FundsMigrated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseFundsMigrated is a log parse operation binding the contract event 0x102bce4e43a6a8cf0306fde6154221c1f5460f64ba63b92b156bce998ef0db56. +// +// Solidity: event FundsMigrated(bytes32 indexed contextId, address indexed zcntoken, address indexed provider, uint256 amount, uint256 availableAmount, uint256 originalAmount) +func (_Bancor *BancorFilterer) ParseFundsMigrated(log types.Log) (*BancorFundsMigrated, error) { + event := new(BancorFundsMigrated) + if err := _Bancor.contract.UnpackLog(event, "FundsMigrated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorNetworkFeesWithdrawnIterator is returned from FilterNetworkFeesWithdrawn and is used to iterate over the raw logs and unpacked data for NetworkFeesWithdrawn events raised by the Bancor contract. +type BancorNetworkFeesWithdrawnIterator struct { + Event *BancorNetworkFeesWithdrawn // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorNetworkFeesWithdrawnIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorNetworkFeesWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorNetworkFeesWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorNetworkFeesWithdrawnIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorNetworkFeesWithdrawnIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorNetworkFeesWithdrawn represents a NetworkFeesWithdrawn event raised by the Bancor contract. +type BancorNetworkFeesWithdrawn struct { + Caller common.Address + Recipient common.Address + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNetworkFeesWithdrawn is a free log retrieval operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) FilterNetworkFeesWithdrawn(opts *bind.FilterOpts, caller []common.Address, recipient []common.Address) (*BancorNetworkFeesWithdrawnIterator, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var recipientRule []interface{} + for _, recipientItem := range recipient { + recipientRule = append(recipientRule, recipientItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "NetworkFeesWithdrawn", callerRule, recipientRule) + if err != nil { + return nil, err + } + return &BancorNetworkFeesWithdrawnIterator{contract: _Bancor.contract, event: "NetworkFeesWithdrawn", logs: logs, sub: sub}, nil +} + +// WatchNetworkFeesWithdrawn is a free log subscription operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) WatchNetworkFeesWithdrawn(opts *bind.WatchOpts, sink chan<- *BancorNetworkFeesWithdrawn, caller []common.Address, recipient []common.Address) (event.Subscription, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var recipientRule []interface{} + for _, recipientItem := range recipient { + recipientRule = append(recipientRule, recipientItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "NetworkFeesWithdrawn", callerRule, recipientRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorNetworkFeesWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "NetworkFeesWithdrawn", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNetworkFeesWithdrawn is a log parse operation binding the contract event 0x328c9cc28e75030423307e732b07659ae452a620281f3e54e838000a7f467538. +// +// Solidity: event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount) +func (_Bancor *BancorFilterer) ParseNetworkFeesWithdrawn(log types.Log) (*BancorNetworkFeesWithdrawn, error) { + event := new(BancorNetworkFeesWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "NetworkFeesWithdrawn", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPOLRewardsPPMUpdatedIterator is returned from FilterPOLRewardsPPMUpdated and is used to iterate over the raw logs and unpacked data for POLRewardsPPMUpdated events raised by the Bancor contract. +type BancorPOLRewardsPPMUpdatedIterator struct { + Event *BancorPOLRewardsPPMUpdated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPOLRewardsPPMUpdatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPOLRewardsPPMUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPOLRewardsPPMUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPOLRewardsPPMUpdatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPOLRewardsPPMUpdatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPOLRewardsPPMUpdated represents a POLRewardsPPMUpdated event raised by the Bancor contract. +type BancorPOLRewardsPPMUpdated struct { + OldRewardsPPM uint32 + NewRewardsPPM uint32 + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPOLRewardsPPMUpdated is a free log retrieval operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) FilterPOLRewardsPPMUpdated(opts *bind.FilterOpts) (*BancorPOLRewardsPPMUpdatedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "POLRewardsPPMUpdated") + if err != nil { + return nil, err + } + return &BancorPOLRewardsPPMUpdatedIterator{contract: _Bancor.contract, event: "POLRewardsPPMUpdated", logs: logs, sub: sub}, nil +} + +// WatchPOLRewardsPPMUpdated is a free log subscription operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) WatchPOLRewardsPPMUpdated(opts *bind.WatchOpts, sink chan<- *BancorPOLRewardsPPMUpdated) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "POLRewardsPPMUpdated") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPOLRewardsPPMUpdated) + if err := _Bancor.contract.UnpackLog(event, "POLRewardsPPMUpdated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePOLRewardsPPMUpdated is a log parse operation binding the contract event 0xa159b13d7eac36d9a65034b4fd6ace1d9cb070d063dc950c564a266f4d091802. +// +// Solidity: event POLRewardsPPMUpdated(uint32 oldRewardsPPM, uint32 newRewardsPPM) +func (_Bancor *BancorFilterer) ParsePOLRewardsPPMUpdated(log types.Log) (*BancorPOLRewardsPPMUpdated, error) { + event := new(BancorPOLRewardsPPMUpdated) + if err := _Bancor.contract.UnpackLog(event, "POLRewardsPPMUpdated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPOLWithdrawnIterator is returned from FilterPOLWithdrawn and is used to iterate over the raw logs and unpacked data for POLWithdrawn events raised by the Bancor contract. +type BancorPOLWithdrawnIterator struct { + Event *BancorPOLWithdrawn // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPOLWithdrawnIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPOLWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPOLWithdrawn) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPOLWithdrawnIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPOLWithdrawnIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPOLWithdrawn represents a POLWithdrawn event raised by the Bancor contract. +type BancorPOLWithdrawn struct { + Caller common.Address + Token common.Address + PolTokenAmount *big.Int + UserReward *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPOLWithdrawn is a free log retrieval operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) FilterPOLWithdrawn(opts *bind.FilterOpts, caller []common.Address, token []common.Address) (*BancorPOLWithdrawnIterator, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "POLWithdrawn", callerRule, tokenRule) + if err != nil { + return nil, err + } + return &BancorPOLWithdrawnIterator{contract: _Bancor.contract, event: "POLWithdrawn", logs: logs, sub: sub}, nil +} + +// WatchPOLWithdrawn is a free log subscription operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) WatchPOLWithdrawn(opts *bind.WatchOpts, sink chan<- *BancorPOLWithdrawn, caller []common.Address, token []common.Address) (event.Subscription, error) { + + var callerRule []interface{} + for _, callerItem := range caller { + callerRule = append(callerRule, callerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "POLWithdrawn", callerRule, tokenRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPOLWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "POLWithdrawn", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePOLWithdrawn is a log parse operation binding the contract event 0x5ad7a2184454b6259cd118e4041a953dc9d6498302bbe528e4f967bed9197129. +// +// Solidity: event POLWithdrawn(address indexed caller, address indexed zcntoken, uint256 polTokenAmount, uint256 userReward) +func (_Bancor *BancorFilterer) ParsePOLWithdrawn(log types.Log) (*BancorPOLWithdrawn, error) { + event := new(BancorPOLWithdrawn) + if err := _Bancor.contract.UnpackLog(event, "POLWithdrawn", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPausedIterator is returned from FilterPaused and is used to iterate over the raw logs and unpacked data for Paused events raised by the Bancor contract. +type BancorPausedIterator struct { + Event *BancorPaused // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPausedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPausedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPausedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPaused represents a Paused event raised by the Bancor contract. +type BancorPaused struct { + Account common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPaused is a free log retrieval operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) FilterPaused(opts *bind.FilterOpts) (*BancorPausedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "Paused") + if err != nil { + return nil, err + } + return &BancorPausedIterator{contract: _Bancor.contract, event: "Paused", logs: logs, sub: sub}, nil +} + +// WatchPaused is a free log subscription operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) WatchPaused(opts *bind.WatchOpts, sink chan<- *BancorPaused) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "Paused") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPaused) + if err := _Bancor.contract.UnpackLog(event, "Paused", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePaused is a log parse operation binding the contract event 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258. +// +// Solidity: event Paused(address account) +func (_Bancor *BancorFilterer) ParsePaused(log types.Log) (*BancorPaused, error) { + event := new(BancorPaused) + if err := _Bancor.contract.UnpackLog(event, "Paused", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolAddedIterator is returned from FilterPoolAdded and is used to iterate over the raw logs and unpacked data for PoolAdded events raised by the Bancor contract. +type BancorPoolAddedIterator struct { + Event *BancorPoolAdded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolAddedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolAddedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolAddedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolAdded represents a PoolAdded event raised by the Bancor contract. +type BancorPoolAdded struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolAdded is a free log retrieval operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolAdded(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolAddedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolAdded", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolAddedIterator{contract: _Bancor.contract, event: "PoolAdded", logs: logs, sub: sub}, nil +} + +// WatchPoolAdded is a free log subscription operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolAdded(opts *bind.WatchOpts, sink chan<- *BancorPoolAdded, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolAdded", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolAdded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolAdded is a log parse operation binding the contract event 0x95f865c2808f8b2a85eea2611db7843150ee7835ef1403f9755918a97d76933c. +// +// Solidity: event PoolAdded(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolAdded(log types.Log) (*BancorPoolAdded, error) { + event := new(BancorPoolAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolAdded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCollectionAddedIterator is returned from FilterPoolCollectionAdded and is used to iterate over the raw logs and unpacked data for PoolCollectionAdded events raised by the Bancor contract. +type BancorPoolCollectionAddedIterator struct { + Event *BancorPoolCollectionAdded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCollectionAddedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCollectionAddedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCollectionAddedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCollectionAdded represents a PoolCollectionAdded event raised by the Bancor contract. +type BancorPoolCollectionAdded struct { + PoolType uint16 + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCollectionAdded is a free log retrieval operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCollectionAdded(opts *bind.FilterOpts, poolType []uint16, poolCollection []common.Address) (*BancorPoolCollectionAddedIterator, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCollectionAdded", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCollectionAddedIterator{contract: _Bancor.contract, event: "PoolCollectionAdded", logs: logs, sub: sub}, nil +} + +// WatchPoolCollectionAdded is a free log subscription operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCollectionAdded(opts *bind.WatchOpts, sink chan<- *BancorPoolCollectionAdded, poolType []uint16, poolCollection []common.Address) (event.Subscription, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCollectionAdded", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCollectionAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionAdded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCollectionAdded is a log parse operation binding the contract event 0x5ae87719d73cb0fabb219f0e4b6e0a614ed7506f8a08bdb20bebf313573151b7. +// +// Solidity: event PoolCollectionAdded(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCollectionAdded(log types.Log) (*BancorPoolCollectionAdded, error) { + event := new(BancorPoolCollectionAdded) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionAdded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCollectionRemovedIterator is returned from FilterPoolCollectionRemoved and is used to iterate over the raw logs and unpacked data for PoolCollectionRemoved events raised by the Bancor contract. +type BancorPoolCollectionRemovedIterator struct { + Event *BancorPoolCollectionRemoved // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCollectionRemovedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCollectionRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCollectionRemovedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCollectionRemovedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCollectionRemoved represents a PoolCollectionRemoved event raised by the Bancor contract. +type BancorPoolCollectionRemoved struct { + PoolType uint16 + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCollectionRemoved is a free log retrieval operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCollectionRemoved(opts *bind.FilterOpts, poolType []uint16, poolCollection []common.Address) (*BancorPoolCollectionRemovedIterator, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCollectionRemoved", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCollectionRemovedIterator{contract: _Bancor.contract, event: "PoolCollectionRemoved", logs: logs, sub: sub}, nil +} + +// WatchPoolCollectionRemoved is a free log subscription operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCollectionRemoved(opts *bind.WatchOpts, sink chan<- *BancorPoolCollectionRemoved, poolType []uint16, poolCollection []common.Address) (event.Subscription, error) { + + var poolTypeRule []interface{} + for _, poolTypeItem := range poolType { + poolTypeRule = append(poolTypeRule, poolTypeItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCollectionRemoved", poolTypeRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCollectionRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionRemoved", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCollectionRemoved is a log parse operation binding the contract event 0xa0c1e3924f995e5ba38f53b4effb6d4b3eeb84176a2951c589115140f638ac09. +// +// Solidity: event PoolCollectionRemoved(uint16 indexed poolType, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCollectionRemoved(log types.Log) (*BancorPoolCollectionRemoved, error) { + event := new(BancorPoolCollectionRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolCollectionRemoved", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolCreatedIterator is returned from FilterPoolCreated and is used to iterate over the raw logs and unpacked data for PoolCreated events raised by the Bancor contract. +type BancorPoolCreatedIterator struct { + Event *BancorPoolCreated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolCreatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolCreated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolCreated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolCreatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolCreatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolCreated represents a PoolCreated event raised by the Bancor contract. +type BancorPoolCreated struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolCreated is a free log retrieval operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolCreated(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolCreatedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolCreated", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolCreatedIterator{contract: _Bancor.contract, event: "PoolCreated", logs: logs, sub: sub}, nil +} + +// WatchPoolCreated is a free log subscription operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolCreated(opts *bind.WatchOpts, sink chan<- *BancorPoolCreated, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolCreated", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolCreated) + if err := _Bancor.contract.UnpackLog(event, "PoolCreated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolCreated is a log parse operation binding the contract event 0x4f2ce4e40f623ca765fc0167a25cb7842ceaafb8d82d3dec26ca0d0e0d2d4896. +// +// Solidity: event PoolCreated(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolCreated(log types.Log) (*BancorPoolCreated, error) { + event := new(BancorPoolCreated) + if err := _Bancor.contract.UnpackLog(event, "PoolCreated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorPoolRemovedIterator is returned from FilterPoolRemoved and is used to iterate over the raw logs and unpacked data for PoolRemoved events raised by the Bancor contract. +type BancorPoolRemovedIterator struct { + Event *BancorPoolRemoved // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorPoolRemovedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorPoolRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorPoolRemoved) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorPoolRemovedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorPoolRemovedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorPoolRemoved represents a PoolRemoved event raised by the Bancor contract. +type BancorPoolRemoved struct { + Pool common.Address + PoolCollection common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPoolRemoved is a free log retrieval operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) FilterPoolRemoved(opts *bind.FilterOpts, pool []common.Address, poolCollection []common.Address) (*BancorPoolRemovedIterator, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "PoolRemoved", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return &BancorPoolRemovedIterator{contract: _Bancor.contract, event: "PoolRemoved", logs: logs, sub: sub}, nil +} + +// WatchPoolRemoved is a free log subscription operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) WatchPoolRemoved(opts *bind.WatchOpts, sink chan<- *BancorPoolRemoved, pool []common.Address, poolCollection []common.Address) (event.Subscription, error) { + + var poolRule []interface{} + for _, poolItem := range pool { + poolRule = append(poolRule, poolItem) + } + var poolCollectionRule []interface{} + for _, poolCollectionItem := range poolCollection { + poolCollectionRule = append(poolCollectionRule, poolCollectionItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "PoolRemoved", poolRule, poolCollectionRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorPoolRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolRemoved", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePoolRemoved is a log parse operation binding the contract event 0x987eb3c2f78454541205f72f34839b434c306c9eaf4922efd7c0c3060fdb2e4c. +// +// Solidity: event PoolRemoved(address indexed pool, address indexed poolCollection) +func (_Bancor *BancorFilterer) ParsePoolRemoved(log types.Log) (*BancorPoolRemoved, error) { + event := new(BancorPoolRemoved) + if err := _Bancor.contract.UnpackLog(event, "PoolRemoved", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleAdminChangedIterator is returned from FilterRoleAdminChanged and is used to iterate over the raw logs and unpacked data for RoleAdminChanged events raised by the Bancor contract. +type BancorRoleAdminChangedIterator struct { + Event *BancorRoleAdminChanged // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleAdminChangedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleAdminChanged) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleAdminChanged) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleAdminChangedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleAdminChangedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleAdminChanged represents a RoleAdminChanged event raised by the Bancor contract. +type BancorRoleAdminChanged struct { + Role [32]byte + PreviousAdminRole [32]byte + NewAdminRole [32]byte + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleAdminChanged is a free log retrieval operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) FilterRoleAdminChanged(opts *bind.FilterOpts, role [][32]byte, previousAdminRole [][32]byte, newAdminRole [][32]byte) (*BancorRoleAdminChangedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var previousAdminRoleRule []interface{} + for _, previousAdminRoleItem := range previousAdminRole { + previousAdminRoleRule = append(previousAdminRoleRule, previousAdminRoleItem) + } + var newAdminRoleRule []interface{} + for _, newAdminRoleItem := range newAdminRole { + newAdminRoleRule = append(newAdminRoleRule, newAdminRoleItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleAdminChanged", roleRule, previousAdminRoleRule, newAdminRoleRule) + if err != nil { + return nil, err + } + return &BancorRoleAdminChangedIterator{contract: _Bancor.contract, event: "RoleAdminChanged", logs: logs, sub: sub}, nil +} + +// WatchRoleAdminChanged is a free log subscription operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) WatchRoleAdminChanged(opts *bind.WatchOpts, sink chan<- *BancorRoleAdminChanged, role [][32]byte, previousAdminRole [][32]byte, newAdminRole [][32]byte) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var previousAdminRoleRule []interface{} + for _, previousAdminRoleItem := range previousAdminRole { + previousAdminRoleRule = append(previousAdminRoleRule, previousAdminRoleItem) + } + var newAdminRoleRule []interface{} + for _, newAdminRoleItem := range newAdminRole { + newAdminRoleRule = append(newAdminRoleRule, newAdminRoleItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleAdminChanged", roleRule, previousAdminRoleRule, newAdminRoleRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleAdminChanged) + if err := _Bancor.contract.UnpackLog(event, "RoleAdminChanged", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleAdminChanged is a log parse operation binding the contract event 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff. +// +// Solidity: event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole) +func (_Bancor *BancorFilterer) ParseRoleAdminChanged(log types.Log) (*BancorRoleAdminChanged, error) { + event := new(BancorRoleAdminChanged) + if err := _Bancor.contract.UnpackLog(event, "RoleAdminChanged", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleGrantedIterator is returned from FilterRoleGranted and is used to iterate over the raw logs and unpacked data for RoleGranted events raised by the Bancor contract. +type BancorRoleGrantedIterator struct { + Event *BancorRoleGranted // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleGrantedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleGranted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleGranted) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleGrantedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleGrantedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleGranted represents a RoleGranted event raised by the Bancor contract. +type BancorRoleGranted struct { + Role [32]byte + Account common.Address + Sender common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleGranted is a free log retrieval operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) FilterRoleGranted(opts *bind.FilterOpts, role [][32]byte, account []common.Address, sender []common.Address) (*BancorRoleGrantedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleGranted", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return &BancorRoleGrantedIterator{contract: _Bancor.contract, event: "RoleGranted", logs: logs, sub: sub}, nil +} + +// WatchRoleGranted is a free log subscription operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) WatchRoleGranted(opts *bind.WatchOpts, sink chan<- *BancorRoleGranted, role [][32]byte, account []common.Address, sender []common.Address) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleGranted", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleGranted) + if err := _Bancor.contract.UnpackLog(event, "RoleGranted", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleGranted is a log parse operation binding the contract event 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d. +// +// Solidity: event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) ParseRoleGranted(log types.Log) (*BancorRoleGranted, error) { + event := new(BancorRoleGranted) + if err := _Bancor.contract.UnpackLog(event, "RoleGranted", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorRoleRevokedIterator is returned from FilterRoleRevoked and is used to iterate over the raw logs and unpacked data for RoleRevoked events raised by the Bancor contract. +type BancorRoleRevokedIterator struct { + Event *BancorRoleRevoked // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorRoleRevokedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorRoleRevoked) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorRoleRevoked) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorRoleRevokedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorRoleRevokedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorRoleRevoked represents a RoleRevoked event raised by the Bancor contract. +type BancorRoleRevoked struct { + Role [32]byte + Account common.Address + Sender common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRoleRevoked is a free log retrieval operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) FilterRoleRevoked(opts *bind.FilterOpts, role [][32]byte, account []common.Address, sender []common.Address) (*BancorRoleRevokedIterator, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "RoleRevoked", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return &BancorRoleRevokedIterator{contract: _Bancor.contract, event: "RoleRevoked", logs: logs, sub: sub}, nil +} + +// WatchRoleRevoked is a free log subscription operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) WatchRoleRevoked(opts *bind.WatchOpts, sink chan<- *BancorRoleRevoked, role [][32]byte, account []common.Address, sender []common.Address) (event.Subscription, error) { + + var roleRule []interface{} + for _, roleItem := range role { + roleRule = append(roleRule, roleItem) + } + var accountRule []interface{} + for _, accountItem := range account { + accountRule = append(accountRule, accountItem) + } + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "RoleRevoked", roleRule, accountRule, senderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorRoleRevoked) + if err := _Bancor.contract.UnpackLog(event, "RoleRevoked", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRoleRevoked is a log parse operation binding the contract event 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b. +// +// Solidity: event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender) +func (_Bancor *BancorFilterer) ParseRoleRevoked(log types.Log) (*BancorRoleRevoked, error) { + event := new(BancorRoleRevoked) + if err := _Bancor.contract.UnpackLog(event, "RoleRevoked", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorTokensTradedIterator is returned from FilterTokensTraded and is used to iterate over the raw logs and unpacked data for TokensTraded events raised by the Bancor contract. +type BancorTokensTradedIterator struct { + Event *BancorTokensTraded // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorTokensTradedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorTokensTraded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorTokensTraded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorTokensTradedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorTokensTradedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorTokensTraded represents a TokensTraded event raised by the Bancor contract. +type BancorTokensTraded struct { + ContextId [32]byte + SourceToken common.Address + TargetToken common.Address + SourceAmount *big.Int + TargetAmount *big.Int + BntAmount *big.Int + TargetFeeAmount *big.Int + BntFeeAmount *big.Int + Trader common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTokensTraded is a free log retrieval operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) FilterTokensTraded(opts *bind.FilterOpts, contextId [][32]byte, sourceToken []common.Address, targetToken []common.Address) (*BancorTokensTradedIterator, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var sourceTokenRule []interface{} + for _, sourceTokenItem := range sourceToken { + sourceTokenRule = append(sourceTokenRule, sourceTokenItem) + } + var targetTokenRule []interface{} + for _, targetTokenItem := range targetToken { + targetTokenRule = append(targetTokenRule, targetTokenItem) + } + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "TokensTraded", contextIdRule, sourceTokenRule, targetTokenRule) + if err != nil { + return nil, err + } + return &BancorTokensTradedIterator{contract: _Bancor.contract, event: "TokensTraded", logs: logs, sub: sub}, nil +} + +// WatchTokensTraded is a free log subscription operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) WatchTokensTraded(opts *bind.WatchOpts, sink chan<- *BancorTokensTraded, contextId [][32]byte, sourceToken []common.Address, targetToken []common.Address) (event.Subscription, error) { + + var contextIdRule []interface{} + for _, contextIdItem := range contextId { + contextIdRule = append(contextIdRule, contextIdItem) + } + var sourceTokenRule []interface{} + for _, sourceTokenItem := range sourceToken { + sourceTokenRule = append(sourceTokenRule, sourceTokenItem) + } + var targetTokenRule []interface{} + for _, targetTokenItem := range targetToken { + targetTokenRule = append(targetTokenRule, targetTokenItem) + } + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "TokensTraded", contextIdRule, sourceTokenRule, targetTokenRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorTokensTraded) + if err := _Bancor.contract.UnpackLog(event, "TokensTraded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTokensTraded is a log parse operation binding the contract event 0x5c02c2bb2d1d082317eb23916ca27b3e7c294398b60061a2ad54f1c3c018c318. +// +// Solidity: event TokensTraded(bytes32 indexed contextId, address indexed sourceToken, address indexed targetToken, uint256 sourceAmount, uint256 targetAmount, uint256 bntAmount, uint256 targetFeeAmount, uint256 bntFeeAmount, address trader) +func (_Bancor *BancorFilterer) ParseTokensTraded(log types.Log) (*BancorTokensTraded, error) { + event := new(BancorTokensTraded) + if err := _Bancor.contract.UnpackLog(event, "TokensTraded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancorUnpausedIterator is returned from FilterUnpaused and is used to iterate over the raw logs and unpacked data for Unpaused events raised by the Bancor contract. +type BancorUnpausedIterator struct { + Event *BancorUnpaused // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancorUnpausedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancorUnpaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancorUnpaused) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancorUnpausedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancorUnpausedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancorUnpaused represents a Unpaused event raised by the Bancor contract. +type BancorUnpaused struct { + Account common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterUnpaused is a free log retrieval operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) FilterUnpaused(opts *bind.FilterOpts) (*BancorUnpausedIterator, error) { + + logs, sub, err := _Bancor.contract.FilterLogs(opts, "Unpaused") + if err != nil { + return nil, err + } + return &BancorUnpausedIterator{contract: _Bancor.contract, event: "Unpaused", logs: logs, sub: sub}, nil +} + +// WatchUnpaused is a free log subscription operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) WatchUnpaused(opts *bind.WatchOpts, sink chan<- *BancorUnpaused) (event.Subscription, error) { + + logs, sub, err := _Bancor.contract.WatchLogs(opts, "Unpaused") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancorUnpaused) + if err := _Bancor.contract.UnpackLog(event, "Unpaused", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseUnpaused is a log parse operation binding the contract event 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa. +// +// Solidity: event Unpaused(address account) +func (_Bancor *BancorFilterer) ParseUnpaused(log types.Log) (*BancorUnpaused, error) { + event := new(BancorUnpaused) + if err := _Bancor.contract.UnpackLog(event, "Unpaused", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/zcnbridge/ethereum/bancortoken/bancortoken.go b/zcnbridge/ethereum/bancortoken/bancortoken.go new file mode 100644 index 000000000..f07d2c95d --- /dev/null +++ b/zcnbridge/ethereum/bancortoken/bancortoken.go @@ -0,0 +1,1556 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package bancortoken + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// BancortokenMetaData contains all meta data concerning the Bancortoken contract. +var BancortokenMetaData = &bind.MetaData{ + ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_disable\",\"type\":\"bool\"}],\"name\":\"disableTransfers\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"standard\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_token\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"withdrawTokens\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"issue\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"destroy\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"transfersEnabled\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"},{\"name\":\"_symbol\",\"type\":\"string\"},{\"name\":\"_decimals\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_token\",\"type\":\"address\"}],\"name\":\"NewSmartToken\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Issuance\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Destruction\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_prevOwner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_newOwner\",\"type\":\"address\"}],\"name\":\"OwnerUpdate\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]", +} + +// BancortokenABI is the input ABI used to generate the binding from. +// Deprecated: Use BancortokenMetaData.ABI instead. +var BancortokenABI = BancortokenMetaData.ABI + +// Bancortoken is an auto generated Go binding around an Ethereum contract. +type Bancortoken struct { + BancortokenCaller // Read-only binding to the contract + BancortokenTransactor // Write-only binding to the contract + BancortokenFilterer // Log filterer for contract events +} + +// BancortokenCaller is an auto generated read-only Go binding around an Ethereum contract. +type BancortokenCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenTransactor is an auto generated write-only Go binding around an Ethereum contract. +type BancortokenTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type BancortokenFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// BancortokenSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type BancortokenSession struct { + Contract *Bancortoken // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancortokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type BancortokenCallerSession struct { + Contract *BancortokenCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// BancortokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type BancortokenTransactorSession struct { + Contract *BancortokenTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// BancortokenRaw is an auto generated low-level Go binding around an Ethereum contract. +type BancortokenRaw struct { + Contract *Bancortoken // Generic contract binding to access the raw methods on +} + +// BancortokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type BancortokenCallerRaw struct { + Contract *BancortokenCaller // Generic read-only contract binding to access the raw methods on +} + +// BancortokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type BancortokenTransactorRaw struct { + Contract *BancortokenTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewBancortoken creates a new instance of Bancortoken, bound to a specific deployed contract. +func NewBancortoken(address common.Address, backend bind.ContractBackend) (*Bancortoken, error) { + contract, err := bindBancortoken(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Bancortoken{BancortokenCaller: BancortokenCaller{contract: contract}, BancortokenTransactor: BancortokenTransactor{contract: contract}, BancortokenFilterer: BancortokenFilterer{contract: contract}}, nil +} + +// NewBancortokenCaller creates a new read-only instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenCaller(address common.Address, caller bind.ContractCaller) (*BancortokenCaller, error) { + contract, err := bindBancortoken(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &BancortokenCaller{contract: contract}, nil +} + +// NewBancortokenTransactor creates a new write-only instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenTransactor(address common.Address, transactor bind.ContractTransactor) (*BancortokenTransactor, error) { + contract, err := bindBancortoken(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &BancortokenTransactor{contract: contract}, nil +} + +// NewBancortokenFilterer creates a new log filterer instance of Bancortoken, bound to a specific deployed contract. +func NewBancortokenFilterer(address common.Address, filterer bind.ContractFilterer) (*BancortokenFilterer, error) { + contract, err := bindBancortoken(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &BancortokenFilterer{contract: contract}, nil +} + +// bindBancortoken binds a generic wrapper to an already deployed contract. +func bindBancortoken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := BancortokenMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancortoken *BancortokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancortoken.Contract.BancortokenCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancortoken *BancortokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.Contract.BancortokenTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancortoken *BancortokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancortoken.Contract.BancortokenTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Bancortoken *BancortokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Bancortoken.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Bancortoken *BancortokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Bancortoken *BancortokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Bancortoken.Contract.contract.Transact(opts, method, params...) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenCaller) Allowance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "allowance", arg0, arg1) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenSession) Allowance(arg0 common.Address, arg1 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.Allowance(&_Bancortoken.CallOpts, arg0, arg1) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address , address ) returns(uint256) +func (_Bancortoken *BancortokenCallerSession) Allowance(arg0 common.Address, arg1 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.Allowance(&_Bancortoken.CallOpts, arg0, arg1) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenCaller) BalanceOf(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "balanceOf", arg0) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenSession) BalanceOf(arg0 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.BalanceOf(&_Bancortoken.CallOpts, arg0) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address ) returns(uint256) +func (_Bancortoken *BancortokenCallerSession) BalanceOf(arg0 common.Address) (*big.Int, error) { + return _Bancortoken.Contract.BalanceOf(&_Bancortoken.CallOpts, arg0) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "decimals") + + if err != nil { + return *new(uint8), err + } + + out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) + + return out0, err + +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenSession) Decimals() (uint8, error) { + return _Bancortoken.Contract.Decimals(&_Bancortoken.CallOpts) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() returns(uint8) +func (_Bancortoken *BancortokenCallerSession) Decimals() (uint8, error) { + return _Bancortoken.Contract.Decimals(&_Bancortoken.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenCaller) Name(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "name") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenSession) Name() (string, error) { + return _Bancortoken.Contract.Name(&_Bancortoken.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() returns(string) +func (_Bancortoken *BancortokenCallerSession) Name() (string, error) { + return _Bancortoken.Contract.Name(&_Bancortoken.CallOpts) +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenCaller) NewOwner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "newOwner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenSession) NewOwner() (common.Address, error) { + return _Bancortoken.Contract.NewOwner(&_Bancortoken.CallOpts) +} + +// NewOwner is a free data retrieval call binding the contract method 0xd4ee1d90. +// +// Solidity: function newOwner() returns(address) +func (_Bancortoken *BancortokenCallerSession) NewOwner() (common.Address, error) { + return _Bancortoken.Contract.NewOwner(&_Bancortoken.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenSession) Owner() (common.Address, error) { + return _Bancortoken.Contract.Owner(&_Bancortoken.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() returns(address) +func (_Bancortoken *BancortokenCallerSession) Owner() (common.Address, error) { + return _Bancortoken.Contract.Owner(&_Bancortoken.CallOpts) +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenCaller) Standard(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "standard") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenSession) Standard() (string, error) { + return _Bancortoken.Contract.Standard(&_Bancortoken.CallOpts) +} + +// Standard is a free data retrieval call binding the contract method 0x5a3b7e42. +// +// Solidity: function standard() returns(string) +func (_Bancortoken *BancortokenCallerSession) Standard() (string, error) { + return _Bancortoken.Contract.Standard(&_Bancortoken.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenCaller) Symbol(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "symbol") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenSession) Symbol() (string, error) { + return _Bancortoken.Contract.Symbol(&_Bancortoken.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() returns(string) +func (_Bancortoken *BancortokenCallerSession) Symbol() (string, error) { + return _Bancortoken.Contract.Symbol(&_Bancortoken.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "totalSupply") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenSession) TotalSupply() (*big.Int, error) { + return _Bancortoken.Contract.TotalSupply(&_Bancortoken.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() returns(uint256) +func (_Bancortoken *BancortokenCallerSession) TotalSupply() (*big.Int, error) { + return _Bancortoken.Contract.TotalSupply(&_Bancortoken.CallOpts) +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenCaller) TransfersEnabled(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "transfersEnabled") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenSession) TransfersEnabled() (bool, error) { + return _Bancortoken.Contract.TransfersEnabled(&_Bancortoken.CallOpts) +} + +// TransfersEnabled is a free data retrieval call binding the contract method 0xbef97c87. +// +// Solidity: function transfersEnabled() returns(bool) +func (_Bancortoken *BancortokenCallerSession) TransfersEnabled() (bool, error) { + return _Bancortoken.Contract.TransfersEnabled(&_Bancortoken.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenCaller) Version(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Bancortoken.contract.Call(opts, &out, "version") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenSession) Version() (string, error) { + return _Bancortoken.Contract.Version(&_Bancortoken.CallOpts) +} + +// Version is a free data retrieval call binding the contract method 0x54fd4d50. +// +// Solidity: function version() returns(string) +func (_Bancortoken *BancortokenCallerSession) Version() (string, error) { + return _Bancortoken.Contract.Version(&_Bancortoken.CallOpts) +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenTransactor) AcceptOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "acceptOwnership") +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenSession) AcceptOwnership() (*types.Transaction, error) { + return _Bancortoken.Contract.AcceptOwnership(&_Bancortoken.TransactOpts) +} + +// AcceptOwnership is a paid mutator transaction binding the contract method 0x79ba5097. +// +// Solidity: function acceptOwnership() returns() +func (_Bancortoken *BancortokenTransactorSession) AcceptOwnership() (*types.Transaction, error) { + return _Bancortoken.Contract.AcceptOwnership(&_Bancortoken.TransactOpts) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "approve", _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Approve(&_Bancortoken.TransactOpts, _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Approve(&_Bancortoken.TransactOpts, _spender, _value) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) Destroy(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "destroy", _from, _amount) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) Destroy(_from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Destroy(&_Bancortoken.TransactOpts, _from, _amount) +} + +// Destroy is a paid mutator transaction binding the contract method 0xa24835d1. +// +// Solidity: function destroy(address _from, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) Destroy(_from common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Destroy(&_Bancortoken.TransactOpts, _from, _amount) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenTransactor) DisableTransfers(opts *bind.TransactOpts, _disable bool) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "disableTransfers", _disable) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenSession) DisableTransfers(_disable bool) (*types.Transaction, error) { + return _Bancortoken.Contract.DisableTransfers(&_Bancortoken.TransactOpts, _disable) +} + +// DisableTransfers is a paid mutator transaction binding the contract method 0x1608f18f. +// +// Solidity: function disableTransfers(bool _disable) returns() +func (_Bancortoken *BancortokenTransactorSession) DisableTransfers(_disable bool) (*types.Transaction, error) { + return _Bancortoken.Contract.DisableTransfers(&_Bancortoken.TransactOpts, _disable) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) Issue(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "issue", _to, _amount) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) Issue(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Issue(&_Bancortoken.TransactOpts, _to, _amount) +} + +// Issue is a paid mutator transaction binding the contract method 0x867904b4. +// +// Solidity: function issue(address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) Issue(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Issue(&_Bancortoken.TransactOpts, _to, _amount) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transfer", _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Transfer(&_Bancortoken.TransactOpts, _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.Transfer(&_Bancortoken.TransactOpts, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transferFrom", _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferFrom(&_Bancortoken.TransactOpts, _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool success) +func (_Bancortoken *BancortokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferFrom(&_Bancortoken.TransactOpts, _from, _to, _value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "transferOwnership", _newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenSession) TransferOwnership(_newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferOwnership(&_Bancortoken.TransactOpts, _newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address _newOwner) returns() +func (_Bancortoken *BancortokenTransactorSession) TransferOwnership(_newOwner common.Address) (*types.Transaction, error) { + return _Bancortoken.Contract.TransferOwnership(&_Bancortoken.TransactOpts, _newOwner) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactor) WithdrawTokens(opts *bind.TransactOpts, _token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.contract.Transact(opts, "withdrawTokens", _token, _to, _amount) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenSession) WithdrawTokens(_token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.WithdrawTokens(&_Bancortoken.TransactOpts, _token, _to, _amount) +} + +// WithdrawTokens is a paid mutator transaction binding the contract method 0x5e35359e. +// +// Solidity: function withdrawTokens(address _token, address _to, uint256 _amount) returns() +func (_Bancortoken *BancortokenTransactorSession) WithdrawTokens(_token common.Address, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Bancortoken.Contract.WithdrawTokens(&_Bancortoken.TransactOpts, _token, _to, _amount) +} + +// BancortokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Bancortoken contract. +type BancortokenApprovalIterator struct { + Event *BancortokenApproval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenApproval represents a Approval event raised by the Bancortoken contract. +type BancortokenApproval struct { + Owner common.Address + Spender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) FilterApproval(opts *bind.FilterOpts, _owner []common.Address, _spender []common.Address) (*BancortokenApprovalIterator, error) { + + var _ownerRule []interface{} + for _, _ownerItem := range _owner { + _ownerRule = append(_ownerRule, _ownerItem) + } + var _spenderRule []interface{} + for _, _spenderItem := range _spender { + _spenderRule = append(_spenderRule, _spenderItem) + } + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Approval", _ownerRule, _spenderRule) + if err != nil { + return nil, err + } + return &BancortokenApprovalIterator{contract: _Bancortoken.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *BancortokenApproval, _owner []common.Address, _spender []common.Address) (event.Subscription, error) { + + var _ownerRule []interface{} + for _, _ownerItem := range _owner { + _ownerRule = append(_ownerRule, _ownerItem) + } + var _spenderRule []interface{} + for _, _spenderItem := range _spender { + _spenderRule = append(_spenderRule, _spenderItem) + } + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Approval", _ownerRule, _spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenApproval) + if err := _Bancortoken.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed _owner, address indexed _spender, uint256 _value) +func (_Bancortoken *BancortokenFilterer) ParseApproval(log types.Log) (*BancortokenApproval, error) { + event := new(BancortokenApproval) + if err := _Bancortoken.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenDestructionIterator is returned from FilterDestruction and is used to iterate over the raw logs and unpacked data for Destruction events raised by the Bancortoken contract. +type BancortokenDestructionIterator struct { + Event *BancortokenDestruction // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenDestructionIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenDestruction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenDestruction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenDestructionIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenDestructionIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenDestruction represents a Destruction event raised by the Bancortoken contract. +type BancortokenDestruction struct { + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterDestruction is a free log retrieval operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) FilterDestruction(opts *bind.FilterOpts) (*BancortokenDestructionIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Destruction") + if err != nil { + return nil, err + } + return &BancortokenDestructionIterator{contract: _Bancortoken.contract, event: "Destruction", logs: logs, sub: sub}, nil +} + +// WatchDestruction is a free log subscription operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) WatchDestruction(opts *bind.WatchOpts, sink chan<- *BancortokenDestruction) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Destruction") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenDestruction) + if err := _Bancortoken.contract.UnpackLog(event, "Destruction", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseDestruction is a log parse operation binding the contract event 0x9a1b418bc061a5d80270261562e6986a35d995f8051145f277be16103abd3453. +// +// Solidity: event Destruction(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) ParseDestruction(log types.Log) (*BancortokenDestruction, error) { + event := new(BancortokenDestruction) + if err := _Bancortoken.contract.UnpackLog(event, "Destruction", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenIssuanceIterator is returned from FilterIssuance and is used to iterate over the raw logs and unpacked data for Issuance events raised by the Bancortoken contract. +type BancortokenIssuanceIterator struct { + Event *BancortokenIssuance // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenIssuanceIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenIssuance) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenIssuance) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenIssuanceIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenIssuanceIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenIssuance represents a Issuance event raised by the Bancortoken contract. +type BancortokenIssuance struct { + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterIssuance is a free log retrieval operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) FilterIssuance(opts *bind.FilterOpts) (*BancortokenIssuanceIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Issuance") + if err != nil { + return nil, err + } + return &BancortokenIssuanceIterator{contract: _Bancortoken.contract, event: "Issuance", logs: logs, sub: sub}, nil +} + +// WatchIssuance is a free log subscription operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) WatchIssuance(opts *bind.WatchOpts, sink chan<- *BancortokenIssuance) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Issuance") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenIssuance) + if err := _Bancortoken.contract.UnpackLog(event, "Issuance", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseIssuance is a log parse operation binding the contract event 0x9386c90217c323f58030f9dadcbc938f807a940f4ff41cd4cead9562f5da7dc3. +// +// Solidity: event Issuance(uint256 _amount) +func (_Bancortoken *BancortokenFilterer) ParseIssuance(log types.Log) (*BancortokenIssuance, error) { + event := new(BancortokenIssuance) + if err := _Bancortoken.contract.UnpackLog(event, "Issuance", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenNewSmartTokenIterator is returned from FilterNewSmartToken and is used to iterate over the raw logs and unpacked data for NewSmartToken events raised by the Bancortoken contract. +type BancortokenNewSmartTokenIterator struct { + Event *BancortokenNewSmartToken // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenNewSmartTokenIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenNewSmartToken) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenNewSmartToken) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenNewSmartTokenIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenNewSmartTokenIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenNewSmartToken represents a NewSmartToken event raised by the Bancortoken contract. +type BancortokenNewSmartToken struct { + Token common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNewSmartToken is a free log retrieval operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) FilterNewSmartToken(opts *bind.FilterOpts) (*BancortokenNewSmartTokenIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "NewSmartToken") + if err != nil { + return nil, err + } + return &BancortokenNewSmartTokenIterator{contract: _Bancortoken.contract, event: "NewSmartToken", logs: logs, sub: sub}, nil +} + +// WatchNewSmartToken is a free log subscription operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) WatchNewSmartToken(opts *bind.WatchOpts, sink chan<- *BancortokenNewSmartToken) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "NewSmartToken") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenNewSmartToken) + if err := _Bancortoken.contract.UnpackLog(event, "NewSmartToken", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNewSmartToken is a log parse operation binding the contract event 0xf4cd1f8571e8d9c97ffcb81558807ab73f9803d54de5da6a0420593c82a4a9f0. +// +// Solidity: event NewSmartToken(address _token) +func (_Bancortoken *BancortokenFilterer) ParseNewSmartToken(log types.Log) (*BancortokenNewSmartToken, error) { + event := new(BancortokenNewSmartToken) + if err := _Bancortoken.contract.UnpackLog(event, "NewSmartToken", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenOwnerUpdateIterator is returned from FilterOwnerUpdate and is used to iterate over the raw logs and unpacked data for OwnerUpdate events raised by the Bancortoken contract. +type BancortokenOwnerUpdateIterator struct { + Event *BancortokenOwnerUpdate // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenOwnerUpdateIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenOwnerUpdate) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenOwnerUpdate) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenOwnerUpdateIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenOwnerUpdateIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenOwnerUpdate represents a OwnerUpdate event raised by the Bancortoken contract. +type BancortokenOwnerUpdate struct { + PrevOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnerUpdate is a free log retrieval operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) FilterOwnerUpdate(opts *bind.FilterOpts) (*BancortokenOwnerUpdateIterator, error) { + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "OwnerUpdate") + if err != nil { + return nil, err + } + return &BancortokenOwnerUpdateIterator{contract: _Bancortoken.contract, event: "OwnerUpdate", logs: logs, sub: sub}, nil +} + +// WatchOwnerUpdate is a free log subscription operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) WatchOwnerUpdate(opts *bind.WatchOpts, sink chan<- *BancortokenOwnerUpdate) (event.Subscription, error) { + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "OwnerUpdate") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenOwnerUpdate) + if err := _Bancortoken.contract.UnpackLog(event, "OwnerUpdate", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnerUpdate is a log parse operation binding the contract event 0x343765429aea5a34b3ff6a3785a98a5abb2597aca87bfbb58632c173d585373a. +// +// Solidity: event OwnerUpdate(address _prevOwner, address _newOwner) +func (_Bancortoken *BancortokenFilterer) ParseOwnerUpdate(log types.Log) (*BancortokenOwnerUpdate, error) { + event := new(BancortokenOwnerUpdate) + if err := _Bancortoken.contract.UnpackLog(event, "OwnerUpdate", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// BancortokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Bancortoken contract. +type BancortokenTransferIterator struct { + Event *BancortokenTransfer // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *BancortokenTransferIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(BancortokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(BancortokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *BancortokenTransferIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *BancortokenTransferIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// BancortokenTransfer represents a Transfer event raised by the Bancortoken contract. +type BancortokenTransfer struct { + From common.Address + To common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) FilterTransfer(opts *bind.FilterOpts, _from []common.Address, _to []common.Address) (*BancortokenTransferIterator, error) { + + var _fromRule []interface{} + for _, _fromItem := range _from { + _fromRule = append(_fromRule, _fromItem) + } + var _toRule []interface{} + for _, _toItem := range _to { + _toRule = append(_toRule, _toItem) + } + + logs, sub, err := _Bancortoken.contract.FilterLogs(opts, "Transfer", _fromRule, _toRule) + if err != nil { + return nil, err + } + return &BancortokenTransferIterator{contract: _Bancortoken.contract, event: "Transfer", logs: logs, sub: sub}, nil +} + +// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *BancortokenTransfer, _from []common.Address, _to []common.Address) (event.Subscription, error) { + + var _fromRule []interface{} + for _, _fromItem := range _from { + _fromRule = append(_fromRule, _fromItem) + } + var _toRule []interface{} + for _, _toItem := range _to { + _toRule = append(_toRule, _toItem) + } + + logs, sub, err := _Bancortoken.contract.WatchLogs(opts, "Transfer", _fromRule, _toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(BancortokenTransfer) + if err := _Bancortoken.contract.UnpackLog(event, "Transfer", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed _from, address indexed _to, uint256 _value) +func (_Bancortoken *BancortokenFilterer) ParseTransfer(log types.Log) (*BancortokenTransfer, error) { + event := new(BancortokenTransfer) + if err := _Bancortoken.contract.UnpackLog(event, "Transfer", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} \ No newline at end of file diff --git a/zcnbridge/ethereum/bind.sh b/zcnbridge/ethereum/bind.sh deleted file mode 100755 index 321aa610a..000000000 --- a/zcnbridge/ethereum/bind.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# shellcheck disable=SC2164 -cd ./erc20 -#solc --abi ERC20.sol | awk '/JSON ABI/{x=1;next}x' > erc20.abi -#solc --bin ERC20.sol | awk '/Binary:/{x=1;next}x' > erc20.bin -#abigen --bin=erc20.bin --abi=erc20.abi --pkg=erc20 --out=erc20.go -abigen --pkg erc20 --sol ERC20.sol --out ./erc20.go diff --git a/zcnbridge/ethereum/erc20/Context.sol b/zcnbridge/ethereum/erc20/Context.sol deleted file mode 100644 index 052c09172..000000000 --- a/zcnbridge/ethereum/erc20/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (utils/Context.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/ERC20.sol b/zcnbridge/ethereum/erc20/ERC20.sol deleted file mode 100644 index 308941e6f..000000000 --- a/zcnbridge/ethereum/erc20/ERC20.sol +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; -import "./IERC20Metadata.sol"; -import "./Context.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20, IERC20Metadata { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Sets the values for {name} and {symbol}. - * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual override returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * Requirements: - * - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for ``sender``'s tokens of at least - * `amount`. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) public virtual override returns (bool) { - _transfer(sender, recipient, amount); - - uint256 currentAllowance = _allowances[sender][_msgSender()]; - require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); - unchecked { - _approve(sender, _msgSender(), currentAllowance - amount); - } - - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - uint256 currentAllowance = _allowances[_msgSender()][spender]; - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(_msgSender(), spender, currentAllowance - subtractedValue); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `sender` to `recipient`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(sender, recipient, amount); - - uint256 senderBalance = _balances[sender]; - require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[sender] = senderBalance - amount; - } - _balances[recipient] += amount; - - emit Transfer(sender, recipient, amount); - - _afterTokenTransfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - _balances[account] += amount; - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - } - _totalSupply -= amount; - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/IERC20.sol b/zcnbridge/ethereum/erc20/IERC20.sol deleted file mode 100644 index 014b5706d..000000000 --- a/zcnbridge/ethereum/erc20/IERC20.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address recipient, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/IERC20Metadata.sol b/zcnbridge/ethereum/erc20/IERC20Metadata.sol deleted file mode 100644 index 3f8166f0d..000000000 --- a/zcnbridge/ethereum/erc20/IERC20Metadata.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/extensions/IERC20Metadata.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} \ No newline at end of file diff --git a/zcnbridge/ethereum/erc20/erc20.go b/zcnbridge/ethereum/erc20/erc20.go deleted file mode 100644 index 064174d8a..000000000 --- a/zcnbridge/ethereum/erc20/erc20.go +++ /dev/null @@ -1,2319 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package erc20 - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// ContextMetaData contains all meta data concerning the Context contract. -var ContextMetaData = &bind.MetaData{ - ABI: "[]", -} - -// ContextABI is the input ABI used to generate the binding from. -// Deprecated: Use ContextMetaData.ABI instead. -var ContextABI = ContextMetaData.ABI - -// Context is an auto generated Go binding around an Ethereum contract. -type Context struct { - ContextCaller // Read-only binding to the contract - ContextTransactor // Write-only binding to the contract - ContextFilterer // Log filterer for contract events -} - -// ContextCaller is an auto generated read-only Go binding around an Ethereum contract. -type ContextCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ContextTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ContextFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ContextSession struct { - Contract *Context // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ContextCallerSession struct { - Contract *ContextCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ContextTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ContextTransactorSession struct { - Contract *ContextTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextRaw is an auto generated low-level Go binding around an Ethereum contract. -type ContextRaw struct { - Contract *Context // Generic contract binding to access the raw methods on -} - -// ContextCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ContextCallerRaw struct { - Contract *ContextCaller // Generic read-only contract binding to access the raw methods on -} - -// ContextTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ContextTransactorRaw struct { - Contract *ContextTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewContext creates a new instance of Context, bound to a specific deployed contract. -func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) { - contract, err := bindContext(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil -} - -// NewContextCaller creates a new read-only instance of Context, bound to a specific deployed contract. -func NewContextCaller(address common.Address, caller bind.ContractCaller) (*ContextCaller, error) { - contract, err := bindContext(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ContextCaller{contract: contract}, nil -} - -// NewContextTransactor creates a new write-only instance of Context, bound to a specific deployed contract. -func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) { - contract, err := bindContext(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ContextTransactor{contract: contract}, nil -} - -// NewContextFilterer creates a new log filterer instance of Context, bound to a specific deployed contract. -func NewContextFilterer(address common.Address, filterer bind.ContractFilterer) (*ContextFilterer, error) { - contract, err := bindContext(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ContextFilterer{contract: contract}, nil -} - -// bindContext binds a generic wrapper to an already deployed contract. -func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ContextABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.ContextCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.contract.Transact(opts, method, params...) -} - -// ERC20MetaData contains all meta data concerning the ERC20 contract. -var ERC20MetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "a457c2d7": "decreaseAllowance(address,uint256)", - "39509351": "increaseAllowance(address,uint256)", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, - Bin: "0x60806040523480156200001157600080fd5b5060405162000b5638038062000b568339810160408190526200003491620001db565b81516200004990600390602085019062000068565b5080516200005f90600490602084019062000068565b50505062000282565b828054620000769062000245565b90600052602060002090601f0160209004810192826200009a5760008555620000e5565b82601f10620000b557805160ff1916838001178555620000e5565b82800160010185558215620000e5579182015b82811115620000e5578251825591602001919060010190620000c8565b50620000f3929150620000f7565b5090565b5b80821115620000f35760008155600101620000f8565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200013657600080fd5b81516001600160401b03808211156200015357620001536200010e565b604051601f8301601f19908116603f011681019082821181831017156200017e576200017e6200010e565b816040528381526020925086838588010111156200019b57600080fd5b600091505b83821015620001bf5785820183015181830184015290820190620001a0565b83821115620001d15760008385830101525b9695505050505050565b60008060408385031215620001ef57600080fd5b82516001600160401b03808211156200020757600080fd5b620002158683870162000124565b935060208501519150808211156200022c57600080fd5b506200023b8582860162000124565b9150509250929050565b600181811c908216806200025a57607f821691505b602082108114156200027c57634e487b7160e01b600052602260045260246000fd5b50919050565b6108c480620002926000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461012357806370a082311461013657806395d89b411461015f578063a457c2d714610167578063a9059cbb1461017a578063dd62ed3e1461018d57600080fd5b806306fdde03146100ae578063095ea7b3146100cc57806318160ddd146100ef57806323b872dd14610101578063313ce56714610114575b600080fd5b6100b66101c6565b6040516100c39190610701565b60405180910390f35b6100df6100da366004610772565b610258565b60405190151581526020016100c3565b6002545b6040519081526020016100c3565b6100df61010f36600461079c565b61026e565b604051601281526020016100c3565b6100df610131366004610772565b61031d565b6100f36101443660046107d8565b6001600160a01b031660009081526020819052604090205490565b6100b6610359565b6100df610175366004610772565b610368565b6100df610188366004610772565b610401565b6100f361019b3660046107fa565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6060600380546101d59061082d565b80601f01602080910402602001604051908101604052809291908181526020018280546102019061082d565b801561024e5780601f106102235761010080835404028352916020019161024e565b820191906000526020600020905b81548152906001019060200180831161023157829003601f168201915b5050505050905090565b600061026533848461040e565b50600192915050565b600061027b848484610532565b6001600160a01b0384166000908152600160209081526040808320338452909152902054828110156103055760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e74206578636565647320616044820152676c6c6f77616e636560c01b60648201526084015b60405180910390fd5b610312853385840361040e565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091610265918590610354908690610868565b61040e565b6060600480546101d59061082d565b3360009081526001602090815260408083206001600160a01b0386168452909152812054828110156103ea5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016102fc565b6103f7338585840361040e565b5060019392505050565b6000610265338484610532565b6001600160a01b0383166104705760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016102fc565b6001600160a01b0382166104d15760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016102fc565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166105965760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016102fc565b6001600160a01b0382166105f85760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016102fc565b6001600160a01b038316600090815260208190526040902054818110156106705760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016102fc565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906106a7908490610868565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516106f391815260200190565b60405180910390a350505050565b600060208083528351808285015260005b8181101561072e57858101830151858201604001528201610712565b81811115610740576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b038116811461076d57600080fd5b919050565b6000806040838503121561078557600080fd5b61078e83610756565b946020939093013593505050565b6000806000606084860312156107b157600080fd5b6107ba84610756565b92506107c860208501610756565b9150604084013590509250925092565b6000602082840312156107ea57600080fd5b6107f382610756565b9392505050565b6000806040838503121561080d57600080fd5b61081683610756565b915061082460208401610756565b90509250929050565b600181811c9082168061084157607f821691505b6020821081141561086257634e487b7160e01b600052602260045260246000fd5b50919050565b6000821982111561088957634e487b7160e01b600052601160045260246000fd5b50019056fea26469706673582212203a382710d330bfc5c08286d13b123167071c03a623c45f800ccb995904d07eef64736f6c63430008090033", -} - -// ERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use ERC20MetaData.ABI instead. -var ERC20ABI = ERC20MetaData.ABI - -// Deprecated: Use ERC20MetaData.Sigs instead. -// ERC20FuncSigs maps the 4-byte function signature to its string representation. -var ERC20FuncSigs = ERC20MetaData.Sigs - -// ERC20Bin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use ERC20MetaData.Bin instead. -var ERC20Bin = ERC20MetaData.Bin - -// DeployERC20 deploys a new Ethereum contract, binding an instance of ERC20 to it. -func DeployERC20(auth *bind.TransactOpts, backend bind.ContractBackend, name_ string, symbol_ string) (common.Address, *types.Transaction, *ERC20, error) { - parsed, err := ERC20MetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(ERC20Bin), backend, name_, symbol_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// ERC20 is an auto generated Go binding around an Ethereum contract. -type ERC20 struct { - ERC20Caller // Read-only binding to the contract - ERC20Transactor // Write-only binding to the contract - ERC20Filterer // Log filterer for contract events -} - -// ERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type ERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type ERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ERC20Session struct { - Contract *ERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ERC20CallerSession struct { - Contract *ERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ERC20TransactorSession struct { - Contract *ERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type ERC20Raw struct { - Contract *ERC20 // Generic contract binding to access the raw methods on -} - -// ERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ERC20CallerRaw struct { - Contract *ERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// ERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ERC20TransactorRaw struct { - Contract *ERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewERC20 creates a new instance of ERC20, bound to a specific deployed contract. -func NewERC20(address common.Address, backend bind.ContractBackend) (*ERC20, error) { - contract, err := bindERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// NewERC20Caller creates a new read-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Caller(address common.Address, caller bind.ContractCaller) (*ERC20Caller, error) { - contract, err := bindERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ERC20Caller{contract: contract}, nil -} - -// NewERC20Transactor creates a new write-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*ERC20Transactor, error) { - contract, err := bindERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ERC20Transactor{contract: contract}, nil -} - -// NewERC20Filterer creates a new log filterer instance of ERC20, bound to a specific deployed contract. -func NewERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*ERC20Filterer, error) { - contract, err := bindERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ERC20Filterer{contract: contract}, nil -} - -// bindERC20 binds a generic wrapper to an already deployed contract. -func bindERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.ERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Caller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Session) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20CallerSession) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Caller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Session) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20CallerSession) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Caller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Session) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20CallerSession) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Session) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20CallerSession) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Transactor) DecreaseAllowance(opts *bind.TransactOpts, spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "decreaseAllowance", spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Session) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "increaseAllowance", spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Session) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// ERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the ERC20 contract. -type ERC20ApprovalIterator struct { - Event *ERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Approval represents a Approval event raised by the ERC20 contract. -type ERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*ERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &ERC20ApprovalIterator{contract: _ERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *ERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) ParseApproval(log types.Log) (*ERC20Approval, error) { - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// ERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the ERC20 contract. -type ERC20TransferIterator struct { - Event *ERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Transfer represents a Transfer event raised by the ERC20 contract. -type ERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*ERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &ERC20TransferIterator{contract: _ERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) ParseTransfer(log types.Log) (*ERC20Transfer, error) { - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetaData contains all meta data concerning the IERC20 contract. -var IERC20MetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetaData.ABI instead. -var IERC20ABI = IERC20MetaData.ABI - -// Deprecated: Use IERC20MetaData.Sigs instead. -// IERC20FuncSigs maps the 4-byte function signature to its string representation. -var IERC20FuncSigs = IERC20MetaData.Sigs - -// IERC20 is an auto generated Go binding around an Ethereum contract. -type IERC20 struct { - IERC20Caller // Read-only binding to the contract - IERC20Transactor // Write-only binding to the contract - IERC20Filterer // Log filterer for contract events -} - -// IERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20Session struct { - Contract *IERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20CallerSession struct { - Contract *IERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20TransactorSession struct { - Contract *IERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20Raw struct { - Contract *IERC20 // Generic contract binding to access the raw methods on -} - -// IERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20CallerRaw struct { - Contract *IERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// IERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20TransactorRaw struct { - Contract *IERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20 creates a new instance of IERC20, bound to a specific deployed contract. -func NewIERC20(address common.Address, backend bind.ContractBackend) (*IERC20, error) { - contract, err := bindIERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20{IERC20Caller: IERC20Caller{contract: contract}, IERC20Transactor: IERC20Transactor{contract: contract}, IERC20Filterer: IERC20Filterer{contract: contract}}, nil -} - -// NewIERC20Caller creates a new read-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Caller(address common.Address, caller bind.ContractCaller) (*IERC20Caller, error) { - contract, err := bindIERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20Caller{contract: contract}, nil -} - -// NewIERC20Transactor creates a new write-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*IERC20Transactor, error) { - contract, err := bindIERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20Transactor{contract: contract}, nil -} - -// NewIERC20Filterer creates a new log filterer instance of IERC20, bound to a specific deployed contract. -func NewIERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*IERC20Filterer, error) { - contract, err := bindIERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20Filterer{contract: contract}, nil -} - -// bindIERC20 binds a generic wrapper to an already deployed contract. -func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.IERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Session) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20CallerSession) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// IERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20 contract. -type IERC20ApprovalIterator struct { - Event *IERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Approval represents a Approval event raised by the IERC20 contract. -type IERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20ApprovalIterator{contract: _IERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) ParseApproval(log types.Log) (*IERC20Approval, error) { - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20 contract. -type IERC20TransferIterator struct { - Event *IERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Transfer represents a Transfer event raised by the IERC20 contract. -type IERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20TransferIterator{contract: _IERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) ParseTransfer(log types.Log) (*IERC20Transfer, error) { - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataMetaData contains all meta data concerning the IERC20Metadata contract. -var IERC20MetadataMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20MetadataABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetadataMetaData.ABI instead. -var IERC20MetadataABI = IERC20MetadataMetaData.ABI - -// Deprecated: Use IERC20MetadataMetaData.Sigs instead. -// IERC20MetadataFuncSigs maps the 4-byte function signature to its string representation. -var IERC20MetadataFuncSigs = IERC20MetadataMetaData.Sigs - -// IERC20Metadata is an auto generated Go binding around an Ethereum contract. -type IERC20Metadata struct { - IERC20MetadataCaller // Read-only binding to the contract - IERC20MetadataTransactor // Write-only binding to the contract - IERC20MetadataFilterer // Log filterer for contract events -} - -// IERC20MetadataCaller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20MetadataCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20MetadataFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20MetadataSession struct { - Contract *IERC20Metadata // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20MetadataCallerSession struct { - Contract *IERC20MetadataCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20MetadataTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20MetadataTransactorSession struct { - Contract *IERC20MetadataTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataRaw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20MetadataRaw struct { - Contract *IERC20Metadata // Generic contract binding to access the raw methods on -} - -// IERC20MetadataCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20MetadataCallerRaw struct { - Contract *IERC20MetadataCaller // Generic read-only contract binding to access the raw methods on -} - -// IERC20MetadataTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactorRaw struct { - Contract *IERC20MetadataTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20Metadata creates a new instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20Metadata(address common.Address, backend bind.ContractBackend) (*IERC20Metadata, error) { - contract, err := bindIERC20Metadata(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20Metadata{IERC20MetadataCaller: IERC20MetadataCaller{contract: contract}, IERC20MetadataTransactor: IERC20MetadataTransactor{contract: contract}, IERC20MetadataFilterer: IERC20MetadataFilterer{contract: contract}}, nil -} - -// NewIERC20MetadataCaller creates a new read-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataCaller(address common.Address, caller bind.ContractCaller) (*IERC20MetadataCaller, error) { - contract, err := bindIERC20Metadata(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataCaller{contract: contract}, nil -} - -// NewIERC20MetadataTransactor creates a new write-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataTransactor(address common.Address, transactor bind.ContractTransactor) (*IERC20MetadataTransactor, error) { - contract, err := bindIERC20Metadata(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataTransactor{contract: contract}, nil -} - -// NewIERC20MetadataFilterer creates a new log filterer instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataFilterer(address common.Address, filterer bind.ContractFilterer) (*IERC20MetadataFilterer, error) { - contract, err := bindIERC20Metadata(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20MetadataFilterer{contract: contract}, nil -} - -// bindIERC20Metadata binds a generic wrapper to an already deployed contract. -func bindIERC20Metadata(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20MetadataABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.IERC20MetadataCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCallerSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// IERC20MetadataApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20Metadata contract. -type IERC20MetadataApprovalIterator struct { - Event *IERC20MetadataApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataApproval represents a Approval event raised by the IERC20Metadata contract. -type IERC20MetadataApproval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20MetadataApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20MetadataApprovalIterator{contract: _IERC20Metadata.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20MetadataApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseApproval(log types.Log) (*IERC20MetadataApproval, error) { - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20Metadata contract. -type IERC20MetadataTransferIterator struct { - Event *IERC20MetadataTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataTransfer represents a Transfer event raised by the IERC20Metadata contract. -type IERC20MetadataTransfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20MetadataTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20MetadataTransferIterator{contract: _IERC20Metadata.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20MetadataTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseTransfer(log types.Log) (*IERC20MetadataTransfer, error) { - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnbridge/ethereum/nftconfig/nftconfig.go b/zcnbridge/ethereum/nftconfig/nftconfig.go new file mode 100644 index 000000000..2961f9fce --- /dev/null +++ b/zcnbridge/ethereum/nftconfig/nftconfig.go @@ -0,0 +1,656 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package nftconfig + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription +) + +// NFTConfigMetaData contains all meta data concerning the NFTConfig contract. +var NFTConfigMetaData = &bind.MetaData{ + ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"previous\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"updated\",\"type\":\"uint256\"}],\"name\":\"ConfigUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"setUint256\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"value\",\"type\":\"address\"}],\"name\":\"setAddress\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getUint256\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"key\",\"type\":\"bytes32\"}],\"name\":\"getAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\",\"constant\":true}]", +} + +// NFTConfigABI is the input ABI used to generate the binding from. +// Deprecated: Use NFTConfigMetaData.ABI instead. +var NFTConfigABI = NFTConfigMetaData.ABI + +// NFTConfig is an auto generated Go binding around an Ethereum contract. +type NFTConfig struct { + NFTConfigCaller // Read-only binding to the contract + NFTConfigTransactor // Write-only binding to the contract + NFTConfigFilterer // Log filterer for contract events +} + +// NFTConfigCaller is an auto generated read-only Go binding around an Ethereum contract. +type NFTConfigCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigTransactor is an auto generated write-only Go binding around an Ethereum contract. +type NFTConfigTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type NFTConfigFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// NFTConfigSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type NFTConfigSession struct { + Contract *NFTConfig // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// NFTConfigCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type NFTConfigCallerSession struct { + Contract *NFTConfigCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// NFTConfigTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type NFTConfigTransactorSession struct { + Contract *NFTConfigTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// NFTConfigRaw is an auto generated low-level Go binding around an Ethereum contract. +type NFTConfigRaw struct { + Contract *NFTConfig // Generic contract binding to access the raw methods on +} + +// NFTConfigCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type NFTConfigCallerRaw struct { + Contract *NFTConfigCaller // Generic read-only contract binding to access the raw methods on +} + +// NFTConfigTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type NFTConfigTransactorRaw struct { + Contract *NFTConfigTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewNFTConfig creates a new instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfig(address common.Address, backend bind.ContractBackend) (*NFTConfig, error) { + contract, err := bindNFTConfig(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &NFTConfig{NFTConfigCaller: NFTConfigCaller{contract: contract}, NFTConfigTransactor: NFTConfigTransactor{contract: contract}, NFTConfigFilterer: NFTConfigFilterer{contract: contract}}, nil +} + +// NewNFTConfigCaller creates a new read-only instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigCaller(address common.Address, caller bind.ContractCaller) (*NFTConfigCaller, error) { + contract, err := bindNFTConfig(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &NFTConfigCaller{contract: contract}, nil +} + +// NewNFTConfigTransactor creates a new write-only instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigTransactor(address common.Address, transactor bind.ContractTransactor) (*NFTConfigTransactor, error) { + contract, err := bindNFTConfig(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &NFTConfigTransactor{contract: contract}, nil +} + +// NewNFTConfigFilterer creates a new log filterer instance of NFTConfig, bound to a specific deployed contract. +func NewNFTConfigFilterer(address common.Address, filterer bind.ContractFilterer) (*NFTConfigFilterer, error) { + contract, err := bindNFTConfig(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &NFTConfigFilterer{contract: contract}, nil +} + +// bindNFTConfig binds a generic wrapper to an already deployed contract. +func bindNFTConfig(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := abi.JSON(strings.NewReader(NFTConfigABI)) + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_NFTConfig *NFTConfigRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _NFTConfig.Contract.NFTConfigCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_NFTConfig *NFTConfigRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.Contract.NFTConfigTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_NFTConfig *NFTConfigRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _NFTConfig.Contract.NFTConfigTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_NFTConfig *NFTConfigCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _NFTConfig.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_NFTConfig *NFTConfigTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_NFTConfig *NFTConfigTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _NFTConfig.Contract.contract.Transact(opts, method, params...) +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigCaller) GetAddress(opts *bind.CallOpts, key [32]byte) (common.Address, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "getAddress", key) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigSession) GetAddress(key [32]byte) (common.Address, error) { + return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) +} + +// GetAddress is a free data retrieval call binding the contract method 0x21f8a721. +// +// Solidity: function getAddress(bytes32 key) view returns(address) +func (_NFTConfig *NFTConfigCallerSession) GetAddress(key [32]byte) (common.Address, error) { + return _NFTConfig.Contract.GetAddress(&_NFTConfig.CallOpts, key) +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigCaller) GetUint256(opts *bind.CallOpts, key [32]byte) (*big.Int, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "getUint256", key) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigSession) GetUint256(key [32]byte) (*big.Int, error) { + return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) +} + +// GetUint256 is a free data retrieval call binding the contract method 0x33598b00. +// +// Solidity: function getUint256(bytes32 key) view returns(uint256) +func (_NFTConfig *NFTConfigCallerSession) GetUint256(key [32]byte) (*big.Int, error) { + return _NFTConfig.Contract.GetUint256(&_NFTConfig.CallOpts, key) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _NFTConfig.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigSession) Owner() (common.Address, error) { + return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_NFTConfig *NFTConfigCallerSession) Owner() (common.Address, error) { + return _NFTConfig.Contract.Owner(&_NFTConfig.CallOpts) +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "renounceOwnership") +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigSession) RenounceOwnership() (*types.Transaction, error) { + return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) +} + +// RenounceOwnership is a paid mutator transaction binding the contract method 0x715018a6. +// +// Solidity: function renounceOwnership() returns() +func (_NFTConfig *NFTConfigTransactorSession) RenounceOwnership() (*types.Transaction, error) { + return _NFTConfig.Contract.RenounceOwnership(&_NFTConfig.TransactOpts) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigTransactor) SetAddress(opts *bind.TransactOpts, key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "setAddress", key, value) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) +} + +// SetAddress is a paid mutator transaction binding the contract method 0xca446dd9. +// +// Solidity: function setAddress(bytes32 key, address value) returns() +func (_NFTConfig *NFTConfigTransactorSession) SetAddress(key [32]byte, value common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.SetAddress(&_NFTConfig.TransactOpts, key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigTransactor) SetUint256(opts *bind.TransactOpts, key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "setUint256", key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) +} + +// SetUint256 is a paid mutator transaction binding the contract method 0x4f3029c2. +// +// Solidity: function setUint256(bytes32 key, uint256 value) returns() +func (_NFTConfig *NFTConfigTransactorSession) SetUint256(key [32]byte, value *big.Int) (*types.Transaction, error) { + return _NFTConfig.Contract.SetUint256(&_NFTConfig.TransactOpts, key, value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.contract.Transact(opts, "transferOwnership", newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_NFTConfig *NFTConfigTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _NFTConfig.Contract.TransferOwnership(&_NFTConfig.TransactOpts, newOwner) +} + +// NFTConfigConfigUpdatedIterator is returned from FilterConfigUpdated and is used to iterate over the raw logs and unpacked data for ConfigUpdated events raised by the NFTConfig contract. +type NFTConfigConfigUpdatedIterator struct { + Event *NFTConfigConfigUpdated // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *NFTConfigConfigUpdatedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(NFTConfigConfigUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(NFTConfigConfigUpdated) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *NFTConfigConfigUpdatedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *NFTConfigConfigUpdatedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// NFTConfigConfigUpdated represents a ConfigUpdated event raised by the NFTConfig contract. +type NFTConfigConfigUpdated struct { + Key [32]byte + Previous *big.Int + Updated *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterConfigUpdated is a free log retrieval operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) FilterConfigUpdated(opts *bind.FilterOpts, key [][32]byte) (*NFTConfigConfigUpdatedIterator, error) { + + var keyRule []interface{} + for _, keyItem := range key { + keyRule = append(keyRule, keyItem) + } + + logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "ConfigUpdated", keyRule) + if err != nil { + return nil, err + } + return &NFTConfigConfigUpdatedIterator{contract: _NFTConfig.contract, event: "ConfigUpdated", logs: logs, sub: sub}, nil +} + +// WatchConfigUpdated is a free log subscription operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) WatchConfigUpdated(opts *bind.WatchOpts, sink chan<- *NFTConfigConfigUpdated, key [][32]byte) (event.Subscription, error) { + + var keyRule []interface{} + for _, keyItem := range key { + keyRule = append(keyRule, keyItem) + } + + logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "ConfigUpdated", keyRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(NFTConfigConfigUpdated) + if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseConfigUpdated is a log parse operation binding the contract event 0xac2ccce3de9c0816ae772598f7f65fe69f9893b637f7c490497378cbb3ea043e. +// +// Solidity: event ConfigUpdated(bytes32 indexed key, uint256 previous, uint256 updated) +func (_NFTConfig *NFTConfigFilterer) ParseConfigUpdated(log types.Log) (*NFTConfigConfigUpdated, error) { + event := new(NFTConfigConfigUpdated) + if err := _NFTConfig.contract.UnpackLog(event, "ConfigUpdated", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// NFTConfigOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the NFTConfig contract. +type NFTConfigOwnershipTransferredIterator struct { + Event *NFTConfigOwnershipTransferred // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *NFTConfigOwnershipTransferredIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(NFTConfigOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(NFTConfigOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *NFTConfigOwnershipTransferredIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *NFTConfigOwnershipTransferredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// NFTConfigOwnershipTransferred represents a OwnershipTransferred event raised by the NFTConfig contract. +type NFTConfigOwnershipTransferred struct { + PreviousOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*NFTConfigOwnershipTransferredIterator, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _NFTConfig.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return &NFTConfigOwnershipTransferredIterator{contract: _NFTConfig.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil +} + +// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *NFTConfigOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _NFTConfig.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(NFTConfigOwnershipTransferred) + if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_NFTConfig *NFTConfigFilterer) ParseOwnershipTransferred(log types.Log) (*NFTConfigOwnershipTransferred, error) { + event := new(NFTConfigOwnershipTransferred) + if err := _NFTConfig.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/zcnbridge/ethereum/zcntoken/zcntoken.go b/zcnbridge/ethereum/zcntoken/zcntoken.go new file mode 100644 index 000000000..0caf78343 --- /dev/null +++ b/zcnbridge/ethereum/zcntoken/zcntoken.go @@ -0,0 +1,1336 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package zcntoken + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// TokenMetaData contains all meta data concerning the Token contract. +var TokenMetaData = &bind.MetaData{ + ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"mintingFinished\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"finishMinting\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseApproval\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"MintFinished\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]", +} + +// TokenABI is the input ABI used to generate the binding from. +// Deprecated: Use TokenMetaData.ABI instead. +var TokenABI = TokenMetaData.ABI + +// Token is an auto generated Go binding around an Ethereum contract. +type Token struct { + TokenCaller // Read-only binding to the contract + TokenTransactor // Write-only binding to the contract + TokenFilterer // Log filterer for contract events +} + +// TokenCaller is an auto generated read-only Go binding around an Ethereum contract. +type TokenCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenTransactor is an auto generated write-only Go binding around an Ethereum contract. +type TokenTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type TokenFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type TokenSession struct { + Contract *Token // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type TokenCallerSession struct { + Contract *TokenCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// TokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type TokenTransactorSession struct { + Contract *TokenTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenRaw is an auto generated low-level Go binding around an Ethereum contract. +type TokenRaw struct { + Contract *Token // Generic contract binding to access the raw methods on +} + +// TokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type TokenCallerRaw struct { + Contract *TokenCaller // Generic read-only contract binding to access the raw methods on +} + +// TokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type TokenTransactorRaw struct { + Contract *TokenTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewToken creates a new instance of Token, bound to a specific deployed contract. +func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) { + contract, err := bindToken(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil +} + +// NewTokenCaller creates a new read-only instance of Token, bound to a specific deployed contract. +func NewTokenCaller(address common.Address, caller bind.ContractCaller) (*TokenCaller, error) { + contract, err := bindToken(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &TokenCaller{contract: contract}, nil +} + +// NewTokenTransactor creates a new write-only instance of Token, bound to a specific deployed contract. +func NewTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*TokenTransactor, error) { + contract, err := bindToken(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &TokenTransactor{contract: contract}, nil +} + +// NewTokenFilterer creates a new log filterer instance of Token, bound to a specific deployed contract. +func NewTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*TokenFilterer, error) { + contract, err := bindToken(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &TokenFilterer{contract: contract}, nil +} + +// bindToken binds a generic wrapper to an already deployed contract. +func bindToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := TokenMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.TokenCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.contract.Transact(opts, method, params...) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCaller) Allowance(opts *bind.CallOpts, _owner common.Address, _spender common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "allowance", _owner, _spender) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCallerSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "balanceOf", _owner) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "decimals") + + if err != nil { + return *new(uint8), err + } + + out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) + + return out0, err + +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCallerSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenCaller) MintingFinished(opts *bind.CallOpts) (bool, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "mintingFinished") + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenSession) MintingFinished() (bool, error) { + return _Token.Contract.MintingFinished(&_Token.CallOpts) +} + +// MintingFinished is a free data retrieval call binding the contract method 0x05d2035b. +// +// Solidity: function mintingFinished() view returns(bool) +func (_Token *TokenCallerSession) MintingFinished() (bool, error) { + return _Token.Contract.MintingFinished(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCaller) Name(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "name") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCallerSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenSession) Owner() (common.Address, error) { + return _Token.Contract.Owner(&_Token.CallOpts) +} + +// Owner is a free data retrieval call binding the contract method 0x8da5cb5b. +// +// Solidity: function owner() view returns(address) +func (_Token *TokenCallerSession) Owner() (common.Address, error) { + return _Token.Contract.Owner(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCaller) Symbol(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "symbol") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCallerSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "totalSupply") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. +// +// Solidity: function totalSupply() view returns(uint256) +func (_Token *TokenCallerSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "approve", _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenTransactor) DecreaseApproval(opts *bind.TransactOpts, _spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "decreaseApproval", _spender, _subtractedValue) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) +} + +// DecreaseApproval is a paid mutator transaction binding the contract method 0x66188463. +// +// Solidity: function decreaseApproval(address _spender, uint256 _subtractedValue) returns(bool) +func (_Token *TokenTransactorSession) DecreaseApproval(_spender common.Address, _subtractedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.DecreaseApproval(&_Token.TransactOpts, _spender, _subtractedValue) +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenTransactor) FinishMinting(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "finishMinting") +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenSession) FinishMinting() (*types.Transaction, error) { + return _Token.Contract.FinishMinting(&_Token.TransactOpts) +} + +// FinishMinting is a paid mutator transaction binding the contract method 0x7d64bcb4. +// +// Solidity: function finishMinting() returns(bool) +func (_Token *TokenTransactorSession) FinishMinting() (*types.Transaction, error) { + return _Token.Contract.FinishMinting(&_Token.TransactOpts) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenTransactor) IncreaseApproval(opts *bind.TransactOpts, _spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "increaseApproval", _spender, _addedValue) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) +} + +// IncreaseApproval is a paid mutator transaction binding the contract method 0xd73dd623. +// +// Solidity: function increaseApproval(address _spender, uint256 _addedValue) returns(bool) +func (_Token *TokenTransactorSession) IncreaseApproval(_spender common.Address, _addedValue *big.Int) (*types.Transaction, error) { + return _Token.Contract.IncreaseApproval(&_Token.TransactOpts, _spender, _addedValue) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "mint", _to, _amount) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) +} + +// Mint is a paid mutator transaction binding the contract method 0x40c10f19. +// +// Solidity: function mint(address _to, uint256 _amount) returns(bool) +func (_Token *TokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) { + return _Token.Contract.Mint(&_Token.TransactOpts, _to, _amount) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transfer", _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transferFrom", _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transferOwnership", newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) +} + +// TransferOwnership is a paid mutator transaction binding the contract method 0xf2fde38b. +// +// Solidity: function transferOwnership(address newOwner) returns() +func (_Token *TokenTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) { + return _Token.Contract.TransferOwnership(&_Token.TransactOpts, newOwner) +} + +// TokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Token contract. +type TokenApprovalIterator struct { + Event *TokenApproval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenApproval represents a Approval event raised by the Token contract. +type TokenApproval struct { + Owner common.Address + Spender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*TokenApprovalIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return &TokenApprovalIterator{contract: _Token.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *TokenApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) ParseApproval(log types.Log) (*TokenApproval, error) { + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenMintIterator is returned from FilterMint and is used to iterate over the raw logs and unpacked data for Mint events raised by the Token contract. +type TokenMintIterator struct { + Event *TokenMint // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenMintIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenMint) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenMint) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenMintIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenMintIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenMint represents a Mint event raised by the Token contract. +type TokenMint struct { + To common.Address + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterMint is a free log retrieval operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) FilterMint(opts *bind.FilterOpts, to []common.Address) (*TokenMintIterator, error) { + + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Mint", toRule) + if err != nil { + return nil, err + } + return &TokenMintIterator{contract: _Token.contract, event: "Mint", logs: logs, sub: sub}, nil +} + +// WatchMint is a free log subscription operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) WatchMint(opts *bind.WatchOpts, sink chan<- *TokenMint, to []common.Address) (event.Subscription, error) { + + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Mint", toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenMint) + if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseMint is a log parse operation binding the contract event 0x0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d4121396885. +// +// Solidity: event Mint(address indexed to, uint256 amount) +func (_Token *TokenFilterer) ParseMint(log types.Log) (*TokenMint, error) { + event := new(TokenMint) + if err := _Token.contract.UnpackLog(event, "Mint", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenMintFinishedIterator is returned from FilterMintFinished and is used to iterate over the raw logs and unpacked data for MintFinished events raised by the Token contract. +type TokenMintFinishedIterator struct { + Event *TokenMintFinished // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenMintFinishedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenMintFinished) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenMintFinished) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenMintFinishedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenMintFinishedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenMintFinished represents a MintFinished event raised by the Token contract. +type TokenMintFinished struct { + Raw types.Log // Blockchain specific contextual infos +} + +// FilterMintFinished is a free log retrieval operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) FilterMintFinished(opts *bind.FilterOpts) (*TokenMintFinishedIterator, error) { + + logs, sub, err := _Token.contract.FilterLogs(opts, "MintFinished") + if err != nil { + return nil, err + } + return &TokenMintFinishedIterator{contract: _Token.contract, event: "MintFinished", logs: logs, sub: sub}, nil +} + +// WatchMintFinished is a free log subscription operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) WatchMintFinished(opts *bind.WatchOpts, sink chan<- *TokenMintFinished) (event.Subscription, error) { + + logs, sub, err := _Token.contract.WatchLogs(opts, "MintFinished") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenMintFinished) + if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseMintFinished is a log parse operation binding the contract event 0xae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa08. +// +// Solidity: event MintFinished() +func (_Token *TokenFilterer) ParseMintFinished(log types.Log) (*TokenMintFinished, error) { + event := new(TokenMintFinished) + if err := _Token.contract.UnpackLog(event, "MintFinished", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenOwnershipTransferredIterator is returned from FilterOwnershipTransferred and is used to iterate over the raw logs and unpacked data for OwnershipTransferred events raised by the Token contract. +type TokenOwnershipTransferredIterator struct { + Event *TokenOwnershipTransferred // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenOwnershipTransferredIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenOwnershipTransferredIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenOwnershipTransferredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenOwnershipTransferred represents a OwnershipTransferred event raised by the Token contract. +type TokenOwnershipTransferred struct { + PreviousOwner common.Address + NewOwner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnershipTransferred is a free log retrieval operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*TokenOwnershipTransferredIterator, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return &TokenOwnershipTransferredIterator{contract: _Token.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil +} + +// WatchOwnershipTransferred is a free log subscription operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *TokenOwnershipTransferred, previousOwner []common.Address, newOwner []common.Address) (event.Subscription, error) { + + var previousOwnerRule []interface{} + for _, previousOwnerItem := range previousOwner { + previousOwnerRule = append(previousOwnerRule, previousOwnerItem) + } + var newOwnerRule []interface{} + for _, newOwnerItem := range newOwner { + newOwnerRule = append(newOwnerRule, newOwnerItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "OwnershipTransferred", previousOwnerRule, newOwnerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenOwnershipTransferred) + if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnershipTransferred is a log parse operation binding the contract event 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0. +// +// Solidity: event OwnershipTransferred(address indexed previousOwner, address indexed newOwner) +func (_Token *TokenFilterer) ParseOwnershipTransferred(log types.Log) (*TokenOwnershipTransferred, error) { + event := new(TokenOwnershipTransferred) + if err := _Token.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Token contract. +type TokenTransferIterator struct { + Event *TokenTransfer // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenTransferIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenTransferIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenTransferIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenTransfer represents a Transfer event raised by the Token contract. +type TokenTransfer struct { + From common.Address + To common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*TokenTransferIterator, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return &TokenTransferIterator{contract: _Token.contract, event: "Transfer", logs: logs, sub: sub}, nil +} + +// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *TokenTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) ParseTransfer(log types.Log) (*TokenTransfer, error) { + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/zcnbridge/ethereum_wallet.go b/zcnbridge/ethereum_wallet.go deleted file mode 100644 index 59e166f66..000000000 --- a/zcnbridge/ethereum_wallet.go +++ /dev/null @@ -1,110 +0,0 @@ -package zcnbridge - -import ( - "context" - "crypto/ecdsa" - "math/big" - "path" - "time" - - "github.com/ethereum/go-ethereum/accounts" - - "github.com/ethereum/go-ethereum/accounts/keystore" - - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "github.com/pkg/errors" - - "github.com/ethereum/go-ethereum/common" -) - -func (b *BridgeClient) CreateEthClient() (*ethclient.Client, error) { - client, err := ethclient.Dial(b.EthereumNodeURL) - if err != nil { - Logger.Error(err) - } - return client, err -} - -// _allowances[owner][spender] = amount; -// as a spender, ERC20 WZCN token must increase allowance for the bridge to make burn on behalf of WZCN owner -func CreateSignedTransaction( - chainID *big.Int, - client *ethclient.Client, - fromAddress common.Address, - privateKey *ecdsa.PrivateKey, - gasLimitUnits uint64, -) *bind.TransactOpts { - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - Logger.Fatal(err) - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - Logger.Fatal(err) - } - - opts, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID) - if err != nil { - Logger.Fatal(err) - } - - valueWei := new(big.Int).Mul(big.NewInt(0), big.NewInt(params.Wei)) - - opts.Nonce = big.NewInt(int64(nonce)) - opts.Value = valueWei // in wei - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts -} - -func (b *BridgeClient) CreateSignedTransactionFromKeyStore(client *ethclient.Client, gasLimitUnits uint64) *bind.TransactOpts { - var ( - signerAddress = common.HexToAddress(b.EthereumAddress) - password = b.Password - ) - - keyDir := path.Join(b.Homedir, EthereumWalletStorageDir) - ks := keystore.NewKeyStore(keyDir, keystore.StandardScryptN, keystore.StandardScryptP) - signer := accounts.Account{ - Address: signerAddress, - } - signerAcc, err := ks.Find(signer) - if err != nil { - Logger.Fatal(errors.Wrapf(err, "signer: %s", signerAddress.Hex())) - } - - chainID, err := client.ChainID(context.Background()) - if err != nil { - Logger.Fatal(errors.Wrap(err, "failed to get chain ID")) - } - - nonce, err := client.PendingNonceAt(context.Background(), signerAddress) - if err != nil { - Logger.Fatal(err) - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - Logger.Fatal(err) - } - - err = ks.TimedUnlock(signer, password, time.Second*2) - if err != nil { - Logger.Fatal(err) - } - - opts, err := bind.NewKeyStoreTransactorWithChainID(ks, signerAcc, chainID) - if err != nil { - Logger.Fatal(err) - } - - opts.Nonce = big.NewInt(int64(nonce)) - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts -} diff --git a/zcnbridge/http/client.go b/zcnbridge/http/client.go index eb53872c3..008c4ad3c 100644 --- a/zcnbridge/http/client.go +++ b/zcnbridge/http/client.go @@ -29,14 +29,15 @@ func CleanClient() *http.Client { } // NewRetryableClient creates default retryablehttp.Client with timeouts and embedded NewClient result. -func NewRetryableClient() *retryablehttp.Client { +func NewRetryableClient(verbose bool) *retryablehttp.Client { client := retryablehttp.NewClient() client.HTTPClient = &http.Client{ Transport: zboxutil.DefaultTransport, } - //client.RetryWaitMax = RetryWaitMax - //client.RetryMax = RetryMax - //client.Logger = nil + + if !verbose { + client.Logger = nil + } return client } diff --git a/zcnbridge/http/rest.go b/zcnbridge/http/rest.go index e3f1729db..87bfee4f9 100644 --- a/zcnbridge/http/rest.go +++ b/zcnbridge/http/rest.go @@ -8,10 +8,10 @@ import ( "io/ioutil" "net/http" "net/url" - "os" "sync" "go.uber.org/zap" + "gopkg.in/natefinch/lumberjack.v2" "github.com/0chain/gosdk/core/logger" "github.com/0chain/gosdk/core/util" @@ -32,16 +32,37 @@ type Params map[string]string var Logger logger.Logger var defaultLogLevel = logger.DEBUG +var logVerbose = true func init() { Logger.Init(defaultLogLevel, "zcnbridge-http-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default + } + Logger.SetLogFile(ioWriter, true) +} + +func SetLogFile(logFile string, verbose bool) { + Logger.Init(defaultLogLevel, "zcnbridge-sdk") + Logger.SetLevel(logger.DEBUG) + + ioWriter := &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - Logger.SetLogFile(f, true) + logVerbose = verbose + Logger.SetLogFile(ioWriter, logVerbose) } // MakeSCRestAPICall calls smart contract with provided address @@ -63,7 +84,7 @@ func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncor results := make(chan *queryResult, len(sharders)) defer close(results) - var client = NewRetryableClient() + var client = NewRetryableClient(logVerbose) wg := &sync.WaitGroup{} for _, sharder := range sharders { @@ -73,7 +94,6 @@ func MakeSCRestAPICall(opCode int, relativePath string, params Params, cb zcncor var u = makeURL(params, sharderUrl, relativePath) Logger.Info("Query ", u.String()) - resp, err := client.Get(u.String()) if err != nil { Logger.Error("MakeSCRestAPICall - failed to get response from", zap.String("URL", sharderUrl), zap.Any("error", err)) @@ -148,8 +168,8 @@ func hashAndBytesOfReader(r io.Reader) (string, []byte, error) { // extractSharders returns string slice of randomly ordered sharders existing in the current network. func extractSharders() []string { - network := zcncore.GetNetwork() - return util.GetRandom(network.Sharders, len(network.Sharders)) + sharders := zcncore.Sharders.Healthy() + return util.GetRandom(sharders, len(sharders)) } // makeURL creates url.URL to make smart contract request to sharder. diff --git a/zcnbridge/keystore.go b/zcnbridge/keystore.go index 6fffbc821..101662b59 100644 --- a/zcnbridge/keystore.go +++ b/zcnbridge/keystore.go @@ -3,6 +3,7 @@ package zcnbridge import ( "fmt" "path" + "time" hdw "github.com/0chain/gosdk/zcncore/ethhdwallet" "github.com/ethereum/go-ethereum/accounts" @@ -11,6 +12,52 @@ import ( "github.com/pkg/errors" ) +// DetailedAccount describes detailed account +type DetailedAccount struct { + EthereumAddress, + PublicKey, + PrivateKey accounts.Account +} + +// KeyStore is a wrapper, which exposes Ethereum KeyStore methods used by DEX bridge. +type KeyStore interface { + Find(accounts.Account) (accounts.Account, error) + TimedUnlock(accounts.Account, string, time.Duration) error + SignHash(account accounts.Account, hash []byte) ([]byte, error) + GetEthereumKeyStore() *keystore.KeyStore +} + +type keyStore struct { + ks *keystore.KeyStore +} + +// NewKeyStore creates new KeyStore wrapper instance +func NewKeyStore(path string) KeyStore { + return &keyStore{ + ks: keystore.NewKeyStore(path, keystore.StandardScryptN, keystore.StandardScryptP), + } +} + +// Find forwards request to Ethereum KeyStore Find method +func (k *keyStore) Find(account accounts.Account) (accounts.Account, error) { + return k.ks.Find(account) +} + +// TimedUnlock forwards request to Ethereum KeyStore TimedUnlock method +func (k *keyStore) TimedUnlock(account accounts.Account, passPhrase string, timeout time.Duration) error { + return k.ks.TimedUnlock(account, passPhrase, timeout) +} + +// SignHash forwards request to Ethereum KeyStore SignHash method +func (k *keyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { + return k.ks.SignHash(account, hash) +} + +// GetEthereumKeyStore returns Ethereum KeyStore instance +func (k *keyStore) GetEthereumKeyStore() *keystore.KeyStore { + return k.ks +} + // ListStorageAccounts List available accounts func ListStorageAccounts(homedir string) []common.Address { keyDir := path.Join(homedir, EthereumWalletStorageDir) @@ -78,8 +125,14 @@ func CreateKeyStorage(homedir, password string) error { return nil } +type AccountAddressIndex struct { + AccountIndex int + AddressIndex int + Bip32 bool +} + // ImportAccount imports account using mnemonic -func ImportAccount(homedir, mnemonic, password string) (string, error) { +func ImportAccount(homedir, mnemonic, password string, accountAddrIndex ...AccountAddressIndex) (string, error) { // 1. Create storage and account if it doesn't exist and add account to it keyDir := path.Join(homedir, EthereumWalletStorageDir) @@ -92,7 +145,18 @@ func ImportAccount(homedir, mnemonic, password string) (string, error) { return "", errors.Wrap(err, "failed to import from mnemonic") } - pathD := hdw.MustParseDerivationPath("m/44'/60'/0'/0/0") + var aai AccountAddressIndex + if len(accountAddrIndex) > 0 { + aai = accountAddrIndex[0] + } + + var pathD accounts.DerivationPath + if aai.Bip32 { + pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/%d", aai.AddressIndex)) + } else { + pathD = hdw.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/%d'/0/%d", aai.AccountIndex, aai.AddressIndex)) + } + account, err := wallet.Derive(pathD, true) if err != nil { return "", errors.Wrap(err, "failed parse derivation path") diff --git a/zcnbridge/mocks/EthereumClient.go b/zcnbridge/mocks/EthereumClient.go new file mode 100644 index 000000000..1169cfa92 --- /dev/null +++ b/zcnbridge/mocks/EthereumClient.go @@ -0,0 +1,332 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + big "math/big" + + common "github.com/ethereum/go-ethereum/common" + + ethereum "github.com/ethereum/go-ethereum" + + mock "github.com/stretchr/testify/mock" + + types "github.com/ethereum/go-ethereum/core/types" +) + +// EthereumClient is an autogenerated mock type for the EthereumClient type +type EthereumClient struct { + mock.Mock +} + +// CallContract provides a mock function with given fields: ctx, call, blockNumber +func (_m *EthereumClient) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { + ret := _m.Called(ctx, call, blockNumber) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { + return rf(ctx, call, blockNumber) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { + r0 = rf(ctx, call, blockNumber) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { + r1 = rf(ctx, call, blockNumber) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ChainID provides a mock function with given fields: ctx +func (_m *EthereumClient) ChainID(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CodeAt provides a mock function with given fields: ctx, contract, blockNumber +func (_m *EthereumClient) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { + ret := _m.Called(ctx, contract, blockNumber) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { + return rf(ctx, contract, blockNumber) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { + r0 = rf(ctx, contract, blockNumber) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { + r1 = rf(ctx, contract, blockNumber) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// EstimateGas provides a mock function with given fields: ctx, call +func (_m *EthereumClient) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { + ret := _m.Called(ctx, call) + + var r0 uint64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { + return rf(ctx, call) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { + r0 = rf(ctx, call) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { + r1 = rf(ctx, call) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FilterLogs provides a mock function with given fields: ctx, query +func (_m *EthereumClient) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { + ret := _m.Called(ctx, query) + + var r0 []types.Log + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { + return rf(ctx, query) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { + r0 = rf(ctx, query) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]types.Log) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { + r1 = rf(ctx, query) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// HeaderByNumber provides a mock function with given fields: ctx, number +func (_m *EthereumClient) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { + ret := _m.Called(ctx, number) + + var r0 *types.Header + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { + return rf(ctx, number) + } + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { + r0 = rf(ctx, number) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Header) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { + r1 = rf(ctx, number) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PendingCodeAt provides a mock function with given fields: ctx, account +func (_m *EthereumClient) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { + ret := _m.Called(ctx, account) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { + return rf(ctx, account) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { + r0 = rf(ctx, account) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { + r1 = rf(ctx, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// PendingNonceAt provides a mock function with given fields: ctx, account +func (_m *EthereumClient) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { + ret := _m.Called(ctx, account) + + var r0 uint64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { + return rf(ctx, account) + } + if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { + r0 = rf(ctx, account) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { + r1 = rf(ctx, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SendTransaction provides a mock function with given fields: ctx, tx +func (_m *EthereumClient) SendTransaction(ctx context.Context, tx *types.Transaction) error { + ret := _m.Called(ctx, tx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { + r0 = rf(ctx, tx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// SubscribeFilterLogs provides a mock function with given fields: ctx, query, ch +func (_m *EthereumClient) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { + ret := _m.Called(ctx, query, ch) + + var r0 ethereum.Subscription + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { + return rf(ctx, query, ch) + } + if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { + r0 = rf(ctx, query, ch) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(ethereum.Subscription) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { + r1 = rf(ctx, query, ch) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SuggestGasPrice provides a mock function with given fields: ctx +func (_m *EthereumClient) SuggestGasPrice(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// SuggestGasTipCap provides a mock function with given fields: ctx +func (_m *EthereumClient) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { + ret := _m.Called(ctx) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewEthereumClient interface { + mock.TestingT + Cleanup(func()) +} + +// NewEthereumClient creates a new instance of EthereumClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewEthereumClient(t mockConstructorTestingTNewEthereumClient) *EthereumClient { + mock := &EthereumClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/JobResult.go b/zcnbridge/mocks/JobResult.go new file mode 100644 index 000000000..78487e1e3 --- /dev/null +++ b/zcnbridge/mocks/JobResult.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// JobResult is an autogenerated mock type for the JobResult type +type JobResult struct { + mock.Mock +} + +// Data provides a mock function with given fields: +func (_m *JobResult) Data() interface{} { + ret := _m.Called() + + var r0 interface{} + if rf, ok := ret.Get(0).(func() interface{}); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(interface{}) + } + } + + return r0 +} + +// Error provides a mock function with given fields: +func (_m *JobResult) Error() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetAuthorizerID provides a mock function with given fields: +func (_m *JobResult) GetAuthorizerID() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetAuthorizerID provides a mock function with given fields: ID +func (_m *JobResult) SetAuthorizerID(ID string) { + _m.Called(ID) +} + +type mockConstructorTestingTNewJobResult interface { + mock.TestingT + Cleanup(func()) +} + +// NewJobResult creates a new instance of JobResult. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewJobResult(t mockConstructorTestingTNewJobResult) *JobResult { + mock := &JobResult{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/KeyStore.go b/zcnbridge/mocks/KeyStore.go new file mode 100644 index 000000000..be25a121c --- /dev/null +++ b/zcnbridge/mocks/KeyStore.go @@ -0,0 +1,112 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + accounts "github.com/ethereum/go-ethereum/accounts" + keystore "github.com/ethereum/go-ethereum/accounts/keystore" + + mock "github.com/stretchr/testify/mock" + + time "time" +) + +// KeyStore is an autogenerated mock type for the KeyStore type +type KeyStore struct { + mock.Mock +} + +// Find provides a mock function with given fields: _a0 +func (_m *KeyStore) Find(_a0 accounts.Account) (accounts.Account, error) { + ret := _m.Called(_a0) + + var r0 accounts.Account + var r1 error + if rf, ok := ret.Get(0).(func(accounts.Account) (accounts.Account, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(accounts.Account) accounts.Account); ok { + r0 = rf(_a0) + } else { + r0 = ret.Get(0).(accounts.Account) + } + + if rf, ok := ret.Get(1).(func(accounts.Account) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetEthereumKeyStore provides a mock function with given fields: +func (_m *KeyStore) GetEthereumKeyStore() *keystore.KeyStore { + ret := _m.Called() + + var r0 *keystore.KeyStore + if rf, ok := ret.Get(0).(func() *keystore.KeyStore); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*keystore.KeyStore) + } + } + + return r0 +} + +// SignHash provides a mock function with given fields: account, hash +func (_m *KeyStore) SignHash(account accounts.Account, hash []byte) ([]byte, error) { + ret := _m.Called(account, hash) + + var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(accounts.Account, []byte) ([]byte, error)); ok { + return rf(account, hash) + } + if rf, ok := ret.Get(0).(func(accounts.Account, []byte) []byte); ok { + r0 = rf(account, hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]byte) + } + } + + if rf, ok := ret.Get(1).(func(accounts.Account, []byte) error); ok { + r1 = rf(account, hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// TimedUnlock provides a mock function with given fields: _a0, _a1, _a2 +func (_m *KeyStore) TimedUnlock(_a0 accounts.Account, _a1 string, _a2 time.Duration) error { + ret := _m.Called(_a0, _a1, _a2) + + var r0 error + if rf, ok := ret.Get(0).(func(accounts.Account, string, time.Duration) error); ok { + r0 = rf(_a0, _a1, _a2) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewKeyStore interface { + mock.TestingT + Cleanup(func()) +} + +// NewKeyStore creates a new instance of KeyStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewKeyStore(t mockConstructorTestingTNewKeyStore) *KeyStore { + mock := &KeyStore{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/Transaction.go b/zcnbridge/mocks/Transaction.go new file mode 100644 index 000000000..b9a833470 --- /dev/null +++ b/zcnbridge/mocks/Transaction.go @@ -0,0 +1,135 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// Transaction is an autogenerated mock type for the Transaction type +type Transaction struct { + mock.Mock +} + +// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val +func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { + ret := _m.Called(ctx, address, funcName, input, val) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { + return rf(ctx, address, funcName, input, val) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { + r0 = rf(ctx, address, funcName, input, val) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { + r1 = rf(ctx, address, funcName, input, val) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetCallback provides a mock function with given fields: +func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { + ret := _m.Called() + + var r0 transaction.TransactionCallbackAwaitable + if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) + } + } + + return r0 +} + +// GetHash provides a mock function with given fields: +func (_m *Transaction) GetHash() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetScheme provides a mock function with given fields: +func (_m *Transaction) GetScheme() zcncore.TransactionScheme { + ret := _m.Called() + + var r0 zcncore.TransactionScheme + if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(zcncore.TransactionScheme) + } + } + + return r0 +} + +// GetTransactionOutput provides a mock function with given fields: +func (_m *Transaction) GetTransactionOutput() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetHash provides a mock function with given fields: _a0 +func (_m *Transaction) SetHash(_a0 string) { + _m.Called(_a0) +} + +// Verify provides a mock function with given fields: ctx +func (_m *Transaction) Verify(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransaction interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { + mock := &Transaction{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/TransactionCallbackAwaitable.go b/zcnbridge/mocks/TransactionCallbackAwaitable.go new file mode 100644 index 000000000..299573252 --- /dev/null +++ b/zcnbridge/mocks/TransactionCallbackAwaitable.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type +type TransactionCallbackAwaitable struct { + mock.Mock +} + +// OnAuthComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnTransactionComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnVerifyComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// WaitCompleteCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WaitVerifyCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCallbackAwaitable interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { + mock := &TransactionCallbackAwaitable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/mocks/TransactionProvider.go b/zcnbridge/mocks/TransactionProvider.go new file mode 100644 index 000000000..25617eb25 --- /dev/null +++ b/zcnbridge/mocks/TransactionProvider.go @@ -0,0 +1,54 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" +) + +// TransactionProvider is an autogenerated mock type for the TransactionProvider type +type TransactionProvider struct { + mock.Mock +} + +// NewTransactionEntity provides a mock function with given fields: txnFee +func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { + ret := _m.Called(txnFee) + + var r0 transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { + return rf(txnFee) + } + if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { + r0 = rf(txnFee) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(uint64) error); ok { + r1 = rf(txnFee) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewTransactionProvider interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { + mock := &TransactionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/callback.go b/zcnbridge/transaction/callback.go index 8481b822a..0ce4a1e1a 100644 --- a/zcnbridge/transaction/callback.go +++ b/zcnbridge/transaction/callback.go @@ -13,6 +13,14 @@ var ( ) type ( + // TransactionCallbackAwaitable extends zcncore.TransactionCallback with synchronization methods + TransactionCallbackAwaitable interface { + zcncore.TransactionCallback + + WaitCompleteCall(ctx context.Context) error + WaitVerifyCall(ctx context.Context) error + } + // callback implements zcncore.TransactionCallback interface. callback struct { // waitCh represents channel for making callback.OnTransactionComplete, @@ -22,7 +30,7 @@ type ( } ) -func NewStatus() zcncore.TransactionCallback { +func NewStatus() TransactionCallbackAwaitable { return &callback{ waitCh: make(chan interface{}), } @@ -58,7 +66,7 @@ func (cb *callback) OnAuthComplete(_ *zcncore.Transaction, status int) { cb.sendCall() } -func (cb *callback) waitCompleteCall(ctx context.Context) error { +func (cb *callback) WaitCompleteCall(ctx context.Context) error { select { case <-ctx.Done(): return errors.New("completing_transaction", "completing transaction context deadline exceeded") @@ -67,7 +75,7 @@ func (cb *callback) waitCompleteCall(ctx context.Context) error { } } -func (cb *callback) waitVerifyCall(ctx context.Context) error { +func (cb *callback) WaitVerifyCall(ctx context.Context) error { select { case <-ctx.Done(): return errors.New("verifying_transaction", "verifying transaction context deadline exceeded") diff --git a/zcnbridge/transaction/functions.go b/zcnbridge/transaction/functions.go index 062b115fd..bf9845645 100644 --- a/zcnbridge/transaction/functions.go +++ b/zcnbridge/transaction/functions.go @@ -8,19 +8,23 @@ import ( "github.com/0chain/gosdk/zcncore" ) -func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (*Transaction, error) { +func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - err = t.scheme.ZCNSCAddAuthorizer(input) + scheme := t.GetScheme() + + err = scheme.ZCNSCAddAuthorizer(input) if err != nil { return t, err } - err = t.callBack.waitCompleteCall(ctx) - t.Hash = t.scheme.Hash() + callBack := t.GetCallback() + + err = callBack.WaitCompleteCall(ctx) + t.SetHash(scheme.Hash()) if err != nil { return t, err } @@ -28,19 +32,23 @@ func AddAuthorizer(ctx context.Context, input *zcncore.AddAuthorizerPayload) (*T return t, nil } -func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthCheckPayload) (*Transaction, error) { +func AuthorizerHealthCheck(ctx context.Context, input *zcncore.AuthorizerHealthCheckPayload) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - err = t.scheme.ZCNSCAuthorizerHealthCheck(input) + scheme := t.GetScheme() + + err = scheme.ZCNSCAuthorizerHealthCheck(input) if err != nil { return t, err } - err = t.callBack.waitCompleteCall(ctx) - t.Hash = t.scheme.Hash() + callBack := t.GetCallback() + + err = callBack.WaitCompleteCall(ctx) + t.SetHash(scheme.Hash()) if err != nil { return t, err } diff --git a/zcnbridge/transaction/mocks/Transaction.go b/zcnbridge/transaction/mocks/Transaction.go new file mode 100644 index 000000000..b9a833470 --- /dev/null +++ b/zcnbridge/transaction/mocks/Transaction.go @@ -0,0 +1,135 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// Transaction is an autogenerated mock type for the Transaction type +type Transaction struct { + mock.Mock +} + +// ExecuteSmartContract provides a mock function with given fields: ctx, address, funcName, input, val +func (_m *Transaction) ExecuteSmartContract(ctx context.Context, address string, funcName string, input interface{}, val uint64) (string, error) { + ret := _m.Called(ctx, address, funcName, input, val) + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) (string, error)); ok { + return rf(ctx, address, funcName, input, val) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string, interface{}, uint64) string); ok { + r0 = rf(ctx, address, funcName, input, val) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string, interface{}, uint64) error); ok { + r1 = rf(ctx, address, funcName, input, val) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetCallback provides a mock function with given fields: +func (_m *Transaction) GetCallback() transaction.TransactionCallbackAwaitable { + ret := _m.Called() + + var r0 transaction.TransactionCallbackAwaitable + if rf, ok := ret.Get(0).(func() transaction.TransactionCallbackAwaitable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.TransactionCallbackAwaitable) + } + } + + return r0 +} + +// GetHash provides a mock function with given fields: +func (_m *Transaction) GetHash() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// GetScheme provides a mock function with given fields: +func (_m *Transaction) GetScheme() zcncore.TransactionScheme { + ret := _m.Called() + + var r0 zcncore.TransactionScheme + if rf, ok := ret.Get(0).(func() zcncore.TransactionScheme); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(zcncore.TransactionScheme) + } + } + + return r0 +} + +// GetTransactionOutput provides a mock function with given fields: +func (_m *Transaction) GetTransactionOutput() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// SetHash provides a mock function with given fields: _a0 +func (_m *Transaction) SetHash(_a0 string) { + _m.Called(_a0) +} + +// Verify provides a mock function with given fields: ctx +func (_m *Transaction) Verify(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransaction interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransaction creates a new instance of Transaction. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransaction(t mockConstructorTestingTNewTransaction) *Transaction { + mock := &Transaction{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go b/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go new file mode 100644 index 000000000..299573252 --- /dev/null +++ b/zcnbridge/transaction/mocks/TransactionCallbackAwaitable.go @@ -0,0 +1,74 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCallbackAwaitable is an autogenerated mock type for the TransactionCallbackAwaitable type +type TransactionCallbackAwaitable struct { + mock.Mock +} + +// OnAuthComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnAuthComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnTransactionComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnTransactionComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// OnVerifyComplete provides a mock function with given fields: t, status +func (_m *TransactionCallbackAwaitable) OnVerifyComplete(t *zcncore.Transaction, status int) { + _m.Called(t, status) +} + +// WaitCompleteCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitCompleteCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WaitVerifyCall provides a mock function with given fields: ctx +func (_m *TransactionCallbackAwaitable) WaitVerifyCall(ctx context.Context) error { + ret := _m.Called(ctx) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCallbackAwaitable interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCallbackAwaitable creates a new instance of TransactionCallbackAwaitable. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCallbackAwaitable(t mockConstructorTestingTNewTransactionCallbackAwaitable) *TransactionCallbackAwaitable { + mock := &TransactionCallbackAwaitable{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/mocks/TransactionProvider.go b/zcnbridge/transaction/mocks/TransactionProvider.go new file mode 100644 index 000000000..25617eb25 --- /dev/null +++ b/zcnbridge/transaction/mocks/TransactionProvider.go @@ -0,0 +1,54 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/zcnbridge/transaction" + mock "github.com/stretchr/testify/mock" +) + +// TransactionProvider is an autogenerated mock type for the TransactionProvider type +type TransactionProvider struct { + mock.Mock +} + +// NewTransactionEntity provides a mock function with given fields: txnFee +func (_m *TransactionProvider) NewTransactionEntity(txnFee uint64) (transaction.Transaction, error) { + ret := _m.Called(txnFee) + + var r0 transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(uint64) (transaction.Transaction, error)); ok { + return rf(txnFee) + } + if rf, ok := ret.Get(0).(func(uint64) transaction.Transaction); ok { + r0 = rf(txnFee) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(uint64) error); ok { + r1 = rf(txnFee) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewTransactionProvider interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionProvider creates a new instance of TransactionProvider. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionProvider(t mockConstructorTestingTNewTransactionProvider) *TransactionProvider { + mock := &TransactionProvider{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcnbridge/transaction/txn.go b/zcnbridge/transaction/txn.go index eb4b8d25c..9d886f773 100644 --- a/zcnbridge/transaction/txn.go +++ b/zcnbridge/transaction/txn.go @@ -18,13 +18,32 @@ var ( ) type ( - // Transaction entity that encapsulates the transaction related data and metadata. - Transaction struct { + // TransactionProvider ... + TransactionProvider interface { + NewTransactionEntity(txnFee uint64) (Transaction, error) + } + + // transactionProvider ... + transactionProvider struct{} + + // Transaction interface describes transaction entity. + Transaction interface { + ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) + Verify(ctx context.Context) error + GetScheme() zcncore.TransactionScheme + GetCallback() TransactionCallbackAwaitable + GetTransactionOutput() string + GetHash() string + SetHash(string) + } + + // TransactionEntity entity that encapsulates the transaction related data and metadata. + transactionEntity struct { Hash string `json:"hash,omitempty"` Version string `json:"version,omitempty"` TransactionOutput string `json:"transaction_output,omitempty"` scheme zcncore.TransactionScheme - callBack *callback + callBack TransactionCallbackAwaitable } ) @@ -35,27 +54,35 @@ type ( // confirmation represents the acceptance that a transaction is included into the blockchain. confirmation struct { - Version string `json:"version"` - Hash string `json:"hash"` - BlockHash string `json:"block_hash"` - PreviousBlockHash string `json:"previous_block_hash"` - Transaction *Transaction `json:"txn,omitempty"` - CreationDate ctime.Timestamp `json:"creation_date"` - MinerID string `json:"miner_id"` - Round int64 `json:"round"` - Status int `json:"transaction_status"` - RoundRandomSeed int64 `json:"round_random_seed"` - MerkleTreeRoot string `json:"merkle_tree_root"` - MerkleTreePath *util.MTPath `json:"merkle_tree_path"` - ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` - ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` + Version string `json:"version"` + Hash string `json:"hash"` + BlockHash string `json:"block_hash"` + PreviousBlockHash string `json:"previous_block_hash"` + Transaction *transactionEntity `json:"txn,omitempty"` + CreationDate ctime.Timestamp `json:"creation_date"` + MinerID string `json:"miner_id"` + Round int64 `json:"round"` + Status int `json:"transaction_status"` + RoundRandomSeed int64 `json:"round_random_seed"` + MerkleTreeRoot string `json:"merkle_tree_root"` + MerkleTreePath *util.MTPath `json:"merkle_tree_path"` + ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"` + ReceiptMerkleTreePath *util.MTPath `json:"receipt_merkle_tree_path"` } ) +func NewTransactionProvider() TransactionProvider { + return &transactionProvider{} +} + +func (t *transactionProvider) NewTransactionEntity(txnFee uint64) (Transaction, error) { + return NewTransactionEntity(txnFee) +} + // NewTransactionEntity creates Transaction with initialized fields. // Sets version, client ID, creation date, public key and creates internal zcncore.TransactionScheme. -func NewTransactionEntity(txnFee uint64) (*Transaction, error) { - txn := &Transaction{ +func NewTransactionEntity(txnFee uint64) (Transaction, error) { + txn := &transactionEntity{ callBack: NewStatus().(*callback), } zcntxn, err := zcncore.NewTransaction(txn.callBack, txnFee, 0) @@ -71,7 +98,7 @@ func NewTransactionEntity(txnFee uint64) (*Transaction, error) { // ExecuteSmartContract executes function of smart contract with provided address. // // Returns hash of executed transaction. -func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, +func (t *transactionEntity) ExecuteSmartContract(ctx context.Context, address, funcName string, input interface{}, val uint64) (string, error) { const errCode = "transaction_send" @@ -83,7 +110,7 @@ func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcNam return "", errors.New(errCode, msg) } - if err := t.callBack.waitCompleteCall(ctx); err != nil { + if err := t.callBack.WaitCompleteCall(ctx); err != nil { msg := fmt.Sprintf("error while sending txn: %v", err) return "", errors.New(errCode, msg) } @@ -95,7 +122,7 @@ func (t *Transaction) ExecuteSmartContract(ctx context.Context, address, funcNam return t.scheme.Hash(), nil } -func (t *Transaction) Verify(ctx context.Context) error { +func (t *transactionEntity) Verify(ctx context.Context) error { const errCode = "transaction_verify" err := t.scheme.Verify() @@ -104,7 +131,7 @@ func (t *Transaction) Verify(ctx context.Context) error { return errors.New(errCode, msg) } - if err := t.callBack.waitVerifyCall(ctx); err != nil { + if err := t.callBack.WaitVerifyCall(ctx); err != nil { msg := fmt.Sprintf("error while verifying txn: %v; txn hash: %s", err, t.scheme.GetTransactionHash()) return errors.New(errCode, msg) } @@ -126,8 +153,8 @@ func (t *Transaction) Verify(ctx context.Context) error { } if vo.Confirmation.Transaction != nil { - t.Hash = vo.Confirmation.Transaction.Hash - t.TransactionOutput = vo.Confirmation.Transaction.TransactionOutput + t.Hash = vo.Confirmation.Transaction.GetHash() + t.TransactionOutput = vo.Confirmation.Transaction.GetTransactionOutput() } else { return errors.New(errCode, "got invalid confirmation (missing transaction)") } @@ -135,14 +162,45 @@ func (t *Transaction) Verify(ctx context.Context) error { return nil } +// GetSheme returns transaction scheme +func (t *transactionEntity) GetScheme() zcncore.TransactionScheme { + return t.scheme +} + +// GetHash returns transaction hash +func (t *transactionEntity) GetHash() string { + return t.Hash +} + +// SetHash sets transaction hash +func (t *transactionEntity) SetHash(hash string) { + t.Hash = hash +} + +// GetTransactionOutput returns transaction output +func (t *transactionEntity) GetTransactionOutput() string { + return t.TransactionOutput +} + +func (t *transactionEntity) GetCallback() TransactionCallbackAwaitable { + return t.callBack +} + +// GetVersion returns transaction version +func (t *transactionEntity) GetVersion() string { + return t.Version +} + // Verify checks including of transaction in the blockchain. -func Verify(ctx context.Context, hash string) (*Transaction, error) { +func Verify(ctx context.Context, hash string) (Transaction, error) { t, err := NewTransactionEntity(0) if err != nil { return nil, err } - if err := t.scheme.SetTransactionHash(hash); err != nil { + scheme := t.GetScheme() + + if err := scheme.SetTransactionHash(hash); err != nil { return nil, err } diff --git a/zcnbridge/wallet/wallet.go b/zcnbridge/wallet/wallet.go index b6fd10c1e..74168b313 100644 --- a/zcnbridge/wallet/wallet.go +++ b/zcnbridge/wallet/wallet.go @@ -1,10 +1,8 @@ package wallet import ( - //"github.com/0chain/gosdk/zcnbridge/log" - "os" - "github.com/0chain/gosdk/core/logger" + "gopkg.in/natefinch/lumberjack.v2" ) const ( @@ -23,9 +21,13 @@ func init() { Logger.Init(defaultLogLevel, "zcnbridge-wallet-sdk") Logger.SetLevel(logger.DEBUG) - f, err := os.OpenFile("bridge.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return + ioWriter := &lumberjack.Logger{ + Filename: "bridge.log", + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default } - Logger.SetLogFile(f, true) + Logger.SetLogFile(ioWriter, true) } diff --git a/zcnbridge/wallets/README.md b/zcnbridge/wallets/README.md new file mode 100644 index 000000000..9ab8bf214 --- /dev/null +++ b/zcnbridge/wallets/README.md @@ -0,0 +1 @@ +Contains Ethereum KeyStore wallets used for tests. \ No newline at end of file diff --git a/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 b/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 new file mode 100644 index 000000000..a3590fc0a --- /dev/null +++ b/zcnbridge/wallets/UTC--2023-08-29T19-30-47.946612000Z--d8c9156e782c68ee671c09b6b92de76c97948432 @@ -0,0 +1 @@ +{"address":"d8c9156e782c68ee671c09b6b92de76c97948432","crypto":{"cipher":"aes-128-ctr","ciphertext":"7048af9fa09a3a0ca22e7ef8afea41fec8dcce848b48be8fc0d59a1f04e8581f","cipherparams":{"iv":"c97dd7cb9c554965196dd4d5bc218e0e"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"aaccc85e65af50058262ee54a2e8952a91b47d0af266e4a3558425049e77c835"},"mac":"c5ac03cbe13375c6e4c3052ff5f23f92a2c595fca6c90c3ac908b57dccd78b0a"},"id":"16c89ced-50fd-4c78-86e3-40ff440078fb","version":3} \ No newline at end of file diff --git a/zcncore/mocks/AuthCallback.go b/zcncore/mocks/AuthCallback.go index 1e7889d88..479e6475e 100644 --- a/zcncore/mocks/AuthCallback.go +++ b/zcncore/mocks/AuthCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/FeeOption.go b/zcncore/mocks/FeeOption.go new file mode 100644 index 000000000..38116bbf2 --- /dev/null +++ b/zcncore/mocks/FeeOption.go @@ -0,0 +1,33 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + zcncore "github.com/0chain/gosdk/zcncore" + mock "github.com/stretchr/testify/mock" +) + +// FeeOption is an autogenerated mock type for the FeeOption type +type FeeOption struct { + mock.Mock +} + +// Execute provides a mock function with given fields: _a0 +func (_m *FeeOption) Execute(_a0 *zcncore.TxnFeeOption) { + _m.Called(_a0) +} + +type mockConstructorTestingTNewFeeOption interface { + mock.TestingT + Cleanup(func()) +} + +// NewFeeOption creates a new instance of FeeOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFeeOption(t mockConstructorTestingTNewFeeOption) *FeeOption { + mock := &FeeOption{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/GetBalanceCallback.go b/zcncore/mocks/GetBalanceCallback.go index a18f52f85..2ca67ea8d 100644 --- a/zcncore/mocks/GetBalanceCallback.go +++ b/zcncore/mocks/GetBalanceCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/GetInfoCallback.go b/zcncore/mocks/GetInfoCallback.go index 631f241e8..9e28c1422 100644 --- a/zcncore/mocks/GetInfoCallback.go +++ b/zcncore/mocks/GetInfoCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/GetNonceCallback.go b/zcncore/mocks/GetNonceCallback.go new file mode 100644 index 000000000..6c0256589 --- /dev/null +++ b/zcncore/mocks/GetNonceCallback.go @@ -0,0 +1,30 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// GetNonceCallback is an autogenerated mock type for the GetNonceCallback type +type GetNonceCallback struct { + mock.Mock +} + +// OnNonceAvailable provides a mock function with given fields: status, nonce, info +func (_m *GetNonceCallback) OnNonceAvailable(status int, nonce int64, info string) { + _m.Called(status, nonce, info) +} + +type mockConstructorTestingTNewGetNonceCallback interface { + mock.TestingT + Cleanup(func()) +} + +// NewGetNonceCallback creates a new instance of GetNonceCallback. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewGetNonceCallback(t mockConstructorTestingTNewGetNonceCallback) *GetNonceCallback { + mock := &GetNonceCallback{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/GetUSDInfoCallback.go b/zcncore/mocks/GetUSDInfoCallback.go deleted file mode 100644 index 90a801c46..000000000 --- a/zcncore/mocks/GetUSDInfoCallback.go +++ /dev/null @@ -1,15 +0,0 @@ -// Code generated by mockery v0.0.0-dev. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// GetUSDInfoCallback is an autogenerated mock type for the GetUSDInfoCallback type -type GetUSDInfoCallback struct { - mock.Mock -} - -// OnUSDInfoAvailable provides a mock function with given fields: status, info, err -func (_m *GetUSDInfoCallback) OnUSDInfoAvailable(status int, info string, err string) { - _m.Called(status, info, err) -} diff --git a/zcncore/mocks/MSVoteCallback.go b/zcncore/mocks/MSVoteCallback.go index 69a09e5e5..db825fbfc 100644 --- a/zcncore/mocks/MSVoteCallback.go +++ b/zcncore/mocks/MSVoteCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/QueryResultHandle.go b/zcncore/mocks/QueryResultHandle.go new file mode 100644 index 000000000..bd43feefb --- /dev/null +++ b/zcncore/mocks/QueryResultHandle.go @@ -0,0 +1,42 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + zcncore "github.com/0chain/gosdk/zcncore" + mock "github.com/stretchr/testify/mock" +) + +// QueryResultHandle is an autogenerated mock type for the QueryResultHandle type +type QueryResultHandle struct { + mock.Mock +} + +// Execute provides a mock function with given fields: result +func (_m *QueryResultHandle) Execute(result zcncore.QueryResult) bool { + ret := _m.Called(result) + + var r0 bool + if rf, ok := ret.Get(0).(func(zcncore.QueryResult) bool); ok { + r0 = rf(result) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +type mockConstructorTestingTNewQueryResultHandle interface { + mock.TestingT + Cleanup(func()) +} + +// NewQueryResultHandle creates a new instance of QueryResultHandle. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewQueryResultHandle(t mockConstructorTestingTNewQueryResultHandle) *QueryResultHandle { + mock := &QueryResultHandle{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/TransactionCallback.go b/zcncore/mocks/TransactionCallback.go index ff51c4e7b..fa43d131e 100644 --- a/zcncore/mocks/TransactionCallback.go +++ b/zcncore/mocks/TransactionCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mocks/TransactionCommon.go b/zcncore/mocks/TransactionCommon.go new file mode 100644 index 000000000..fd487b7b8 --- /dev/null +++ b/zcncore/mocks/TransactionCommon.go @@ -0,0 +1,567 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package mocks + +import ( + transaction "github.com/0chain/gosdk/core/transaction" + mock "github.com/stretchr/testify/mock" + + zcncore "github.com/0chain/gosdk/zcncore" +) + +// TransactionCommon is an autogenerated mock type for the TransactionCommon type +type TransactionCommon struct { + mock.Mock +} + +// CancelAllocation provides a mock function with given fields: allocID +func (_m *TransactionCommon) CancelAllocation(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CreateAllocation provides a mock function with given fields: car, lock +func (_m *TransactionCommon) CreateAllocation(car *zcncore.CreateAllocationRequest, lock uint64) error { + ret := _m.Called(car, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.CreateAllocationRequest, uint64) error); ok { + r0 = rf(car, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CreateReadPool provides a mock function with given fields: +func (_m *TransactionCommon) CreateReadPool() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ExecuteSmartContract provides a mock function with given fields: address, methodName, input, val, feeOpts +func (_m *TransactionCommon) ExecuteSmartContract(address string, methodName string, input interface{}, val uint64, feeOpts ...zcncore.FeeOption) (*transaction.Transaction, error) { + _va := make([]interface{}, len(feeOpts)) + for _i := range feeOpts { + _va[_i] = feeOpts[_i] + } + var _ca []interface{} + _ca = append(_ca, address, methodName, input, val) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { + return rf(address, methodName, input, val, feeOpts...) + } + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { + r0 = rf(address, methodName, input, val, feeOpts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*transaction.Transaction) + } + } + + if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { + r1 = rf(address, methodName, input, val, feeOpts...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FaucetUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) FaucetUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// FinalizeAllocation provides a mock function with given fields: allocID +func (_m *TransactionCommon) FinalizeAllocation(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetVerifyConfirmationStatus provides a mock function with given fields: +func (_m *TransactionCommon) GetVerifyConfirmationStatus() zcncore.ConfirmationStatus { + ret := _m.Called() + + var r0 zcncore.ConfirmationStatus + if rf, ok := ret.Get(0).(func() zcncore.ConfirmationStatus); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(zcncore.ConfirmationStatus) + } + + return r0 +} + +// MinerSCCollectReward provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) MinerSCCollectReward(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCDeleteMiner provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCDeleteMiner(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCDeleteSharder provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCDeleteSharder(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCKill provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) MinerSCKill(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCLock provides a mock function with given fields: providerId, providerType, lock +func (_m *TransactionCommon) MinerSCLock(providerId string, providerType zcncore.Provider, lock uint64) error { + ret := _m.Called(providerId, providerType, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { + r0 = rf(providerId, providerType, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCMinerSettings provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCMinerSettings(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCSharderSettings provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerSCSharderSettings(_a0 *zcncore.MinerSCMinerInfo) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.MinerSCMinerInfo) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerSCUnlock provides a mock function with given fields: providerId, providerType +func (_m *TransactionCommon) MinerSCUnlock(providerId string, providerType zcncore.Provider) error { + ret := _m.Called(providerId, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerId, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerScUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerScUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MinerScUpdateGlobals provides a mock function with given fields: _a0 +func (_m *TransactionCommon) MinerScUpdateGlobals(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ReadPoolLock provides a mock function with given fields: allocID, blobberID, duration, lock +func (_m *TransactionCommon) ReadPoolLock(allocID string, blobberID string, duration int64, lock uint64) error { + ret := _m.Called(allocID, blobberID, duration, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { + r0 = rf(allocID, blobberID, duration, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ReadPoolUnlock provides a mock function with given fields: +func (_m *TransactionCommon) ReadPoolUnlock() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// RegisterMultiSig provides a mock function with given fields: walletstr, mswallet +func (_m *TransactionCommon) RegisterMultiSig(walletstr string, mswallet string) error { + ret := _m.Called(walletstr, mswallet) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(walletstr, mswallet) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Send provides a mock function with given fields: toClientID, val, desc +func (_m *TransactionCommon) Send(toClientID string, val uint64, desc string) error { + ret := _m.Called(toClientID, val, desc) + + var r0 error + if rf, ok := ret.Get(0).(func(string, uint64, string) error); ok { + r0 = rf(toClientID, val, desc) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StakePoolLock provides a mock function with given fields: providerId, providerType, lock +func (_m *TransactionCommon) StakePoolLock(providerId string, providerType zcncore.Provider, lock uint64) error { + ret := _m.Called(providerId, providerType, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider, uint64) error); ok { + r0 = rf(providerId, providerType, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StakePoolUnlock provides a mock function with given fields: providerId, providerType +func (_m *TransactionCommon) StakePoolUnlock(providerId string, providerType zcncore.Provider) error { + ret := _m.Called(providerId, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerId, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StorageSCCollectReward provides a mock function with given fields: providerID, providerType +func (_m *TransactionCommon) StorageSCCollectReward(providerID string, providerType zcncore.Provider) error { + ret := _m.Called(providerID, providerType) + + var r0 error + if rf, ok := ret.Get(0).(func(string, zcncore.Provider) error); ok { + r0 = rf(providerID, providerType) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// StorageScUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) StorageScUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateAllocation provides a mock function with given fields: allocID, sizeDiff, expirationDiff, lock +func (_m *TransactionCommon) UpdateAllocation(allocID string, sizeDiff int64, expirationDiff int64, lock uint64) error { + ret := _m.Called(allocID, sizeDiff, expirationDiff, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, int64, int64, uint64) error); ok { + r0 = rf(allocID, sizeDiff, expirationDiff, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateBlobberSettings provides a mock function with given fields: blobber +func (_m *TransactionCommon) UpdateBlobberSettings(blobber *zcncore.Blobber) error { + ret := _m.Called(blobber) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.Blobber) error); ok { + r0 = rf(blobber) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// UpdateValidatorSettings provides a mock function with given fields: validator +func (_m *TransactionCommon) UpdateValidatorSettings(validator *zcncore.Validator) error { + ret := _m.Called(validator) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.Validator) error); ok { + r0 = rf(validator) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// VestingAdd provides a mock function with given fields: ar, value +func (_m *TransactionCommon) VestingAdd(ar *zcncore.VestingAddRequest, value uint64) error { + ret := _m.Called(ar, value) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.VestingAddRequest, uint64) error); ok { + r0 = rf(ar, value) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// VestingUpdateConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) VestingUpdateConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WritePoolLock provides a mock function with given fields: allocID, blobberID, duration, lock +func (_m *TransactionCommon) WritePoolLock(allocID string, blobberID string, duration int64, lock uint64) error { + ret := _m.Called(allocID, blobberID, duration, lock) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string, int64, uint64) error); ok { + r0 = rf(allocID, blobberID, duration, lock) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// WritePoolUnlock provides a mock function with given fields: allocID +func (_m *TransactionCommon) WritePoolUnlock(allocID string) error { + ret := _m.Called(allocID) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(allocID) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCAddAuthorizer provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCAddAuthorizer(_a0 *zcncore.AddAuthorizerPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AddAuthorizerPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCAuthorizerHealthCheck provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCAuthorizerHealthCheck(_a0 *zcncore.AuthorizerHealthCheckPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerHealthCheckPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCDeleteAuthorizer provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCDeleteAuthorizer(_a0 *zcncore.DeleteAuthorizerPayload) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.DeleteAuthorizerPayload) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCUpdateAuthorizerConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCUpdateAuthorizerConfig(_a0 *zcncore.AuthorizerNode) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.AuthorizerNode) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ZCNSCUpdateGlobalConfig provides a mock function with given fields: _a0 +func (_m *TransactionCommon) ZCNSCUpdateGlobalConfig(_a0 *zcncore.InputMap) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(*zcncore.InputMap) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +type mockConstructorTestingTNewTransactionCommon interface { + mock.TestingT + Cleanup(func()) +} + +// NewTransactionCommon creates a new instance of TransactionCommon. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewTransactionCommon(t mockConstructorTestingTNewTransactionCommon) *TransactionCommon { + mock := &TransactionCommon{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/zcncore/mocks/TransactionScheme.go b/zcncore/mocks/TransactionScheme.go index 72fc7f621..3cd02f514 100644 --- a/zcncore/mocks/TransactionScheme.go +++ b/zcncore/mocks/TransactionScheme.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks @@ -82,6 +82,10 @@ func (_m *TransactionScheme) ExecuteSmartContract(address string, methodName str ret := _m.Called(_ca...) var r0 *transaction.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) (*transaction.Transaction, error)); ok { + return rf(address, methodName, input, val, feeOpts...) + } if rf, ok := ret.Get(0).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) *transaction.Transaction); ok { r0 = rf(address, methodName, input, val, feeOpts...) } else { @@ -90,7 +94,6 @@ func (_m *TransactionScheme) ExecuteSmartContract(address string, methodName str } } - var r1 error if rf, ok := ret.Get(1).(func(string, string, interface{}, uint64, ...zcncore.FeeOption) error); ok { r1 = rf(address, methodName, input, val, feeOpts...) } else { diff --git a/zcncore/mocks/WalletCallback.go b/zcncore/mocks/WalletCallback.go index 2cc410d17..267600db9 100644 --- a/zcncore/mocks/WalletCallback.go +++ b/zcncore/mocks/WalletCallback.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.22.1. DO NOT EDIT. package mocks diff --git a/zcncore/mswallet_base.go b/zcncore/mswallet_base.go index b51d70c37..c1762cd92 100644 --- a/zcncore/mswallet_base.go +++ b/zcncore/mswallet_base.go @@ -13,7 +13,7 @@ import ( "github.com/0chain/gosdk/core/zcncrypto" ) -//MSVoteCallback callback definition multisig Vote function +// MSVoteCallback callback definition multisig Vote function type MSVoteCallback interface { OnVoteComplete(status int, proposal string, err string) } @@ -123,6 +123,10 @@ func GetClientID(pkey string) string { return encryption.Hash(publicKeyBytes) } +func GetClientWalletKey() string { + return _config.wallet.ClientKey +} + func GetClientWalletID() string { return _config.wallet.ClientID } diff --git a/zcncore/networkworker.go b/zcncore/networkworker.go index 90d6610ab..e267c5f4a 100644 --- a/zcncore/networkworker.go +++ b/zcncore/networkworker.go @@ -10,10 +10,9 @@ import ( "reflect" "time" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/errors" "github.com/0chain/gosdk/core/conf" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/util" "go.uber.org/zap" ) @@ -58,7 +57,16 @@ func UpdateNetworkDetails() error { _config.isConfigured = false _config.chain.Miners = networkDetails.Miners _config.chain.Sharders = networkDetails.Sharders - transaction.InitCache(networkDetails.Sharders) + consensus := _config.chain.SharderConsensous + if consensus < conf.DefaultSharderConsensous { + consensus = conf.DefaultSharderConsensous + } + if len(networkDetails.Sharders) < consensus { + consensus = len(networkDetails.Sharders) + } + + Sharders = node.NewHolder(networkDetails.Sharders, consensus) + node.InitCache(Sharders) conf.InitChainNetwork(&conf.Network{ Sharders: networkDetails.Sharders, Miners: networkDetails.Miners, @@ -119,7 +127,16 @@ func SetNetwork(miners []string, sharders []string) { _config.chain.Miners = miners _config.chain.Sharders = sharders - transaction.InitCache(sharders) + consensus := _config.chain.SharderConsensous + if consensus < conf.DefaultSharderConsensous { + consensus = conf.DefaultSharderConsensous + } + if len(sharders) < consensus { + consensus = len(sharders) + } + + Sharders = node.NewHolder(sharders, consensus) + node.InitCache(Sharders) conf.InitChainNetwork(&conf.Network{ Miners: miners, diff --git a/zcncore/networkworker_mobile.go b/zcncore/networkworker_mobile.go index fee9281ae..ca0863ff8 100644 --- a/zcncore/networkworker_mobile.go +++ b/zcncore/networkworker_mobile.go @@ -9,10 +9,9 @@ import ( "reflect" "time" - "github.com/0chain/gosdk/core/transaction" - "github.com/0chain/errors" "github.com/0chain/gosdk/core/conf" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/util" "go.uber.org/zap" ) @@ -73,7 +72,16 @@ func UpdateNetworkDetails() error { _config.isConfigured = false _config.chain.Miners = networkDetails.net.Miners _config.chain.Sharders = networkDetails.net.Sharders - transaction.InitCache(networkDetails.net.Sharders) + consensus := _config.chain.SharderConsensous + if consensus < conf.DefaultSharderConsensous { + consensus = conf.DefaultSharderConsensous + } + if len(networkDetails.net.Sharders) < consensus { + consensus = len(networkDetails.net.Sharders) + } + + Sharders = node.NewHolder(networkDetails.net.Sharders, consensus) + node.InitCache(Sharders) conf.InitChainNetwork(&conf.Network{ Sharders: networkDetails.net.Sharders, Miners: networkDetails.net.Miners, @@ -131,7 +139,17 @@ func SetNetwork(net *Network) { _config.chain.Miners = net.net.Miners _config.chain.Sharders = net.net.Sharders - transaction.InitCache(net.net.Sharders) + consensus := _config.chain.SharderConsensous + if consensus < conf.DefaultSharderConsensous { + consensus = conf.DefaultSharderConsensous + } + if len(net.net.Sharders) < consensus { + consensus = len(net.net.Sharders) + } + + Sharders = node.NewHolder(_config.chain.Sharders, consensus) + + node.InitCache(Sharders) conf.InitChainNetwork(&conf.Network{ Miners: net.net.Miners, diff --git a/zcncore/transaction.go b/zcncore/transaction.go index 0f0293921..043ffcbdd 100644 --- a/zcncore/transaction.go +++ b/zcncore/transaction.go @@ -16,6 +16,7 @@ import ( "github.com/0chain/gosdk/core/block" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/core/util" ) @@ -788,9 +789,9 @@ func (t *Transaction) RegisterMultiSig(walletstr string, mswallet string) error t.txn.Value = 0 nonce := t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(t.txn.ClientID) + nonce = node.Cache.GetNextNonce(t.txn.ClientID) } else { - transaction.Cache.Set(t.txn.ClientID, nonce) + node.Cache.Set(t.txn.ClientID, nonce) } t.txn.TransactionNonce = nonce @@ -852,9 +853,9 @@ func (t *Transaction) RegisterVote(signerwalletstr string, msvstr string) error t.txn.Value = 0 nonce := t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(t.txn.ClientID) + nonce = node.Cache.GetNextNonce(t.txn.ClientID) } else { - transaction.Cache.Set(t.txn.ClientID, nonce) + node.Cache.Set(t.txn.ClientID, nonce) } t.txn.TransactionNonce = nonce @@ -955,7 +956,7 @@ func (t *Transaction) Verify() error { if t.txnHash == "" && t.txnStatus == StatusSuccess { h := t.GetTransactionHash() if h == "" { - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) return errors.New("", "invalid transaction. cannot be verified.") } } @@ -964,7 +965,7 @@ func (t *Transaction) Verify() error { t.txn.CreationDate = int64(common.Now()) } - tq, err := NewTransactionQuery(_config.chain.Sharders, _config.chain.Miners) + tq, err := NewTransactionQuery(Sharders.Healthy(), _config.chain.Miners) if err != nil { logging.Error(err) return err @@ -1058,8 +1059,8 @@ func GetLatestFinalized(ctx context.Context, numSharders int) (b *block.Header, var result = make(chan *util.GetResponse, numSharders) defer close(result) - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) var ( maxConsensus int @@ -1068,6 +1069,10 @@ func GetLatestFinalized(ctx context.Context, numSharders int) (b *block.Header, for i := 0; i < numSharders; i++ { var rsp = <-result + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) @@ -1099,8 +1104,8 @@ func GetLatestFinalizedMagicBlock(ctx context.Context, numSharders int) (m *bloc var result = make(chan *util.GetResponse, numSharders) defer close(result) - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) var ( maxConsensus int @@ -1113,6 +1118,10 @@ func GetLatestFinalizedMagicBlock(ctx context.Context, numSharders int) (m *bloc for i := 0; i < numSharders; i++ { var rsp = <-result + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) @@ -1146,11 +1155,15 @@ func GetChainStats(ctx context.Context) (b *block.ChainStats, err error) { var result = make(chan *util.GetResponse, 1) defer close(result) - var numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) + var numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) var rsp *util.GetResponse for i := 0; i < numSharders; i++ { var x = <-result + if x == nil { + logging.Error("nil response") + continue + } if x.StatusCode != http.StatusOK { continue } @@ -1206,71 +1219,11 @@ loop: } func GetBlockByRound(ctx context.Context, numSharders int, round int64) (b *block.Block, err error) { + return Sharders.GetBlockByRound(ctx, numSharders, round) +} - var result = make(chan *util.GetResponse, numSharders) - defer close(result) - - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, - fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round), - result) - - var ( - maxConsensus int - roundConsensus = make(map[string]int) - ) - - type respObj struct { - Block *block.Block `json:"block"` - Header *block.Header `json:"header"` - } - - for i := 0; i < numSharders; i++ { - var rsp = <-result - - logging.Debug(rsp.Url, rsp.Status) - - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - continue - } - - var respo respObj - if err = json.Unmarshal([]byte(rsp.Body), &respo); err != nil { - logging.Error("block parse error: ", err) - err = nil - continue - } - - if respo.Block == nil { - logging.Debug(rsp.Url, "no block in response:", rsp.Body) - continue - } - - if respo.Header == nil { - logging.Debug(rsp.Url, "no block header in response:", rsp.Body) - continue - } - - if respo.Header.Hash != string(respo.Block.Hash) { - logging.Debug(rsp.Url, "header and block hash mismatch:", rsp.Body) - continue - } - - b = respo.Block - b.Header = respo.Header - - var h = encryption.FastHash([]byte(b.Hash)) - if roundConsensus[h]++; roundConsensus[h] > maxConsensus { - maxConsensus = roundConsensus[h] - } - } - - if maxConsensus == 0 { - return nil, errors.New("", "round info not found") - } - - return +func GetRoundFromSharders() (int64, error) { + return Sharders.GetRoundFromSharders() } func GetMagicBlockByNumber(ctx context.Context, numSharders int, number int64) (m *block.MagicBlock, err error) { @@ -1278,8 +1231,8 @@ func GetMagicBlockByNumber(ctx context.Context, numSharders int, number int64) ( var result = make(chan *util.GetResponse, numSharders) defer close(result) - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, fmt.Sprintf("%smagic_block_number=%d", GET_MAGIC_BLOCK_INFO, number), result) @@ -1294,7 +1247,10 @@ func GetMagicBlockByNumber(ctx context.Context, numSharders int, number int64) ( for i := 0; i < numSharders; i++ { var rsp = <-result - + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) if rsp.StatusCode != http.StatusOK { diff --git a/zcncore/transaction_base.go b/zcncore/transaction_base.go index 2569f55ad..ac260553b 100644 --- a/zcncore/transaction_base.go +++ b/zcncore/transaction_base.go @@ -11,6 +11,7 @@ import ( "github.com/0chain/errors" "github.com/0chain/gosdk/core/common" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/zboxcore/logger" "go.uber.org/zap" @@ -113,6 +114,8 @@ type ChainConfig struct { SharderConsensous int `json:"sharder_consensous"` } +var Sharders *node.NodeHolder + // InitZCNSDK initializes the SDK with miner, sharder and signature scheme provided. func InitZCNSDK(blockWorker string, signscheme string, configs ...func(*ChainConfig) error) error { if signscheme != "ed25519" && signscheme != "bls0chain" { @@ -288,7 +291,7 @@ func (t *Transaction) completeVerifyWithConStatus(status int, conStatus int, out t.verifyOut = out t.verifyError = err if status == StatusError { - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) } if t.txnCb != nil { t.txnCb.OnVerifyComplete(t, t.verifyStatus) @@ -316,9 +319,9 @@ func (t *Transaction) setNonceAndSubmit() { func (t *Transaction) setNonce() { nonce := t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(t.txn.ClientID) + nonce = node.Cache.GetNextNonce(t.txn.ClientID) } else { - transaction.Cache.Set(t.txn.ClientID, nonce) + node.Cache.Set(t.txn.ClientID, nonce) } t.txn.TransactionNonce = nonce } @@ -334,7 +337,7 @@ func (t *Transaction) submitTxn() { err := t.txn.ComputeHashAndSign(SignFn) if err != nil { t.completeTxn(StatusError, "", err) - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) return } } @@ -386,7 +389,7 @@ func (t *Transaction) submitTxn() { case <-failC: logging.Error("failed to submit transaction") t.completeTxn(StatusError, "", fmt.Errorf("failed to submit transaction to all miners")) - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) ResetStableMiners() return case ret := <-resultC: @@ -395,7 +398,7 @@ func (t *Transaction) submitTxn() { t.completeTxn(StatusSuccess, ret.Body, nil) } else { t.completeTxn(StatusError, "", fmt.Errorf("submit transaction failed. %s", ret.Body)) - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) } } } @@ -435,7 +438,7 @@ func (t *Transaction) StoreData(data string) error { return nil } -type txnFeeOption struct { +type TxnFeeOption struct { // stop estimate txn fee, usually if txn fee was 0, the createSmartContractTxn method would // estimate the txn fee by calling API from 0chain network. With this option, we could force // the txn to have zero fee for those exempt transactions. @@ -443,11 +446,11 @@ type txnFeeOption struct { } // FeeOption represents txn fee related option type -type FeeOption func(*txnFeeOption) +type FeeOption func(*TxnFeeOption) // WithNoEstimateFee would prevent txn fee estimation from remote func WithNoEstimateFee() FeeOption { - return func(o *txnFeeOption) { + return func(o *TxnFeeOption) { o.noEstimateFee = true } } @@ -468,7 +471,7 @@ func (t *Transaction) createSmartContractTxn(address, methodName string, input i return nil } - tf := &txnFeeOption{} + tf := &TxnFeeOption{} for _, opt := range opts { opt(tf) } @@ -513,9 +516,9 @@ func (t *Transaction) ExecuteFaucetSCWallet(walletStr string, methodName string, go func() { nonce := t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(t.txn.ClientID) + nonce = node.Cache.GetNextNonce(t.txn.ClientID) } else { - transaction.Cache.Set(t.txn.ClientID, nonce) + node.Cache.Set(t.txn.ClientID, nonce) } t.txn.TransactionNonce = nonce err = t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) @@ -560,33 +563,6 @@ func (t *Transaction) GetTransactionHash() string { return t.txnHash } -func queryFromSharders(numSharders int, query string, - result chan *util.GetResponse) { - - queryFromShardersContext(context.Background(), numSharders, query, result) -} - -func queryFromShardersContext(ctx context.Context, numSharders int, - query string, result chan *util.GetResponse) { - - for _, sharder := range util.Shuffle(_config.chain.Sharders)[:numSharders] { - go func(sharderurl string) { - logging.Info("Query from ", sharderurl+query) - url := fmt.Sprintf("%v%v", sharderurl, query) - req, err := util.NewHTTPGetRequestContext(ctx, url) - if err != nil { - logging.Error(sharderurl, " new get request failed. ", err.Error()) - return - } - res, err := req.Get() - if err != nil { - logging.Error(sharderurl, " get error. ", err.Error()) - } - result <- res - }(sharder) - } -} - func queryFromMinersContext(ctx context.Context, numMiners int, query string, result chan *util.GetResponse) { randomMiners := util.Shuffle(_config.chain.Miners)[:numMiners] @@ -651,9 +627,9 @@ func getBlockHeaderFromTransactionConfirmation(txnHash string, cfmBlock map[stri } func getBlockInfoByRound(round int64, content string) (*blockHeader, error) { - numSharders := len(_config.chain.Sharders) // overwrite, use all + numSharders := len(Sharders.Healthy()) // overwrite, use all resultC := make(chan *util.GetResponse, numSharders) - queryFromSharders(numSharders, fmt.Sprintf("%vround=%v&content=%v", GET_BLOCK_INFO, round, content), resultC) + Sharders.QueryFromSharders(numSharders, fmt.Sprintf("%vround=%v&content=%v", GET_BLOCK_INFO, round, content), resultC) var ( maxConsensus int roundConsensus = make(map[string]int) @@ -670,6 +646,10 @@ func getBlockInfoByRound(round int64, content string) (*blockHeader, error) { case <-waitTime.C: return nil, stdErrors.New("failed to get block info by round with consensus, timeout") case rsp := <-resultC: + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) if failedCount*100/numSharders > 100-consensusThresh { return nil, stdErrors.New("failed to get block info by round with consensus, too many failures") @@ -723,7 +703,7 @@ func validateChain(confirmBlock *blockHeader) bool { for { nextBlock, err := getBlockInfoByRound(round, "header") if err != nil { - logging.Info(err, " after a second falling thru to ", getMinShardersVerify(), "of ", len(_config.chain.Sharders), "Sharders") + logging.Info(err, " after a second falling thru to ", getMinShardersVerify(), "of ", len(_config.chain.Sharders), "Sharders", len(Sharders.Healthy()), "Healthy sharders") sys.Sleep(1 * time.Second) nextBlock, err = getBlockInfoByRound(round, "header") if err != nil { diff --git a/zcncore/transaction_mobile.go b/zcncore/transaction_mobile.go index 2d1bf7380..52ba609be 100644 --- a/zcncore/transaction_mobile.go +++ b/zcncore/transaction_mobile.go @@ -16,6 +16,7 @@ import ( "github.com/0chain/gosdk/core/block" "github.com/0chain/gosdk/core/common" "github.com/0chain/gosdk/core/encryption" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/core/util" ) @@ -935,7 +936,7 @@ func (t *Transaction) Verify() error { if t.txnHash == "" && t.txnStatus == StatusSuccess { h := t.GetTransactionHash() if h == "" { - transaction.Cache.Evict(t.txn.ClientID) + node.Cache.Evict(t.txn.ClientID) return errors.New("", "invalid transaction. cannot be verified.") } } @@ -944,7 +945,7 @@ func (t *Transaction) Verify() error { t.txn.CreationDate = int64(common.Now()) } - tq, err := newTransactionQuery(_config.chain.Sharders) + tq, err := newTransactionQuery(Sharders.Healthy()) if err != nil { logging.Error(err) return err @@ -970,7 +971,7 @@ func (t *Transaction) Verify() error { // transaction is done or expired. it means random sharder might be outdated, try to query it from s/S sharders to confirm it if util.MaxInt64(lfbBlockHeader.getCreationDate(now), now) >= (t.txn.CreationDate + int64(defaultTxnExpirationSeconds)) { - logging.Info("falling back to ", getMinShardersVerify(), " of ", len(_config.chain.Sharders), " Sharders") + logging.Info("falling back to ", getMinShardersVerify(), " of ", len(_config.chain.Sharders), " Sharders", len(Sharders.Healthy()), "Healthy sharders") confirmBlockHeader, confirmationBlock, lfbBlockHeader, err = tq.getConsensusConfirmation(getMinShardersVerify(), t.txnHash, nil) } @@ -1076,8 +1077,8 @@ func GetLatestFinalized(numSharders int, timeout RequestTimeout) (b *BlockHeader ctx, cancel := makeTimeoutContext(timeout) defer cancel() - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED, result) var ( maxConsensus int @@ -1086,6 +1087,10 @@ func GetLatestFinalized(numSharders int, timeout RequestTimeout) (b *BlockHeader for i := 0; i < numSharders; i++ { var rsp = <-result + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) @@ -1120,8 +1125,8 @@ func GetLatestFinalizedMagicBlock(numSharders int, timeout RequestTimeout) ([]by ctx, cancel := makeTimeoutContext(timeout) defer cancel() - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_LATEST_FINALIZED_MAGIC_BLOCK, result) var ( maxConsensus int @@ -1136,6 +1141,10 @@ func GetLatestFinalizedMagicBlock(numSharders int, timeout RequestTimeout) ([]by for i := 0; i < numSharders; i++ { var rsp = <-result + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) @@ -1183,11 +1192,15 @@ func GetChainStats(timeout RequestTimeout) ([]byte, error) { err error ) - var numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) + var numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, GET_CHAIN_STATS, result) var rsp *util.GetResponse for i := 0; i < numSharders; i++ { var x = <-result + if x == nil { + logging.Error("nil response") + continue + } if x.StatusCode != http.StatusOK { continue } @@ -1426,8 +1439,8 @@ func GetBlockByRound(numSharders int, round int64, timeout RequestTimeout) (b *B ctx, cancel := makeTimeoutContext(timeout) defer cancel() - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, fmt.Sprintf("%sround=%d&content=full,header", GET_BLOCK_INFO, round), result) @@ -1443,7 +1456,10 @@ func GetBlockByRound(numSharders int, round int64, timeout RequestTimeout) (b *B for i := 0; i < numSharders; i++ { var rsp = <-result - + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) if rsp.StatusCode != http.StatusOK { @@ -1508,8 +1524,8 @@ func GetMagicBlockByNumber(numSharders int, number int64, timeout RequestTimeout ctx, cancel := makeTimeoutContext(timeout) defer cancel() - numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromShardersContext(ctx, numSharders, + numSharders = len(Sharders.Healthy()) // overwrite, use all + Sharders.QueryFromShardersContext(ctx, numSharders, fmt.Sprintf("%smagic_block_number=%d", GET_MAGIC_BLOCK_INFO, number), result) @@ -1526,6 +1542,10 @@ func GetMagicBlockByNumber(numSharders int, number int64, timeout RequestTimeout for i := 0; i < numSharders; i++ { var rsp = <-result + if rsp == nil { + logging.Error("nil response") + continue + } logging.Debug(rsp.Url, rsp.Status) diff --git a/zcncore/transaction_query.go b/zcncore/transaction_query.go index c6c17e972..797d36d6a 100644 --- a/zcncore/transaction_query.go +++ b/zcncore/transaction_query.go @@ -527,7 +527,7 @@ func (tq *TransactionQuery) getFastConfirmation(ctx context.Context, txnHash str func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { - tq, err := NewTransactionQuery(util.Shuffle(_config.chain.Sharders), []string{}) + tq, err := NewTransactionQuery(util.Shuffle(Sharders.Healthy()), []string{}) if err != nil { cb.OnInfoAvailable(op, StatusError, "", err.Error()) return @@ -544,7 +544,7 @@ func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { func GetInfoFromAnySharder(urlSuffix string, op int, cb GetInfoCallback) { - tq, err := NewTransactionQuery(util.Shuffle(_config.chain.Sharders), []string{}) + tq, err := NewTransactionQuery(util.Shuffle(Sharders.Healthy()), []string{}) if err != nil { cb.OnInfoAvailable(op, StatusError, "", err.Error()) return diff --git a/zcncore/transaction_query_mobile.go b/zcncore/transaction_query_mobile.go index 29a685480..5756b586e 100644 --- a/zcncore/transaction_query_mobile.go +++ b/zcncore/transaction_query_mobile.go @@ -458,7 +458,7 @@ func (tq *transactionQuery) getFastConfirmation(txnHash string, timeout RequestT func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { - tq, err := newTransactionQuery(util.Shuffle(_config.chain.Sharders)) + tq, err := newTransactionQuery(util.Shuffle(Sharders.Healthy())) if err != nil { cb.OnInfoAvailable(op, StatusError, "", err.Error()) return @@ -475,7 +475,7 @@ func GetInfoFromSharders(urlSuffix string, op int, cb GetInfoCallback) { func GetInfoFromAnySharder(urlSuffix string, op int, cb GetInfoCallback) { - tq, err := newTransactionQuery(util.Shuffle(_config.chain.Sharders)) + tq, err := newTransactionQuery(util.Shuffle(Sharders.Healthy())) if err != nil { cb.OnInfoAvailable(op, StatusError, "", err.Error()) return diff --git a/zcncore/transactionauth_base.go b/zcncore/transactionauth_base.go index 7b73be452..8fa166a10 100644 --- a/zcncore/transactionauth_base.go +++ b/zcncore/transactionauth_base.go @@ -4,6 +4,7 @@ import ( "encoding/json" "github.com/0chain/errors" + "github.com/0chain/gosdk/core/node" "github.com/0chain/gosdk/core/sys" "github.com/0chain/gosdk/core/transaction" "github.com/0chain/gosdk/core/zcncrypto" @@ -115,9 +116,9 @@ func (ta *TransactionWithAuth) sign(otherSig string) error { func (ta *TransactionWithAuth) submitTxn() { nonce := ta.t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(ta.t.txn.ClientID) + nonce = node.Cache.GetNextNonce(ta.t.txn.ClientID) } else { - transaction.Cache.Set(ta.t.txn.ClientID, nonce) + node.Cache.Set(ta.t.txn.ClientID, nonce) } ta.t.txn.TransactionNonce = nonce authTxn, err := ta.getAuthorize() @@ -158,9 +159,9 @@ func (ta *TransactionWithAuth) ExecuteFaucetSCWallet(walletStr string, methodNam go func() { nonce := ta.t.txn.TransactionNonce if nonce < 1 { - nonce = transaction.Cache.GetNextNonce(ta.t.txn.ClientID) + nonce = node.Cache.GetNextNonce(ta.t.txn.ClientID) } else { - transaction.Cache.Set(ta.t.txn.ClientID, nonce) + node.Cache.Set(ta.t.txn.ClientID, nonce) } ta.t.txn.TransactionNonce = nonce err = ta.t.txn.ComputeHashAndSignWithWallet(signWithWallet, w) diff --git a/zcncore/wallet_base.go b/zcncore/wallet_base.go index 90d38ed57..afb85aa98 100644 --- a/zcncore/wallet_base.go +++ b/zcncore/wallet_base.go @@ -8,7 +8,6 @@ import ( "math" "net/http" "net/url" - "os" "strconv" "strings" "sync" @@ -27,20 +26,19 @@ import ( "github.com/0chain/gosdk/zboxcore/encryption" "github.com/0chain/gosdk/zboxcore/zboxutil" openssl "github.com/Luzifer/go-openssl/v3" + "gopkg.in/natefinch/lumberjack.v2" ) const ( GET_CLIENT = `/v1/client/get` PUT_TRANSACTION = `/v1/transaction/put` TXN_VERIFY_URL = `/v1/transaction/get/confirmation?hash=` - GET_BALANCE = `/v1/client/get/balance?client_id=` GET_BLOCK_INFO = `/v1/block/get?` GET_MAGIC_BLOCK_INFO = `/v1/block/magic/get?` GET_LATEST_FINALIZED = `/v1/block/get/latest_finalized` GET_LATEST_FINALIZED_MAGIC_BLOCK = `/v1/block/get/latest_finalized_magic_block` GET_FEE_STATS = `/v1/block/get/fee_stats` GET_CHAIN_STATS = `/v1/chain/get/stats` - // vesting SC VESTINGSC_PFX = `/v1/screst/` + VestingSmartContractAddress @@ -113,8 +111,8 @@ const ( const consensusThresh = 25 const ( - defaultMinSubmit = int(50) - defaultMinConfirmation = int(50) + defaultMinSubmit = int(10) + defaultMinConfirmation = int(10) defaultConfirmationChainLength = int(3) defaultTxnExpirationSeconds = 60 defaultWaitSeconds = 3 * time.Second @@ -295,7 +293,7 @@ func GetMinShardersVerify() int { } func getMinShardersVerify() int { - minSharders := util.MaxInt(calculateMinRequired(float64(_config.chain.MinConfirmation), float64(len(_config.chain.Sharders))/100), 1) + minSharders := util.MaxInt(calculateMinRequired(float64(_config.chain.MinConfirmation), float64(len(Sharders.Healthy()))/100), 1) logging.Info("Minimum sharders used for verify :", minSharders) return minSharders } @@ -321,11 +319,15 @@ func SetLogLevel(lvl int) { // SetLogFile - sets file path to write log // verbose - true - console output; false - no console output func SetLogFile(logFile string, verbose bool) { - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return - } - logging.SetLogFile(f, verbose) + ioWriter := &lumberjack.Logger{ + Filename: logFile, + MaxSize: 100, // MB + MaxBackups: 5, // number of backups + MaxAge: 28, //days + LocalTime: false, + Compress: false, // disabled by default + } + logging.SetLogFile(ioWriter, verbose) logging.Info("******* Wallet SDK Version:", version.VERSIONSTR, " ******* (SetLogFile)") } @@ -708,57 +710,11 @@ func GetBalanceWallet(walletStr string, cb GetBalanceCallback) error { } func getBalanceFromSharders(clientID string) (int64, string, error) { - return getBalanceFieldFromSharders(clientID, "balance") + return Sharders.GetBalanceFieldFromSharders(clientID, "balance") } func getNonceFromSharders(clientID string) (int64, string, error) { - return getBalanceFieldFromSharders(clientID, "nonce") -} - -func getBalanceFieldFromSharders(clientID, name string) (int64, string, error) { - result := make(chan *util.GetResponse) - defer close(result) - // getMinShardersVerify - var numSharders = len(_config.chain.Sharders) // overwrite, use all - queryFromSharders(numSharders, fmt.Sprintf("%v%v", GET_BALANCE, clientID), result) - - consensusMaps := NewHttpConsensusMaps(consensusThresh) - - for i := 0; i < numSharders; i++ { - rsp := <-result - - logging.Debug(rsp.Url, rsp.Status) - if rsp.StatusCode != http.StatusOK { - logging.Error(rsp.Body) - - } else { - logging.Debug(rsp.Body) - } - - if err := consensusMaps.Add(rsp.StatusCode, rsp.Body); err != nil { - logging.Error(rsp.Body) - } - } - - rate := consensusMaps.MaxConsensus * 100 / len(_config.chain.Sharders) - if rate < consensusThresh { - if strings.TrimSpace(consensusMaps.WinError) == `{"error":"value not present"}` { - return 0, consensusMaps.WinError, nil - } - return 0, consensusMaps.WinError, errors.New("", "get balance failed. consensus not reached") - } - - winValue, ok := consensusMaps.GetValue(name) - if ok { - winBalance, err := strconv.ParseInt(string(winValue), 10, 64) - if err != nil { - return 0, "", fmt.Errorf("get balance failed. %w", err) - } - - return winBalance, consensusMaps.WinInfo, nil - } - - return 0, consensusMaps.WinInfo, errors.New("", "get balance failed. balance field is missed") + return Sharders.GetBalanceFieldFromSharders(clientID, "nonce") } // ConvertToToken converts the SAS tokens to ZCN tokens diff --git a/zcnswap/config/config.go b/zcnswap/config/config.go deleted file mode 100644 index 0d1b0182b..000000000 --- a/zcnswap/config/config.go +++ /dev/null @@ -1,69 +0,0 @@ -package config - -import ( - "errors" - "os" - - thrown "github.com/0chain/errors" - "github.com/0chain/gosdk/core/conf" - "github.com/0chain/gosdk/core/sys" - "github.com/spf13/viper" -) - -var Configuration SwapConfig - -type SwapConfig struct { - BancorAddress string - UsdcTokenAddress string - ZcnTokenAddress string - WalletMnemonic string -} - -func Init(file string) error { - var err error - Configuration, err = loadConfigFile(file) - - return err -} - -func SetWalletMnemonic(mnemonic string) { - Configuration.WalletMnemonic = mnemonic -} - -// LoadConfigFile load and parse Config from file -func loadConfigFile(file string) (SwapConfig, error) { - - var cfg SwapConfig - var err error - - _, err = sys.Files.Stat(file) - - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return cfg, thrown.Throw(conf.ErrMssingConfig, file) - } - return cfg, err - } - - v := viper.New() - - v.SetConfigFile(file) - - if err := v.ReadInConfig(); err != nil { - return cfg, thrown.Throw(conf.ErrBadParsing, err.Error()) - } - - return loadConfig(v) -} - -// LoadConfig load and parse config -func loadConfig(v conf.Reader) (SwapConfig, error) { - - var cfg SwapConfig - - cfg.UsdcTokenAddress = v.GetString("zcnswap.usdc_token_address") - cfg.BancorAddress = v.GetString("zcnswap.bancor_address") - cfg.ZcnTokenAddress = v.GetString("zcnswap.zcn_token_address") - - return cfg, nil -} diff --git a/zcnswap/contracts/IERC20.sol b/zcnswap/contracts/IERC20.sol deleted file mode 100755 index a23208dae..000000000 --- a/zcnswap/contracts/IERC20.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity 0.8.9; -pragma abicoder v2; - -interface IERC20 { - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - function approve(address spender, uint256 tokens) - external - returns (bool success); -} diff --git a/zcnswap/contracts/IQuoter.sol b/zcnswap/contracts/IQuoter.sol deleted file mode 100755 index ed7fd2a67..000000000 --- a/zcnswap/contracts/IQuoter.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity >=0.7.5; -pragma abicoder v2; - -/// @title Quoter Interface -/// @notice Supports quoting the calculated amounts from exact input or exact output swaps -/// @dev These functions are not marked view because they rely on calling non-view functions and reverting -/// to compute the result. They are also not gas efficient and should not be called on-chain. -interface IQuoter { - /// @notice Returns the amount out received for a given exact input swap without executing the swap - /// @param path The path of the swap, i.e. each token pair and the pool fee - /// @param amountIn The amount of the first token to swap - /// @return amountOut The amount of the last token that would be received - function quoteExactInput(bytes memory path, uint256 amountIn) - external - returns (uint256 amountOut); - - /// @notice Returns the amount out received for a given exact input but for a swap of a single pool - /// @param tokenIn The token being swapped in - /// @param tokenOut The token being swapped out - /// @param fee The fee of the token pool to consider for the pair - /// @param amountIn The desired input amount - /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap - /// @return amountOut The amount of `tokenOut` that would be received - function quoteExactInputSingle( - address tokenIn, - address tokenOut, - uint24 fee, - uint256 amountIn, - uint160 sqrtPriceLimitX96 - ) external returns (uint256 amountOut); - - /// @notice Returns the amount in required for a given exact output swap without executing the swap - /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order - /// @param amountOut The amount of the last token to receive - /// @return amountIn The amount of first token required to be paid - function quoteExactOutput(bytes memory path, uint256 amountOut) - external - returns (uint256 amountIn); - - /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool - /// @param tokenIn The token being swapped in - /// @param tokenOut The token being swapped out - /// @param fee The fee of the token pool to consider for the pair - /// @param amountOut The desired output amount - /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap - /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` - function quoteExactOutputSingle( - address tokenIn, - address tokenOut, - uint24 fee, - uint256 amountOut, - uint160 sqrtPriceLimitX96 - ) external returns (uint256 amountIn); -} diff --git a/zcnswap/contracts/ISwapRouter.sol b/zcnswap/contracts/ISwapRouter.sol deleted file mode 100755 index 1e4207143..000000000 --- a/zcnswap/contracts/ISwapRouter.sol +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity >=0.7.5; -pragma abicoder v2; - -import "./IUniswapV3SwapCallback.sol"; - -/// @title Router token swapping functionality -/// @notice Functions for swapping tokens via Uniswap V3 -interface ISwapRouter is IUniswapV3SwapCallback { - struct ExactInputSingleParams { - address tokenIn; - address tokenOut; - uint24 fee; - address recipient; - uint256 deadline; - uint256 amountIn; - uint256 amountOutMinimum; - uint160 sqrtPriceLimitX96; - } - - /// @notice Swaps `amountIn` of one token for as much as possible of another token - /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata - /// @return amountOut The amount of the received token - function exactInputSingle(ExactInputSingleParams calldata params) - external - payable - returns (uint256 amountOut); - - struct ExactInputParams { - bytes path; - address recipient; - uint256 deadline; - uint256 amountIn; - uint256 amountOutMinimum; - } - - /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path - /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata - /// @return amountOut The amount of the received token - function exactInput(ExactInputParams calldata params) - external - payable - returns (uint256 amountOut); - - struct ExactOutputSingleParams { - address tokenIn; - address tokenOut; - uint24 fee; - address recipient; - uint256 deadline; - uint256 amountOut; - uint256 amountInMaximum; - uint160 sqrtPriceLimitX96; - } - - /// @notice Swaps as little as possible of one token for `amountOut` of another token - /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata - /// @return amountIn The amount of the input token - function exactOutputSingle(ExactOutputSingleParams calldata params) - external - payable - returns (uint256 amountIn); - - struct ExactOutputParams { - bytes path; - address recipient; - uint256 deadline; - uint256 amountOut; - uint256 amountInMaximum; - } - - /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) - /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata - /// @return amountIn The amount of the input token - function exactOutput(ExactOutputParams calldata params) - external - payable - returns (uint256 amountIn); -} diff --git a/zcnswap/contracts/bancor.go b/zcnswap/contracts/bancor.go deleted file mode 100755 index 8b78c5809..000000000 --- a/zcnswap/contracts/bancor.go +++ /dev/null @@ -1,445 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// IBancorNetworkMetaData contains all meta data concerning the IBancorNetwork contract. -var IBancorNetworkMetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"contractIReserveToken\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"contractIReserveToken\",\"name\":\"targetToken\",\"type\":\"address\"}],\"name\":\"conversionPath\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturn\",\"type\":\"uint256\"},{\"internalType\":\"addresspayable\",\"name\":\"beneficiary\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"affiliateAccount\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"affiliateFee\",\"type\":\"uint256\"}],\"name\":\"convertByPath\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"minReturn\",\"type\":\"uint256\"},{\"internalType\":\"addresspayable\",\"name\":\"beneficiary\",\"type\":\"address\"}],\"name\":\"convertByPath2\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"sourceAmount\",\"type\":\"uint256\"}],\"name\":\"rateByPath\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "d734fa19": "conversionPath(address,address)", - "b77d239b": "convertByPath(address[],uint256,uint256,address,address,uint256)", - "f8394fb7": "convertByPath2(address[],uint256,uint256,address)", - "7f9c0ecd": "rateByPath(address[],uint256)", - }, -} - -// IBancorNetworkABI is the input ABI used to generate the binding from. -// Deprecated: Use IBancorNetworkMetaData.ABI instead. -var IBancorNetworkABI = IBancorNetworkMetaData.ABI - -// Deprecated: Use IBancorNetworkMetaData.Sigs instead. -// IBancorNetworkFuncSigs maps the 4-byte function signature to its string representation. -var IBancorNetworkFuncSigs = IBancorNetworkMetaData.Sigs - -// IBancorNetwork is an auto generated Go binding around an Ethereum contract. -type IBancorNetwork struct { - IBancorNetworkCaller // Read-only binding to the contract - IBancorNetworkTransactor // Write-only binding to the contract - IBancorNetworkFilterer // Log filterer for contract events -} - -// IBancorNetworkCaller is an auto generated read-only Go binding around an Ethereum contract. -type IBancorNetworkCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IBancorNetworkTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IBancorNetworkFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IBancorNetworkSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IBancorNetworkSession struct { - Contract *IBancorNetwork // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IBancorNetworkCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IBancorNetworkCallerSession struct { - Contract *IBancorNetworkCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IBancorNetworkTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IBancorNetworkTransactorSession struct { - Contract *IBancorNetworkTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IBancorNetworkRaw is an auto generated low-level Go binding around an Ethereum contract. -type IBancorNetworkRaw struct { - Contract *IBancorNetwork // Generic contract binding to access the raw methods on -} - -// IBancorNetworkCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IBancorNetworkCallerRaw struct { - Contract *IBancorNetworkCaller // Generic read-only contract binding to access the raw methods on -} - -// IBancorNetworkTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IBancorNetworkTransactorRaw struct { - Contract *IBancorNetworkTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIBancorNetwork creates a new instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetwork(address common.Address, backend bind.ContractBackend) (*IBancorNetwork, error) { - contract, err := bindIBancorNetwork(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IBancorNetwork{IBancorNetworkCaller: IBancorNetworkCaller{contract: contract}, IBancorNetworkTransactor: IBancorNetworkTransactor{contract: contract}, IBancorNetworkFilterer: IBancorNetworkFilterer{contract: contract}}, nil -} - -// NewIBancorNetworkCaller creates a new read-only instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkCaller(address common.Address, caller bind.ContractCaller) (*IBancorNetworkCaller, error) { - contract, err := bindIBancorNetwork(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IBancorNetworkCaller{contract: contract}, nil -} - -// NewIBancorNetworkTransactor creates a new write-only instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkTransactor(address common.Address, transactor bind.ContractTransactor) (*IBancorNetworkTransactor, error) { - contract, err := bindIBancorNetwork(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IBancorNetworkTransactor{contract: contract}, nil -} - -// NewIBancorNetworkFilterer creates a new log filterer instance of IBancorNetwork, bound to a specific deployed contract. -func NewIBancorNetworkFilterer(address common.Address, filterer bind.ContractFilterer) (*IBancorNetworkFilterer, error) { - contract, err := bindIBancorNetwork(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IBancorNetworkFilterer{contract: contract}, nil -} - -// bindIBancorNetwork binds a generic wrapper to an already deployed contract. -func bindIBancorNetwork(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IBancorNetworkABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IBancorNetwork *IBancorNetworkRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IBancorNetwork.Contract.IBancorNetworkCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IBancorNetwork *IBancorNetworkRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IBancorNetwork.Contract.IBancorNetworkTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IBancorNetwork *IBancorNetworkRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IBancorNetwork.Contract.IBancorNetworkTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IBancorNetwork *IBancorNetworkCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IBancorNetwork.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IBancorNetwork *IBancorNetworkTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IBancorNetwork.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IBancorNetwork *IBancorNetworkTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IBancorNetwork.Contract.contract.Transact(opts, method, params...) -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkCaller) ConversionPath(opts *bind.CallOpts, sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - var out []interface{} - err := _IBancorNetwork.contract.Call(opts, &out, "conversionPath", sourceToken, targetToken) - - if err != nil { - return *new([]common.Address), err - } - - out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) - - return out0, err - -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkSession) ConversionPath(sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - return _IBancorNetwork.Contract.ConversionPath(&_IBancorNetwork.CallOpts, sourceToken, targetToken) -} - -// ConversionPath is a free data retrieval call binding the contract method 0xd734fa19. -// -// Solidity: function conversionPath(address sourceToken, address targetToken) view returns(address[]) -func (_IBancorNetwork *IBancorNetworkCallerSession) ConversionPath(sourceToken common.Address, targetToken common.Address) ([]common.Address, error) { - return _IBancorNetwork.Contract.ConversionPath(&_IBancorNetwork.CallOpts, sourceToken, targetToken) -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkCaller) RateByPath(opts *bind.CallOpts, path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - var out []interface{} - err := _IBancorNetwork.contract.Call(opts, &out, "rateByPath", path, sourceAmount) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) RateByPath(path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - return _IBancorNetwork.Contract.RateByPath(&_IBancorNetwork.CallOpts, path, sourceAmount) -} - -// RateByPath is a free data retrieval call binding the contract method 0x7f9c0ecd. -// -// Solidity: function rateByPath(address[] path, uint256 sourceAmount) view returns(uint256) -func (_IBancorNetwork *IBancorNetworkCallerSession) RateByPath(path []common.Address, sourceAmount *big.Int) (*big.Int, error) { - return _IBancorNetwork.Contract.RateByPath(&_IBancorNetwork.CallOpts, path, sourceAmount) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactor) ConvertByPath(opts *bind.TransactOpts, path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.contract.Transact(opts, "convertByPath", path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) ConvertByPath(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath is a paid mutator transaction binding the contract method 0xb77d239b. -// -// Solidity: function convertByPath(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary, address affiliateAccount, uint256 affiliateFee) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactorSession) ConvertByPath(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address, affiliateAccount common.Address, affiliateFee *big.Int) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary, affiliateAccount, affiliateFee) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactor) ConvertByPath2(opts *bind.TransactOpts, path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.contract.Transact(opts, "convertByPath2", path, sourceAmount, minReturn, beneficiary) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkSession) ConvertByPath2(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath2(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary) -} - -// ConvertByPath2 is a paid mutator transaction binding the contract method 0xf8394fb7. -// -// Solidity: function convertByPath2(address[] path, uint256 sourceAmount, uint256 minReturn, address beneficiary) payable returns(uint256) -func (_IBancorNetwork *IBancorNetworkTransactorSession) ConvertByPath2(path []common.Address, sourceAmount *big.Int, minReturn *big.Int, beneficiary common.Address) (*types.Transaction, error) { - return _IBancorNetwork.Contract.ConvertByPath2(&_IBancorNetwork.TransactOpts, path, sourceAmount, minReturn, beneficiary) -} - -// IReserveTokenMetaData contains all meta data concerning the IReserveToken contract. -var IReserveTokenMetaData = &bind.MetaData{ - ABI: "[]", -} - -// IReserveTokenABI is the input ABI used to generate the binding from. -// Deprecated: Use IReserveTokenMetaData.ABI instead. -var IReserveTokenABI = IReserveTokenMetaData.ABI - -// IReserveToken is an auto generated Go binding around an Ethereum contract. -type IReserveToken struct { - IReserveTokenCaller // Read-only binding to the contract - IReserveTokenTransactor // Write-only binding to the contract - IReserveTokenFilterer // Log filterer for contract events -} - -// IReserveTokenCaller is an auto generated read-only Go binding around an Ethereum contract. -type IReserveTokenCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IReserveTokenTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IReserveTokenFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IReserveTokenSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IReserveTokenSession struct { - Contract *IReserveToken // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IReserveTokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IReserveTokenCallerSession struct { - Contract *IReserveTokenCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IReserveTokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IReserveTokenTransactorSession struct { - Contract *IReserveTokenTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IReserveTokenRaw is an auto generated low-level Go binding around an Ethereum contract. -type IReserveTokenRaw struct { - Contract *IReserveToken // Generic contract binding to access the raw methods on -} - -// IReserveTokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IReserveTokenCallerRaw struct { - Contract *IReserveTokenCaller // Generic read-only contract binding to access the raw methods on -} - -// IReserveTokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IReserveTokenTransactorRaw struct { - Contract *IReserveTokenTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIReserveToken creates a new instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveToken(address common.Address, backend bind.ContractBackend) (*IReserveToken, error) { - contract, err := bindIReserveToken(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IReserveToken{IReserveTokenCaller: IReserveTokenCaller{contract: contract}, IReserveTokenTransactor: IReserveTokenTransactor{contract: contract}, IReserveTokenFilterer: IReserveTokenFilterer{contract: contract}}, nil -} - -// NewIReserveTokenCaller creates a new read-only instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenCaller(address common.Address, caller bind.ContractCaller) (*IReserveTokenCaller, error) { - contract, err := bindIReserveToken(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IReserveTokenCaller{contract: contract}, nil -} - -// NewIReserveTokenTransactor creates a new write-only instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*IReserveTokenTransactor, error) { - contract, err := bindIReserveToken(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IReserveTokenTransactor{contract: contract}, nil -} - -// NewIReserveTokenFilterer creates a new log filterer instance of IReserveToken, bound to a specific deployed contract. -func NewIReserveTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*IReserveTokenFilterer, error) { - contract, err := bindIReserveToken(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IReserveTokenFilterer{contract: contract}, nil -} - -// bindIReserveToken binds a generic wrapper to an already deployed contract. -func bindIReserveToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IReserveTokenABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IReserveToken *IReserveTokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IReserveToken.Contract.IReserveTokenCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IReserveToken *IReserveTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IReserveToken.Contract.IReserveTokenTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IReserveToken *IReserveTokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IReserveToken.Contract.IReserveTokenTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IReserveToken *IReserveTokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IReserveToken.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IReserveToken *IReserveTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IReserveToken.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IReserveToken *IReserveTokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IReserveToken.Contract.contract.Transact(opts, method, params...) -} diff --git a/zcnswap/contracts/erc20.go b/zcnswap/contracts/erc20.go deleted file mode 100755 index c87028f5d..000000000 --- a/zcnswap/contracts/erc20.go +++ /dev/null @@ -1,2319 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "errors" - "math/big" - "strings" - - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = errors.New - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// ContextMetaData contains all meta data concerning the Context contract. -var ContextMetaData = &bind.MetaData{ - ABI: "[]", -} - -// ContextABI is the input ABI used to generate the binding from. -// Deprecated: Use ContextMetaData.ABI instead. -var ContextABI = ContextMetaData.ABI - -// Context is an auto generated Go binding around an Ethereum contract. -type Context struct { - ContextCaller // Read-only binding to the contract - ContextTransactor // Write-only binding to the contract - ContextFilterer // Log filterer for contract events -} - -// ContextCaller is an auto generated read-only Go binding around an Ethereum contract. -type ContextCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ContextTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ContextFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ContextSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ContextSession struct { - Contract *Context // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ContextCallerSession struct { - Contract *ContextCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ContextTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ContextTransactorSession struct { - Contract *ContextTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ContextRaw is an auto generated low-level Go binding around an Ethereum contract. -type ContextRaw struct { - Contract *Context // Generic contract binding to access the raw methods on -} - -// ContextCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ContextCallerRaw struct { - Contract *ContextCaller // Generic read-only contract binding to access the raw methods on -} - -// ContextTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ContextTransactorRaw struct { - Contract *ContextTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewContext creates a new instance of Context, bound to a specific deployed contract. -func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) { - contract, err := bindContext(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil -} - -// NewContextCaller creates a new read-only instance of Context, bound to a specific deployed contract. -func NewContextCaller(address common.Address, caller bind.ContractCaller) (*ContextCaller, error) { - contract, err := bindContext(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ContextCaller{contract: contract}, nil -} - -// NewContextTransactor creates a new write-only instance of Context, bound to a specific deployed contract. -func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) { - contract, err := bindContext(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ContextTransactor{contract: contract}, nil -} - -// NewContextFilterer creates a new log filterer instance of Context, bound to a specific deployed contract. -func NewContextFilterer(address common.Address, filterer bind.ContractFilterer) (*ContextFilterer, error) { - contract, err := bindContext(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ContextFilterer{contract: contract}, nil -} - -// bindContext binds a generic wrapper to an already deployed contract. -func bindContext(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ContextABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.ContextCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.ContextTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Context *ContextCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Context.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Context *ContextTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Context.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Context *ContextTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Context.Contract.contract.Transact(opts, method, params...) -} - -// ERC20MetaData contains all meta data concerning the ERC20 contract. -var ERC20MetaData = &bind.MetaData{ - ABI: "[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"name_\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"symbol_\",\"type\":\"string\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "a457c2d7": "decreaseAllowance(address,uint256)", - "39509351": "increaseAllowance(address,uint256)", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, - Bin: "0x60806040523480156200001157600080fd5b5060405162000b5638038062000b568339810160408190526200003491620001db565b81516200004990600390602085019062000068565b5080516200005f90600490602084019062000068565b50505062000282565b828054620000769062000245565b90600052602060002090601f0160209004810192826200009a5760008555620000e5565b82601f10620000b557805160ff1916838001178555620000e5565b82800160010185558215620000e5579182015b82811115620000e5578251825591602001919060010190620000c8565b50620000f3929150620000f7565b5090565b5b80821115620000f35760008155600101620000f8565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200013657600080fd5b81516001600160401b03808211156200015357620001536200010e565b604051601f8301601f19908116603f011681019082821181831017156200017e576200017e6200010e565b816040528381526020925086838588010111156200019b57600080fd5b600091505b83821015620001bf5785820183015181830184015290820190620001a0565b83821115620001d15760008385830101525b9695505050505050565b60008060408385031215620001ef57600080fd5b82516001600160401b03808211156200020757600080fd5b620002158683870162000124565b935060208501519150808211156200022c57600080fd5b506200023b8582860162000124565b9150509250929050565b600181811c908216806200025a57607f821691505b602082108114156200027c57634e487b7160e01b600052602260045260246000fd5b50919050565b6108c480620002926000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461012357806370a082311461013657806395d89b411461015f578063a457c2d714610167578063a9059cbb1461017a578063dd62ed3e1461018d57600080fd5b806306fdde03146100ae578063095ea7b3146100cc57806318160ddd146100ef57806323b872dd14610101578063313ce56714610114575b600080fd5b6100b66101c6565b6040516100c39190610701565b60405180910390f35b6100df6100da366004610772565b610258565b60405190151581526020016100c3565b6002545b6040519081526020016100c3565b6100df61010f36600461079c565b61026e565b604051601281526020016100c3565b6100df610131366004610772565b61031d565b6100f36101443660046107d8565b6001600160a01b031660009081526020819052604090205490565b6100b6610359565b6100df610175366004610772565b610368565b6100df610188366004610772565b610401565b6100f361019b3660046107fa565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6060600380546101d59061082d565b80601f01602080910402602001604051908101604052809291908181526020018280546102019061082d565b801561024e5780601f106102235761010080835404028352916020019161024e565b820191906000526020600020905b81548152906001019060200180831161023157829003601f168201915b5050505050905090565b600061026533848461040e565b50600192915050565b600061027b848484610532565b6001600160a01b0384166000908152600160209081526040808320338452909152902054828110156103055760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e74206578636565647320616044820152676c6c6f77616e636560c01b60648201526084015b60405180910390fd5b610312853385840361040e565b506001949350505050565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091610265918590610354908690610868565b61040e565b6060600480546101d59061082d565b3360009081526001602090815260408083206001600160a01b0386168452909152812054828110156103ea5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016102fc565b6103f7338585840361040e565b5060019392505050565b6000610265338484610532565b6001600160a01b0383166104705760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016102fc565b6001600160a01b0382166104d15760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016102fc565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166105965760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016102fc565b6001600160a01b0382166105f85760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016102fc565b6001600160a01b038316600090815260208190526040902054818110156106705760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016102fc565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906106a7908490610868565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516106f391815260200190565b60405180910390a350505050565b600060208083528351808285015260005b8181101561072e57858101830151858201604001528201610712565b81811115610740576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b038116811461076d57600080fd5b919050565b6000806040838503121561078557600080fd5b61078e83610756565b946020939093013593505050565b6000806000606084860312156107b157600080fd5b6107ba84610756565b92506107c860208501610756565b9150604084013590509250925092565b6000602082840312156107ea57600080fd5b6107f382610756565b9392505050565b6000806040838503121561080d57600080fd5b61081683610756565b915061082460208401610756565b90509250929050565b600181811c9082168061084157607f821691505b6020821081141561086257634e487b7160e01b600052602260045260246000fd5b50919050565b6000821982111561088957634e487b7160e01b600052601160045260246000fd5b50019056fea26469706673582212203a382710d330bfc5c08286d13b123167071c03a623c45f800ccb995904d07eef64736f6c63430008090033", -} - -// ERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use ERC20MetaData.ABI instead. -var ERC20ABI = ERC20MetaData.ABI - -// Deprecated: Use ERC20MetaData.Sigs instead. -// ERC20FuncSigs maps the 4-byte function signature to its string representation. -var ERC20FuncSigs = ERC20MetaData.Sigs - -// ERC20Bin is the compiled bytecode used for deploying new contracts. -// Deprecated: Use ERC20MetaData.Bin instead. -var ERC20Bin = ERC20MetaData.Bin - -// DeployERC20 deploys a new Ethereum contract, binding an instance of ERC20 to it. -func DeployERC20(auth *bind.TransactOpts, backend bind.ContractBackend, name_ string, symbol_ string) (common.Address, *types.Transaction, *ERC20, error) { - parsed, err := ERC20MetaData.GetAbi() - if err != nil { - return common.Address{}, nil, nil, err - } - if parsed == nil { - return common.Address{}, nil, nil, errors.New("GetABI returned nil") - } - - address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(ERC20Bin), backend, name_, symbol_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// ERC20 is an auto generated Go binding around an Ethereum contract. -type ERC20 struct { - ERC20Caller // Read-only binding to the contract - ERC20Transactor // Write-only binding to the contract - ERC20Filterer // Log filterer for contract events -} - -// ERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type ERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type ERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ERC20Session struct { - Contract *ERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ERC20CallerSession struct { - Contract *ERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ERC20TransactorSession struct { - Contract *ERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type ERC20Raw struct { - Contract *ERC20 // Generic contract binding to access the raw methods on -} - -// ERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ERC20CallerRaw struct { - Contract *ERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// ERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ERC20TransactorRaw struct { - Contract *ERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewERC20 creates a new instance of ERC20, bound to a specific deployed contract. -func NewERC20(address common.Address, backend bind.ContractBackend) (*ERC20, error) { - contract, err := bindERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ERC20{ERC20Caller: ERC20Caller{contract: contract}, ERC20Transactor: ERC20Transactor{contract: contract}, ERC20Filterer: ERC20Filterer{contract: contract}}, nil -} - -// NewERC20Caller creates a new read-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Caller(address common.Address, caller bind.ContractCaller) (*ERC20Caller, error) { - contract, err := bindERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ERC20Caller{contract: contract}, nil -} - -// NewERC20Transactor creates a new write-only instance of ERC20, bound to a specific deployed contract. -func NewERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*ERC20Transactor, error) { - contract, err := bindERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ERC20Transactor{contract: contract}, nil -} - -// NewERC20Filterer creates a new log filterer instance of ERC20, bound to a specific deployed contract. -func NewERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*ERC20Filterer, error) { - contract, err := bindERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ERC20Filterer{contract: contract}, nil -} - -// bindERC20 binds a generic wrapper to an already deployed contract. -func bindERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.ERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.ERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ERC20 *ERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ERC20 *ERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ERC20 *ERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _ERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_ERC20 *ERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _ERC20.Contract.Allowance(&_ERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_ERC20 *ERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _ERC20.Contract.BalanceOf(&_ERC20.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Caller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20Session) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_ERC20 *ERC20CallerSession) Decimals() (uint8, error) { - return _ERC20.Contract.Decimals(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Caller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20Session) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_ERC20 *ERC20CallerSession) Name() (string, error) { - return _ERC20.Contract.Name(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Caller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20Session) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_ERC20 *ERC20CallerSession) Symbol() (string, error) { - return _ERC20.Contract.Symbol(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _ERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20Session) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_ERC20 *ERC20CallerSession) TotalSupply() (*big.Int, error) { - return _ERC20.Contract.TotalSupply(&_ERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Approve(&_ERC20.TransactOpts, spender, amount) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Transactor) DecreaseAllowance(opts *bind.TransactOpts, spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "decreaseAllowance", spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20Session) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// DecreaseAllowance is a paid mutator transaction binding the contract method 0xa457c2d7. -// -// Solidity: function decreaseAllowance(address spender, uint256 subtractedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) DecreaseAllowance(spender common.Address, subtractedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.DecreaseAllowance(&_ERC20.TransactOpts, spender, subtractedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "increaseAllowance", spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20Session) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// IncreaseAllowance is a paid mutator transaction binding the contract method 0x39509351. -// -// Solidity: function increaseAllowance(address spender, uint256 addedValue) returns(bool) -func (_ERC20 *ERC20TransactorSession) IncreaseAllowance(spender common.Address, addedValue *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.IncreaseAllowance(&_ERC20.TransactOpts, spender, addedValue) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.Transfer(&_ERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_ERC20 *ERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _ERC20.Contract.TransferFrom(&_ERC20.TransactOpts, sender, recipient, amount) -} - -// ERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the ERC20 contract. -type ERC20ApprovalIterator struct { - Event *ERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Approval represents a Approval event raised by the ERC20 contract. -type ERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*ERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &ERC20ApprovalIterator{contract: _ERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *ERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_ERC20 *ERC20Filterer) ParseApproval(log types.Log) (*ERC20Approval, error) { - event := new(ERC20Approval) - if err := _ERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// ERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the ERC20 contract. -type ERC20TransferIterator struct { - Event *ERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ERC20Transfer represents a Transfer event raised by the ERC20 contract. -type ERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*ERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &ERC20TransferIterator{contract: _ERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _ERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_ERC20 *ERC20Filterer) ParseTransfer(log types.Log) (*ERC20Transfer, error) { - event := new(ERC20Transfer) - if err := _ERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetaData contains all meta data concerning the IERC20 contract. -var IERC20MetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20ABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetaData.ABI instead. -var IERC20ABI = IERC20MetaData.ABI - -// Deprecated: Use IERC20MetaData.Sigs instead. -// IERC20FuncSigs maps the 4-byte function signature to its string representation. -var IERC20FuncSigs = IERC20MetaData.Sigs - -// IERC20 is an auto generated Go binding around an Ethereum contract. -type IERC20 struct { - IERC20Caller // Read-only binding to the contract - IERC20Transactor // Write-only binding to the contract - IERC20Filterer // Log filterer for contract events -} - -// IERC20Caller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20Caller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Transactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20Transactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Filterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20Filterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20Session is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20Session struct { - Contract *IERC20 // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20CallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20CallerSession struct { - Contract *IERC20Caller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20TransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20TransactorSession struct { - Contract *IERC20Transactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20Raw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20Raw struct { - Contract *IERC20 // Generic contract binding to access the raw methods on -} - -// IERC20CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20CallerRaw struct { - Contract *IERC20Caller // Generic read-only contract binding to access the raw methods on -} - -// IERC20TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20TransactorRaw struct { - Contract *IERC20Transactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20 creates a new instance of IERC20, bound to a specific deployed contract. -func NewIERC20(address common.Address, backend bind.ContractBackend) (*IERC20, error) { - contract, err := bindIERC20(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20{IERC20Caller: IERC20Caller{contract: contract}, IERC20Transactor: IERC20Transactor{contract: contract}, IERC20Filterer: IERC20Filterer{contract: contract}}, nil -} - -// NewIERC20Caller creates a new read-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Caller(address common.Address, caller bind.ContractCaller) (*IERC20Caller, error) { - contract, err := bindIERC20(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20Caller{contract: contract}, nil -} - -// NewIERC20Transactor creates a new write-only instance of IERC20, bound to a specific deployed contract. -func NewIERC20Transactor(address common.Address, transactor bind.ContractTransactor) (*IERC20Transactor, error) { - contract, err := bindIERC20(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20Transactor{contract: contract}, nil -} - -// NewIERC20Filterer creates a new log filterer instance of IERC20, bound to a specific deployed contract. -func NewIERC20Filterer(address common.Address, filterer bind.ContractFilterer) (*IERC20Filterer, error) { - contract, err := bindIERC20(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20Filterer{contract: contract}, nil -} - -// bindIERC20 binds a generic wrapper to an already deployed contract. -func bindIERC20(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20ABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.IERC20Caller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.IERC20Transactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20 *IERC20CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20 *IERC20TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20 *IERC20TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Caller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20Session) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20 *IERC20CallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20.Contract.Allowance(&_IERC20.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Caller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20Session) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20 *IERC20CallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20.Contract.BalanceOf(&_IERC20.CallOpts, account) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Caller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20Session) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20 *IERC20CallerSession) TotalSupply() (*big.Int, error) { - return _IERC20.Contract.TotalSupply(&_IERC20.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Approve(&_IERC20.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.Transfer(&_IERC20.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Transactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20Session) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20 *IERC20TransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20.Contract.TransferFrom(&_IERC20.TransactOpts, sender, recipient, amount) -} - -// IERC20ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20 contract. -type IERC20ApprovalIterator struct { - Event *IERC20Approval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20ApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Approval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20ApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20ApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Approval represents a Approval event raised by the IERC20 contract. -type IERC20Approval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20ApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20ApprovalIterator{contract: _IERC20.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20Approval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20 *IERC20Filterer) ParseApproval(log types.Log) (*IERC20Approval, error) { - event := new(IERC20Approval) - if err := _IERC20.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20TransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20 contract. -type IERC20TransferIterator struct { - Event *IERC20Transfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20TransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20Transfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20TransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20TransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20Transfer represents a Transfer event raised by the IERC20 contract. -type IERC20Transfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20TransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20TransferIterator{contract: _IERC20.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20Transfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20 *IERC20Filterer) ParseTransfer(log types.Log) (*IERC20Transfer, error) { - event := new(IERC20Transfer) - if err := _IERC20.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataMetaData contains all meta data concerning the IERC20Metadata contract. -var IERC20MetadataMetaData = &bind.MetaData{ - ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", - Sigs: map[string]string{ - "dd62ed3e": "allowance(address,address)", - "095ea7b3": "approve(address,uint256)", - "70a08231": "balanceOf(address)", - "313ce567": "decimals()", - "06fdde03": "name()", - "95d89b41": "symbol()", - "18160ddd": "totalSupply()", - "a9059cbb": "transfer(address,uint256)", - "23b872dd": "transferFrom(address,address,uint256)", - }, -} - -// IERC20MetadataABI is the input ABI used to generate the binding from. -// Deprecated: Use IERC20MetadataMetaData.ABI instead. -var IERC20MetadataABI = IERC20MetadataMetaData.ABI - -// Deprecated: Use IERC20MetadataMetaData.Sigs instead. -// IERC20MetadataFuncSigs maps the 4-byte function signature to its string representation. -var IERC20MetadataFuncSigs = IERC20MetadataMetaData.Sigs - -// IERC20Metadata is an auto generated Go binding around an Ethereum contract. -type IERC20Metadata struct { - IERC20MetadataCaller // Read-only binding to the contract - IERC20MetadataTransactor // Write-only binding to the contract - IERC20MetadataFilterer // Log filterer for contract events -} - -// IERC20MetadataCaller is an auto generated read-only Go binding around an Ethereum contract. -type IERC20MetadataCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataTransactor is an auto generated write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type IERC20MetadataFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// IERC20MetadataSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type IERC20MetadataSession struct { - Contract *IERC20Metadata // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type IERC20MetadataCallerSession struct { - Contract *IERC20MetadataCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// IERC20MetadataTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type IERC20MetadataTransactorSession struct { - Contract *IERC20MetadataTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// IERC20MetadataRaw is an auto generated low-level Go binding around an Ethereum contract. -type IERC20MetadataRaw struct { - Contract *IERC20Metadata // Generic contract binding to access the raw methods on -} - -// IERC20MetadataCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type IERC20MetadataCallerRaw struct { - Contract *IERC20MetadataCaller // Generic read-only contract binding to access the raw methods on -} - -// IERC20MetadataTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type IERC20MetadataTransactorRaw struct { - Contract *IERC20MetadataTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewIERC20Metadata creates a new instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20Metadata(address common.Address, backend bind.ContractBackend) (*IERC20Metadata, error) { - contract, err := bindIERC20Metadata(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &IERC20Metadata{IERC20MetadataCaller: IERC20MetadataCaller{contract: contract}, IERC20MetadataTransactor: IERC20MetadataTransactor{contract: contract}, IERC20MetadataFilterer: IERC20MetadataFilterer{contract: contract}}, nil -} - -// NewIERC20MetadataCaller creates a new read-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataCaller(address common.Address, caller bind.ContractCaller) (*IERC20MetadataCaller, error) { - contract, err := bindIERC20Metadata(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataCaller{contract: contract}, nil -} - -// NewIERC20MetadataTransactor creates a new write-only instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataTransactor(address common.Address, transactor bind.ContractTransactor) (*IERC20MetadataTransactor, error) { - contract, err := bindIERC20Metadata(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &IERC20MetadataTransactor{contract: contract}, nil -} - -// NewIERC20MetadataFilterer creates a new log filterer instance of IERC20Metadata, bound to a specific deployed contract. -func NewIERC20MetadataFilterer(address common.Address, filterer bind.ContractFilterer) (*IERC20MetadataFilterer, error) { - contract, err := bindIERC20Metadata(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &IERC20MetadataFilterer{contract: contract}, nil -} - -// bindIERC20Metadata binds a generic wrapper to an already deployed contract. -func bindIERC20Metadata(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(IERC20MetadataABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.IERC20MetadataCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.IERC20MetadataTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_IERC20Metadata *IERC20MetadataCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _IERC20Metadata.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_IERC20Metadata *IERC20MetadataTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _IERC20Metadata.Contract.contract.Transact(opts, method, params...) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "allowance", owner, spender) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. -// -// Solidity: function allowance(address owner, address spender) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.Allowance(&_IERC20Metadata.CallOpts, owner, spender) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) BalanceOf(opts *bind.CallOpts, account common.Address) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "balanceOf", account) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. -// -// Solidity: function balanceOf(address account) view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) BalanceOf(account common.Address) (*big.Int, error) { - return _IERC20Metadata.Contract.BalanceOf(&_IERC20Metadata.CallOpts, account) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "decimals") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() view returns(uint8) -func (_IERC20Metadata *IERC20MetadataCallerSession) Decimals() (uint8, error) { - return _IERC20Metadata.Contract.Decimals(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Name(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "name") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Name is a free data retrieval call binding the contract method 0x06fdde03. -// -// Solidity: function name() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Name() (string, error) { - return _IERC20Metadata.Contract.Name(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCaller) Symbol(opts *bind.CallOpts) (string, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "symbol") - - if err != nil { - return *new(string), err - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return out0, err - -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// Symbol is a free data retrieval call binding the contract method 0x95d89b41. -// -// Solidity: function symbol() view returns(string) -func (_IERC20Metadata *IERC20MetadataCallerSession) Symbol() (string, error) { - return _IERC20Metadata.Contract.Symbol(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _IERC20Metadata.contract.Call(opts, &out, "totalSupply") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() view returns(uint256) -func (_IERC20Metadata *IERC20MetadataCallerSession) TotalSupply() (*big.Int, error) { - return _IERC20Metadata.Contract.TotalSupply(&_IERC20Metadata.CallOpts) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Approve(opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "approve", spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. -// -// Solidity: function approve(address spender, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Approve(spender common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Approve(&_IERC20Metadata.TransactOpts, spender, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transfer", recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. -// -// Solidity: function transfer(address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.Transfer(&_IERC20Metadata.TransactOpts, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactor) TransferFrom(opts *bind.TransactOpts, sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.contract.Transact(opts, "transferFrom", sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. -// -// Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) -func (_IERC20Metadata *IERC20MetadataTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) { - return _IERC20Metadata.Contract.TransferFrom(&_IERC20Metadata.TransactOpts, sender, recipient, amount) -} - -// IERC20MetadataApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the IERC20Metadata contract. -type IERC20MetadataApprovalIterator struct { - Event *IERC20MetadataApproval // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataApprovalIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataApproval) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataApprovalIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataApprovalIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataApproval represents a Approval event raised by the IERC20Metadata contract. -type IERC20MetadataApproval struct { - Owner common.Address - Spender common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*IERC20MetadataApprovalIterator, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return &IERC20MetadataApprovalIterator{contract: _IERC20Metadata.contract, event: "Approval", logs: logs, sub: sub}, nil -} - -// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *IERC20MetadataApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { - - var ownerRule []interface{} - for _, ownerItem := range owner { - ownerRule = append(ownerRule, ownerItem) - } - var spenderRule []interface{} - for _, spenderItem := range spender { - spenderRule = append(spenderRule, spenderItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. -// -// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseApproval(log types.Log) (*IERC20MetadataApproval, error) { - event := new(IERC20MetadataApproval) - if err := _IERC20Metadata.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// IERC20MetadataTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the IERC20Metadata contract. -type IERC20MetadataTransferIterator struct { - Event *IERC20MetadataTransfer // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *IERC20MetadataTransferIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(IERC20MetadataTransfer) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *IERC20MetadataTransferIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *IERC20MetadataTransferIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// IERC20MetadataTransfer represents a Transfer event raised by the IERC20Metadata contract. -type IERC20MetadataTransfer struct { - From common.Address - To common.Address - Value *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*IERC20MetadataTransferIterator, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.FilterLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return &IERC20MetadataTransferIterator{contract: _IERC20Metadata.contract, event: "Transfer", logs: logs, sub: sub}, nil -} - -// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IERC20MetadataTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { - - var fromRule []interface{} - for _, fromItem := range from { - fromRule = append(fromRule, fromItem) - } - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - - logs, sub, err := _IERC20Metadata.contract.WatchLogs(opts, "Transfer", fromRule, toRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. -// -// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) -func (_IERC20Metadata *IERC20MetadataFilterer) ParseTransfer(log types.Log) (*IERC20MetadataTransfer, error) { - event := new(IERC20MetadataTransfer) - if err := _IERC20Metadata.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/zcnswap/contracts/erc20/Context.sol b/zcnswap/contracts/erc20/Context.sol deleted file mode 100755 index 052c09172..000000000 --- a/zcnswap/contracts/erc20/Context.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (utils/Context.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Provides information about the current execution context, including the - * sender of the transaction and its data. While these are generally available - * via msg.sender and msg.data, they should not be accessed in such a direct - * manner, since when dealing with meta-transactions the account sending and - * paying for execution may not be the actual sender (as far as an application - * is concerned). - * - * This contract is only required for intermediate, library-like contracts. - */ -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/ERC20.sol b/zcnswap/contracts/erc20/ERC20.sol deleted file mode 100755 index 308941e6f..000000000 --- a/zcnswap/contracts/erc20/ERC20.sol +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; -import "./IERC20Metadata.sol"; -import "./Context.sol"; - -/** - * @dev Implementation of the {IERC20} interface. - * - * This implementation is agnostic to the way tokens are created. This means - * that a supply mechanism has to be added in a derived contract using {_mint}. - * For a generic mechanism see {ERC20PresetMinterPauser}. - * - * TIP: For a detailed writeup see our guide - * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How - * to implement supply mechanisms]. - * - * We have followed general OpenZeppelin Contracts guidelines: functions revert - * instead returning `false` on failure. This behavior is nonetheless - * conventional and does not conflict with the expectations of ERC20 - * applications. - * - * Additionally, an {Approval} event is emitted on calls to {transferFrom}. - * This allows applications to reconstruct the allowance for all accounts just - * by listening to said events. Other implementations of the EIP may not emit - * these events, as it isn't required by the specification. - * - * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} - * functions have been added to mitigate the well-known issues around setting - * allowances. See {IERC20-approve}. - */ -contract ERC20 is Context, IERC20, IERC20Metadata { - mapping(address => uint256) private _balances; - - mapping(address => mapping(address => uint256)) private _allowances; - - uint256 private _totalSupply; - - string private _name; - string private _symbol; - - /** - * @dev Sets the values for {name} and {symbol}. - * - * The default value of {decimals} is 18. To select a different value for - * {decimals} you should overload it. - * - * All two of these values are immutable: they can only be set once during - * construction. - */ - constructor(string memory name_, string memory symbol_) { - _name = name_; - _symbol = symbol_; - } - - /** - * @dev Returns the name of the token. - */ - function name() public view virtual override returns (string memory) { - return _name; - } - - /** - * @dev Returns the symbol of the token, usually a shorter version of the - * name. - */ - function symbol() public view virtual override returns (string memory) { - return _symbol; - } - - /** - * @dev Returns the number of decimals used to get its user representation. - * For example, if `decimals` equals `2`, a balance of `505` tokens should - * be displayed to a user as `5.05` (`505 / 10 ** 2`). - * - * Tokens usually opt for a value of 18, imitating the relationship between - * Ether and Wei. This is the value {ERC20} uses, unless this function is - * overridden; - * - * NOTE: This information is only used for _display_ purposes: it in - * no way affects any of the arithmetic of the contract, including - * {IERC20-balanceOf} and {IERC20-transfer}. - */ - function decimals() public view virtual override returns (uint8) { - return 18; - } - - /** - * @dev See {IERC20-totalSupply}. - */ - function totalSupply() public view virtual override returns (uint256) { - return _totalSupply; - } - - /** - * @dev See {IERC20-balanceOf}. - */ - function balanceOf(address account) public view virtual override returns (uint256) { - return _balances[account]; - } - - /** - * @dev See {IERC20-transfer}. - * - * Requirements: - * - * - `recipient` cannot be the zero address. - * - the caller must have a balance of at least `amount`. - */ - function transfer(address recipient, uint256 amount) public virtual override returns (bool) { - _transfer(_msgSender(), recipient, amount); - return true; - } - - /** - * @dev See {IERC20-allowance}. - */ - function allowance(address owner, address spender) public view virtual override returns (uint256) { - return _allowances[owner][spender]; - } - - /** - * @dev See {IERC20-approve}. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function approve(address spender, uint256 amount) public virtual override returns (bool) { - _approve(_msgSender(), spender, amount); - return true; - } - - /** - * @dev See {IERC20-transferFrom}. - * - * Emits an {Approval} event indicating the updated allowance. This is not - * required by the EIP. See the note at the beginning of {ERC20}. - * - * Requirements: - * - * - `sender` and `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - * - the caller must have allowance for ``sender``'s tokens of at least - * `amount`. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) public virtual override returns (bool) { - _transfer(sender, recipient, amount); - - uint256 currentAllowance = _allowances[sender][_msgSender()]; - require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); - unchecked { - _approve(sender, _msgSender(), currentAllowance - amount); - } - - return true; - } - - /** - * @dev Atomically increases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - */ - function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { - _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); - return true; - } - - /** - * @dev Atomically decreases the allowance granted to `spender` by the caller. - * - * This is an alternative to {approve} that can be used as a mitigation for - * problems described in {IERC20-approve}. - * - * Emits an {Approval} event indicating the updated allowance. - * - * Requirements: - * - * - `spender` cannot be the zero address. - * - `spender` must have allowance for the caller of at least - * `subtractedValue`. - */ - function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { - uint256 currentAllowance = _allowances[_msgSender()][spender]; - require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); - unchecked { - _approve(_msgSender(), spender, currentAllowance - subtractedValue); - } - - return true; - } - - /** - * @dev Moves `amount` of tokens from `sender` to `recipient`. - * - * This internal function is equivalent to {transfer}, and can be used to - * e.g. implement automatic token fees, slashing mechanisms, etc. - * - * Emits a {Transfer} event. - * - * Requirements: - * - * - `sender` cannot be the zero address. - * - `recipient` cannot be the zero address. - * - `sender` must have a balance of at least `amount`. - */ - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual { - require(sender != address(0), "ERC20: transfer from the zero address"); - require(recipient != address(0), "ERC20: transfer to the zero address"); - - _beforeTokenTransfer(sender, recipient, amount); - - uint256 senderBalance = _balances[sender]; - require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); - unchecked { - _balances[sender] = senderBalance - amount; - } - _balances[recipient] += amount; - - emit Transfer(sender, recipient, amount); - - _afterTokenTransfer(sender, recipient, amount); - } - - /** @dev Creates `amount` tokens and assigns them to `account`, increasing - * the total supply. - * - * Emits a {Transfer} event with `from` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - */ - function _mint(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: mint to the zero address"); - - _beforeTokenTransfer(address(0), account, amount); - - _totalSupply += amount; - _balances[account] += amount; - emit Transfer(address(0), account, amount); - - _afterTokenTransfer(address(0), account, amount); - } - - /** - * @dev Destroys `amount` tokens from `account`, reducing the - * total supply. - * - * Emits a {Transfer} event with `to` set to the zero address. - * - * Requirements: - * - * - `account` cannot be the zero address. - * - `account` must have at least `amount` tokens. - */ - function _burn(address account, uint256 amount) internal virtual { - require(account != address(0), "ERC20: burn from the zero address"); - - _beforeTokenTransfer(account, address(0), amount); - - uint256 accountBalance = _balances[account]; - require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); - unchecked { - _balances[account] = accountBalance - amount; - } - _totalSupply -= amount; - - emit Transfer(account, address(0), amount); - - _afterTokenTransfer(account, address(0), amount); - } - - /** - * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. - * - * This internal function is equivalent to `approve`, and can be used to - * e.g. set automatic allowances for certain subsystems, etc. - * - * Emits an {Approval} event. - * - * Requirements: - * - * - `owner` cannot be the zero address. - * - `spender` cannot be the zero address. - */ - function _approve( - address owner, - address spender, - uint256 amount - ) internal virtual { - require(owner != address(0), "ERC20: approve from the zero address"); - require(spender != address(0), "ERC20: approve to the zero address"); - - _allowances[owner][spender] = amount; - emit Approval(owner, spender, amount); - } - - /** - * @dev Hook that is called before any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * will be transferred to `to`. - * - when `from` is zero, `amount` tokens will be minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens will be burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _beforeTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} - - /** - * @dev Hook that is called after any transfer of tokens. This includes - * minting and burning. - * - * Calling conditions: - * - * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens - * has been transferred to `to`. - * - when `from` is zero, `amount` tokens have been minted for `to`. - * - when `to` is zero, `amount` of ``from``'s tokens have been burned. - * - `from` and `to` are never both zero. - * - * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. - */ - function _afterTokenTransfer( - address from, - address to, - uint256 amount - ) internal virtual {} -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/IERC20.sol b/zcnswap/contracts/erc20/IERC20.sol deleted file mode 100755 index 014b5706d..000000000 --- a/zcnswap/contracts/erc20/IERC20.sol +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC20 standard as defined in the EIP. - */ -interface IERC20 { - /** - * @dev Returns the amount of tokens in existence. - */ - function totalSupply() external view returns (uint256); - - /** - * @dev Returns the amount of tokens owned by `account`. - */ - function balanceOf(address account) external view returns (uint256); - - /** - * @dev Moves `amount` tokens from the caller's account to `recipient`. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transfer(address recipient, uint256 amount) external returns (bool); - - /** - * @dev Returns the remaining number of tokens that `spender` will be - * allowed to spend on behalf of `owner` through {transferFrom}. This is - * zero by default. - * - * This value changes when {approve} or {transferFrom} are called. - */ - function allowance(address owner, address spender) external view returns (uint256); - - /** - * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * IMPORTANT: Beware that changing an allowance with this method brings the risk - * that someone may use both the old and the new allowance by unfortunate - * transaction ordering. One possible solution to mitigate this race - * condition is to first reduce the spender's allowance to 0 and set the - * desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * - * Emits an {Approval} event. - */ - function approve(address spender, uint256 amount) external returns (bool); - - /** - * @dev Moves `amount` tokens from `sender` to `recipient` using the - * allowance mechanism. `amount` is then deducted from the caller's - * allowance. - * - * Returns a boolean value indicating whether the operation succeeded. - * - * Emits a {Transfer} event. - */ - function transferFrom( - address sender, - address recipient, - uint256 amount - ) external returns (bool); - - /** - * @dev Emitted when `value` tokens are moved from one account (`from`) to - * another (`to`). - * - * Note that `value` may be zero. - */ - event Transfer(address indexed from, address indexed to, uint256 value); - - /** - * @dev Emitted when the allowance of a `spender` for an `owner` is set by - * a call to {approve}. `value` is the new allowance. - */ - event Approval(address indexed owner, address indexed spender, uint256 value); -} \ No newline at end of file diff --git a/zcnswap/contracts/erc20/IERC20Metadata.sol b/zcnswap/contracts/erc20/IERC20Metadata.sol deleted file mode 100755 index 3f8166f0d..000000000 --- a/zcnswap/contracts/erc20/IERC20Metadata.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts v4.3.2 (token/ERC20/extensions/IERC20Metadata.sol) - -pragma solidity ^0.8.0; - -import "./IERC20.sol"; - -/** - * @dev Interface for the optional metadata functions from the ERC20 standard. - * - * _Available since v4.1._ - */ -interface IERC20Metadata is IERC20 { - /** - * @dev Returns the name of the token. - */ - function name() external view returns (string memory); - - /** - * @dev Returns the symbol of the token. - */ - function symbol() external view returns (string memory); - - /** - * @dev Returns the decimals places of the token. - */ - function decimals() external view returns (uint8); -} \ No newline at end of file diff --git a/zcnswap/handler.go b/zcnswap/handler.go deleted file mode 100644 index fd20c433d..000000000 --- a/zcnswap/handler.go +++ /dev/null @@ -1,84 +0,0 @@ -package zcnswap - -import ( - "crypto/ecdsa" - "github.com/0chain/errors" - "github.com/0chain/gosdk/zcncore" - hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" - "github.com/0chain/gosdk/zcnswap/config" - "github.com/0chain/gosdk/zcnswap/swapfactory/bancor" - "github.com/0chain/gosdk/zcnswap/swapfactory/erc20" - "github.com/ethereum/go-ethereum/accounts" - cmn "github.com/ethereum/go-ethereum/common" - "math/big" -) - -type ethAccount struct { - PrivateKey *ecdsa.PrivateKey - SourceAddr *cmn.Address - Account *accounts.Account -} - -func Swap(swapAmount int64, tokenSource string) (string, error) { - client, _ := zcncore.GetEthClient() - - ethAccount, err := getWallet() - if err != nil { - return "", err - } - - targetTokenAddress := config.Configuration.ZcnTokenAddress - sourceTokenAddress := tokenSource - - amount := new(big.Int).SetInt64(swapAmount) - - // checking for available funds - balance, err := erc20.TokenBalance(*ethAccount.SourceAddr, - cmn.HexToAddress(sourceTokenAddress), - client) - if err != nil { - return "", err - } - if balance.Cmp(amount) == -1 { - return "", errors.New("500", "Not enough balance") - } - - bancorService := bancor.NewSwapService(client, ethAccount.PrivateKey) - pair, err := bancorService.EstimateRate(sourceTokenAddress, targetTokenAddress, amount) - if err != nil { - return "", err - } - - signedTx, err := bancorService.SwapWithConversionPath(pair, - ethAccount.SourceAddr.Hex()) - if err != nil { - return "", err - } - return signedTx.Hash().String(), nil -} - -func getWallet() (acc *ethAccount, err error) { - walletHd, err := hdwallet.NewFromMnemonic(config.Configuration.WalletMnemonic) - if err != nil { - return nil, err - } - - path := hdwallet.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := walletHd.Derive(path, false) - if err != nil { - return nil, err - } - - privateKey, err := walletHd.PrivateKey(account) - if err != nil { - return nil, err - } - sourceAddrHex, _ := walletHd.AddressHex(account) - address := cmn.HexToAddress(sourceAddrHex) - - return ðAccount{ - PrivateKey: privateKey, - SourceAddr: &address, - Account: &account, - }, err -} diff --git a/zcnswap/swapfactory/bancor/bancor.abi b/zcnswap/swapfactory/bancor/bancor.abi deleted file mode 100755 index 99a7e8386..000000000 --- a/zcnswap/swapfactory/bancor/bancor.abi +++ /dev/null @@ -1 +0,0 @@ -[{"constant":false,"inputs":[{"name":"_onlyOwnerCanUpdateRegistry","type":"bool"}],"name":"restrictRegistryUpdate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_register","type":"bool"}],"name":"registerEtherToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"}],"name":"getReturnByPath","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"claimAndConvertFor2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"onlyOwnerCanUpdateRegistry","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"updateRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convert2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"maxAffiliateFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"withdrawTokens","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"prevRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"acceptOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"registry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"}],"name":"rateByPath","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"etherTokens","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_bancorX","type":"address"},{"name":"_conversionId","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"completeXConversion","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convertFor2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"claimAndConvertFor","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"restoreRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"convertByPath","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_targetBlockchain","type":"bytes32"},{"name":"_targetAccount","type":"bytes32"},{"name":"_conversionId","type":"uint256"}],"name":"xConvert","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"}],"name":"claimAndConvert","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_beneficiary","type":"address"}],"name":"convertFor","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_targetBlockchain","type":"bytes32"},{"name":"_targetAccount","type":"bytes32"},{"name":"_conversionId","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"xConvert2","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"newOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_sourceToken","type":"address"},{"name":"_targetToken","type":"address"}],"name":"conversionPath","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"},{"name":"_affiliateAccount","type":"address"},{"name":"_affiliateFee","type":"uint256"}],"name":"claimAndConvert2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_path","type":"address[]"},{"name":"_amount","type":"uint256"},{"name":"_minReturn","type":"uint256"}],"name":"convert","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_maxAffiliateFee","type":"uint256"}],"name":"setMaxAffiliateFee","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_registry","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_smartToken","type":"address"},{"indexed":true,"name":"_fromToken","type":"address"},{"indexed":true,"name":"_toToken","type":"address"},{"indexed":false,"name":"_fromAmount","type":"uint256"},{"indexed":false,"name":"_toAmount","type":"uint256"},{"indexed":false,"name":"_trader","type":"address"}],"name":"Conversion","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_prevOwner","type":"address"},{"indexed":true,"name":"_newOwner","type":"address"}],"name":"OwnerUpdate","type":"event"}] \ No newline at end of file diff --git a/zcnswap/swapfactory/bancor/service.go b/zcnswap/swapfactory/bancor/service.go deleted file mode 100755 index 61fd6999c..000000000 --- a/zcnswap/swapfactory/bancor/service.go +++ /dev/null @@ -1,236 +0,0 @@ -package bancor - -import ( - "context" - "crypto/ecdsa" - "math/big" - "time" - - "github.com/0chain/errors" - l "github.com/0chain/gosdk/zboxcore/logger" - contractErc20 "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" - "github.com/0chain/gosdk/zcnswap/config" - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/0chain/gosdk/zcnswap/swapfactory" - "github.com/0chain/gosdk/zcnswap/swapfactory/erc20" - ethutils "github.com/0chain/gosdk/zcnswap/utils" - cmn "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" - "go.uber.org/zap" -) - -type ISwapService interface { - SwapWithConversionPath(pair *swapfactory.ExchangePair, from string) (*types.Transaction, error) - Approve(spender, fromToken, fromAddress cmn.Address, amountIn *big.Int) error - IncreaseAllowance(spender, fromToken, fromAddress cmn.Address, addedValue *big.Int) error - PackConvert(path *[]cmn.Address, amount, minReturn *big.Int, affiliate cmn.Address) ([]byte, error) - EstimateRate(from, to string, amount *big.Int) (*swapfactory.ExchangePair, error) -} - -type swapService struct { - Client *ethclient.Client - PrivateKey *ecdsa.PrivateKey -} - -// func SwapWithConversionPath(path *[]cmn.Address, from string, amountIn, amountOut *big.Int, privateKey *ecdsa.PrivateKey, client *ethclient.Client) (*types.Transaction, error) { -func (s *swapService) SwapWithConversionPath(pair *swapfactory.ExchangePair, from string) (*types.Transaction, error) { - var affiliateAccount = cmn.HexToAddress("0x0000000000000000000000000000000000000000") - - fromAddress := cmn.HexToAddress(from) - spender := cmn.HexToAddress(config.Configuration.BancorAddress) - fromToken := cmn.HexToAddress(config.Configuration.UsdcTokenAddress) - - bancorModule, err := contracts.NewIBancorNetwork(spender, s.Client) - if err != nil { - return nil, err - } - - balance, err := erc20.TokenBalance(fromAddress, fromToken, s.Client) - if err != nil { - return nil, err - } - - if balance.Cmp(pair.AmountIn) != 1 { - return nil, errors.New("500", "Not enough balance") - } - - tokenInfo, err := erc20.TokenInfo(fromToken, s.Client) - if err != nil { - return nil, err - } - - // allowance - aCheckAllowanceResult, err := erc20.CheckAllowance(fromToken, - spender, - fromAddress, - pair.AmountIn, - tokenInfo.TokenSymbol == "ETH", - s.Client) - if err != nil { - l.Logger.Error("Allowance error", zap.Error(err)) - return nil, err - } - - convertPayload, err := s.PackConvert(pair.ConversionPath, pair.AmountIn, pair.AmountOut, affiliateAccount) - if err != nil { - l.Logger.Error("error in PackConvert", zap.Error(err)) - return nil, err - } - - if !aCheckAllowanceResult.IsSatisfied { - err := s.Approve(spender, fromToken, fromAddress, pair.AmountIn) - if err != nil { - l.Logger.Error("Approve error", zap.Error(err)) - return nil, err - } - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(convertPayload, from, spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - l.Logger.Error("Signed transaction errorr", zap.Error(err)) - return nil, err - } - - // ropsten test network deployed old contract, hence using old method - //return bancorModule.ConvertByPath2(opts, *path, amountIn, amountOut, affiliateAccount) - return bancorModule.ConvertByPath(opts, *pair.ConversionPath, pair.AmountIn, pair.AmountOut, affiliateAccount, affiliateAccount, big.NewInt(0)) -} - -func (s *swapService) Approve(spender, fromToken, fromAddress cmn.Address, amountIn *big.Int) error { - l.Logger.Info("Approve called", zap.Any("fromToken", fromToken.Hex())) - - ercModule, err := contracts.NewERC20(fromToken, s.Client) - if err != nil { - return err - } - - approvePayload, err := erc20.PackApprove(spender, amountIn) - if err != nil { - return err - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(approvePayload, fromAddress.Hex(), spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - return err - } - - trans, err := ercModule.Approve(opts, spender, amountIn) - if err != nil { - return err - } - - l.Logger.Info("Approve tx hash", zap.Any("hash", trans.Hash().Hex())) - - res, err := ethutils.ConfirmEthereumTransaction(trans.Hash().Hex(), 60, time.Minute, s.Client) - if err != nil { - return err - } - if res == ethutils.STATUS_FAIL { - return errors.New("500", "Unable to confirm transaction") - } - - return nil -} - -func (s *swapService) IncreaseAllowance(spender, fromToken, fromAddress cmn.Address, addedValue *big.Int) error { - l.Logger.Info("IncreaseAllowance called", zap.Any("fromToken", fromToken.Hex())) - - abi, err := contractErc20.ERC20MetaData.GetAbi() - if err != nil { - return err - } - - pack, err := abi.Pack("increaseAllowance", spender, addedValue) - if err != nil { - return err - } - - value := big.NewInt(0) - opts, err := ethutils.NewSignedTransaction(pack, fromAddress.Hex(), spender.Hex(), value, s.PrivateKey, s.Client) - if err != nil { - return err - } - - tokenInstance, err := contractErc20.NewERC20(fromToken, s.Client) - if err != nil { - return err - } - trans, err := tokenInstance.IncreaseAllowance(opts, spender, addedValue) - if err != nil { - return err - } - - l.Logger.Info("Allowance transaction", zap.Any("hash", trans.Hash().Hex())) - - res, err := ethutils.ConfirmEthereumTransaction(trans.Hash().Hex(), 60, time.Minute, s.Client) - if err != nil { - return err - } - if res == ethutils.STATUS_FAIL { - return errors.New("500", "Unable to confirm transaction") - } - - return nil -} - -func (s *swapService) PackConvert(path *[]cmn.Address, amount, minReturn *big.Int, affiliate cmn.Address) ([]byte, error) { - abi, err := contracts.IBancorNetworkMetaData.GetAbi() - if err != nil { - return nil, errors.New("500", "No ABI") - } - - // ropsten test network deployed old contract, hence using old method - //pack, err := abi.Pack("convertByPath2", path, amount, minReturn, affiliate) - pack, err := abi.Pack("convertByPath", path, amount, minReturn, affiliate, affiliate, big.NewInt(0)) - if err != nil { - return nil, errors.New("500", "Unable to pack") - } - - return pack, nil -} - -// EstimateRate get token exchange rate based on from amount -func (s *swapService) EstimateRate(from, to string, amount *big.Int) (*swapfactory.ExchangePair, error) { - fromHex := cmn.HexToAddress(from) - toHex := cmn.HexToAddress(to) - bancorAddr := cmn.HexToAddress(config.Configuration.BancorAddress) - - bancorModule, err := contracts.NewIBancorNetwork(bancorAddr, s.Client) - if err != nil { - return nil, err - } - - convertAddrs, err := bancorModule.ConversionPath(nil, fromHex, toHex) - if err != nil { - return nil, err - } - - result, err := bancorModule.RateByPath(nil, convertAddrs, amount) - if err != nil { - return nil, err - } - - gasPriceWei, err := s.Client.SuggestGasPrice(context.Background()) - if err != nil { - return nil, err - } - - return &swapfactory.ExchangePair{ - ContractName: "Bancor", - AmountIn: amount, - AmountOut: result, - TxFee: gasPriceWei, - ConversionPath: &convertAddrs, - }, nil -} - -// NewSwapService - creating repository -func NewSwapService(client *ethclient.Client, privateKey *ecdsa.PrivateKey) ISwapService { - return &swapService{ - Client: client, - PrivateKey: privateKey, - } -} diff --git a/zcnswap/swapfactory/erc20/allowance.go b/zcnswap/swapfactory/erc20/allowance.go deleted file mode 100755 index d3120bce1..000000000 --- a/zcnswap/swapfactory/erc20/allowance.go +++ /dev/null @@ -1,48 +0,0 @@ -package erc20 - -import ( - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - "math/big" - - "github.com/ethereum/go-ethereum/common" -) - -func GetAllowance(tokenAddr, spender, userAddr common.Address, client *ethclient.Client) (*big.Int, error) { - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return nil, err - } - - return erc20Module.Allowance(&bind.CallOpts{}, userAddr, spender) -} - -// func (fromToken, data.Bancor, userAddr, amount) (Allowance, AllowanceSatisfied, AllowanceData, error) -type CheckAllowanceResult struct { - AllowanceAmount *big.Int `json:"allowanceAmount"` - IsSatisfied bool `json:"isSatisfied"` - AllowanceData []byte `json:"allowanceData"` -} - -// CheckAllowance Cannot use this to check ETH -func CheckAllowance(fromToken, spender, userAddr common.Address, amount *big.Int, fromIsETH bool, client *ethclient.Client) (*CheckAllowanceResult, error) { - if fromIsETH { - return &CheckAllowanceResult{ - AllowanceAmount: amount, - IsSatisfied: true, - AllowanceData: []byte(""), - }, nil - } - - fromTokenAllowance, err := GetAllowance(fromToken, spender, userAddr, client) - if err != nil { - return nil, err - } - - return &CheckAllowanceResult{ - AllowanceAmount: amount, - IsSatisfied: fromTokenAllowance.Cmp(amount) >= 0, - //AllowanceData: callData, - }, nil -} diff --git a/zcnswap/swapfactory/erc20/erc20.abi b/zcnswap/swapfactory/erc20/erc20.abi deleted file mode 100755 index 668d6979f..000000000 --- a/zcnswap/swapfactory/erc20/erc20.abi +++ /dev/null @@ -1,222 +0,0 @@ -[ - { - "constant": true, - "inputs": [], - "name": "name", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_spender", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_from", - "type": "address" - }, - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "decimals", - "outputs": [ - { - "name": "", - "type": "uint8" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "name": "balance", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [], - "name": "symbol", - "outputs": [ - { - "name": "", - "type": "string" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "_to", - "type": "address" - }, - { - "name": "_value", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "_owner", - "type": "address" - }, - { - "name": "_spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "payable": true, - "stateMutability": "payable", - "type": "fallback" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "name": "spender", - "type": "address" - }, - { - "indexed": false, - "name": "value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "from", - "type": "address" - }, - { - "indexed": true, - "name": "to", - "type": "address" - }, - { - "indexed": false, - "name": "value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - } -] \ No newline at end of file diff --git a/zcnswap/swapfactory/erc20/service.go b/zcnswap/swapfactory/erc20/service.go deleted file mode 100755 index 4a7ee2809..000000000 --- a/zcnswap/swapfactory/erc20/service.go +++ /dev/null @@ -1,77 +0,0 @@ -package erc20 - -import ( - "github.com/0chain/gosdk/zcnbridge/ethereum/erc20" - "github.com/0chain/gosdk/zcnswap/contracts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/ethclient" - "math/big" - - cmn "github.com/0chain/errors" - "github.com/ethereum/go-ethereum/common" -) - -var erc20Info = map[common.Address]Info{} - -type Info struct { - TokenAddr common.Address - TokenName string - TokenSymbol string - Decimals uint8 -} - -// PackApprove - pack approve payload from ABI contract -func PackApprove(spender common.Address, amount *big.Int) ([]byte, error) { - abi, err := erc20.ERC20MetaData.GetAbi() - if err != nil { - return nil, cmn.New("500", "No ABI") - } - - pack, err := abi.Pack("approve", spender, amount) - if err != nil { - return nil, cmn.New("500", "Unable to pack") - } - - return pack, nil -} - -// TokenBalance - return balance by selected token contract -func TokenBalance(userAddr, tokenAddr common.Address, client *ethclient.Client) (*big.Int, error) { - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return nil, err - } - return erc20Module.BalanceOf(&bind.CallOpts{}, userAddr) -} - -func TokenInfo(tokenAddr common.Address, client *ethclient.Client) (Info, error) { - ret := Info{} - if out, ok := erc20Info[tokenAddr]; ok { - return out, nil - } - - erc20Module, err := contracts.NewERC20(tokenAddr, client) - if err != nil { - return ret, err - } - decimals, err := erc20Module.Decimals(nil) - if err != nil { - return ret, err - } - tokenName, err := erc20Module.Symbol(nil) - if err != nil { - return ret, err - } - tokenSymbol, err := erc20Module.Name(nil) - if err != nil { - return ret, err - } - - ret.TokenAddr = tokenAddr - ret.TokenName = tokenName - ret.TokenSymbol = tokenSymbol - ret.Decimals = decimals - - erc20Info[tokenAddr] = ret - return ret, nil -} diff --git a/zcnswap/swapfactory/models.go b/zcnswap/swapfactory/models.go deleted file mode 100755 index 1ced96786..000000000 --- a/zcnswap/swapfactory/models.go +++ /dev/null @@ -1,121 +0,0 @@ -package swapfactory - -import ( - "encoding/json" - cmn "github.com/ethereum/go-ethereum/common" - "math/big" - "strings" - - "github.com/labstack/echo" -) - -type EchoContext struct { - echo.Context -} - -type Token struct { - Name string `json:"name"` - Address string `json:"address"` - Symbol string `json:"symbol"` - Decimals int `json:"decimals"` - LogoURI string `json:"logoURI"` -} - -type Tokens []Token - -func (t Tokens) Len() int { return len(t) } -func (t Tokens) Less(i, j int) bool { - cmp := strings.Compare(t[i].Symbol, t[j].Symbol) - return cmp == -1 -} -func (t Tokens) Swap(i, j int) { t[i], t[j] = t[j], t[i] } - -type Exchange struct { - Name string `json:"name"` - APIAddress string `json:"api_address"` - Decimals int `json:"decimals"` -} - -type ExchangeResult struct { - FromName string `json:"from_name,omitempty"` - ToName string `json:"to_name,omitempty"` - FromAddr string `json:"from_addr,omitempty"` - ToAddr string `json:"to_addr,omitempty"` - ExchangePairs ExchangePairList `json:"exchange_pairs,omitempty"` -} - -type ExchangePair struct { - ContractName string `json:"contract_name,omitempty"` - AmountIn *big.Int `json:"amount_in,omitempty"` - AmountOut *big.Int `json:"amount_out,omitempty"` - ExchangeRatio *big.Int `json:"exchange_ratio,omitempty"` - TxFee *big.Int `json:"tx_fee,omitempty"` - SupportSwap bool `json:"support_swap,omitempty"` - ConversionPath *[]cmn.Address `json:"coversion_path,omitempty"` -} - -func (e *ExchangePair) MarshalJSON() ([]byte, error) { - return json.Marshal(&struct { - ContractName string `json:"contract_name"` - AmountIn string `json:"amount_in"` - AmountOut string `json:"amount_out"` - ExchangeRatio string `json:"exchange_ratio"` - TxFee string `json:"tx_fee"` - SupportSwap bool `json:"support_swap"` - }{ - ContractName: e.ContractName, - AmountIn: e.AmountIn.String(), - AmountOut: e.AmountOut.String(), - ExchangeRatio: e.ExchangeRatio.String(), - TxFee: e.TxFee.String(), - SupportSwap: e.SupportSwap, - }) -} - -type ExchangePairList []ExchangePair - -func (p ExchangePairList) Len() int { return len(p) } -func (p ExchangePairList) Less(i, j int) bool { - - return p[i].AmountOut.Cmp(p[j].AmountOut) == 1 -} -func (p ExchangePairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type PoolToken struct { - Address string `json:"address"` - Name string `json:"name"` - Symbol string `json:"symbol"` - Logo string `json:"logo,omitempty"` - Decimals int `json:"decimals,omitempty"` - DenormWeight string `json:"denormWeight,omitempty"` - Balance string `json:"balance,omitempty"` -} - -type PoolInfo struct { - Address string `json:"address,omitempty"` - Platform string `json:"platform,omitempty"` - Liquidity string `json:"liquidity,omitempty"` - Reserves []string `json:"reserves,omitempty"` - TokenPrices []string `json:"tokenprices,omitempty"` - Volumes []string `json:"volumes,omitempty"` - ReserveUSD string `json:"reserveUSD,omitempty"` - ReserveETH string `json:"reserveETH,omitempty"` - TotalSupply string `json:"totalSupply,omitempty"` - VolumeUSD string `json:"volumeUSD,omitempty"` - Tokens []PoolToken `json:"tokens,omitempty"` - SwapFee string `json:"swapFee,omitempty"` - TotalWeight string `json:"totalWeight,omitempty"` -} - -type SwapTx struct { - Data string `json:"data"` - TxFee string `json:"tx_fee"` - ContractAddr string `json:"contract_addr"` - FromTokenAmount string `json:"from_token_amount"` - ToTokenAmount string `json:"to_token_amount"` - ExchangeRatio string `json:"exchange_ratio"` - FromTokenAddr string `json:"from_token_addr"` - Allowance string `json:"allowance"` - AllowanceSatisfied bool `json:"allowance_satisfied"` - AllowanceData string `json:"allowance_data"` -} diff --git a/zcnswap/utils/ethconvert.go b/zcnswap/utils/ethconvert.go deleted file mode 100755 index 6d72af703..000000000 --- a/zcnswap/utils/ethconvert.go +++ /dev/null @@ -1,56 +0,0 @@ -package utils - -import ( - "fmt" - - "github.com/shopspring/decimal" -) - -// ErrInvalidUnit is returned when the given unit is not supported. -var ErrInvalidUnit = fmt.Errorf("invalid unit") - -func init() { - // set the decimal precision to 18 - decimal.DivisionPrecision = 18 -} - -// Convert converts the given amount from the given unit to the given unit. -func Convert(input decimal.Decimal, inputUnit string, outputUnit string) (decimal.Decimal, error) { - wei, err := ToWei(input, inputUnit) - if err != nil { - return decimal.Zero, err - } - return FromWei(wei, outputUnit) -} - -// ToWei converts the given amount to Wei. -func ToWei(amount decimal.Decimal, unit string) (decimal.Decimal, error) { - if unit == Wei { - return amount.RoundDown(0), nil - } - value, err := getUnitValue(unit) - if err != nil { - return decimal.Zero, err - } - return amount.Mul(value).RoundDown(0), nil -} - -// FromWei converts the given amount from Wei to the given unit. -func FromWei(amount decimal.Decimal, unit string) (decimal.Decimal, error) { - if unit == Wei { - return amount.RoundDown(0), nil - } - value, err := getUnitValue(unit) - if err != nil { - return decimal.Zero, err - } - return amount.Div(value), nil -} - -func getUnitValue(unit string) (decimal.Decimal, error) { - value, ok := units[unit] - if !ok { - return decimal.Zero, ErrInvalidUnit - } - return decimal.NewFromString(value) -} diff --git a/zcnswap/utils/ethutils.go b/zcnswap/utils/ethutils.go deleted file mode 100755 index 1aa83fd47..000000000 --- a/zcnswap/utils/ethutils.go +++ /dev/null @@ -1,132 +0,0 @@ -package utils - -import ( - "context" - "crypto/ecdsa" - "math/big" - "time" - - "github.com/0chain/errors" - l "github.com/0chain/gosdk/zboxcore/logger" - "github.com/0chain/gosdk/zcnbridge" - hdwallet "github.com/0chain/gosdk/zcncore/ethhdwallet" - eth "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - cmn "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" - "github.com/tyler-smith/go-bip39" - "go.uber.org/zap" -) - -const ( - STATUS_FAIL = 1 - STATUS_SUCCESS = 0 -) - -func ConfirmEthereumTransaction(hash string, times int, duration time.Duration, client *ethclient.Client) (int, error) { - var ( - res = 0 - ) - - if hash == "" { - return -1, errors.New("500", "transaction hash should not be empty") - } - - l.Logger.Info("Start transaction check", zap.Any("hash", hash)) - for i := 0; i < times; i++ { - res := CheckEthHashStatus(hash, client) - if res == STATUS_SUCCESS || res == STATUS_FAIL { - break - } - time.Sleep(duration) - } - return res, nil -} - -// CheckEthHashStatus - checking the status of ETH transaction -// possible values 0 (fail) or 1 (success) -func CheckEthHashStatus(hash string, client *ethclient.Client) int { - txHash := cmn.HexToHash(hash) - - tx, err := client.TransactionReceipt(context.Background(), txHash) - if err != nil { - return -1 - } - return int(tx.Status) -} - -func NewSignedTransaction(pack []byte, from, to string, value *big.Int, privateKey *ecdsa.PrivateKey, client *ethclient.Client) (*bind.TransactOpts, error) { - fromAddress := cmn.HexToAddress(from) - toAddress := cmn.HexToAddress(to) - gasLimitUnits, err := client.EstimateGas(context.Background(), eth.CallMsg{ - From: fromAddress, - To: &toAddress, - Data: pack, - }) - if err != nil { - return nil, err - } - - nonce, err := client.PendingNonceAt(context.Background(), fromAddress) - if err != nil { - return nil, err - } - - gasPriceWei, err := client.SuggestGasPrice(context.Background()) - if err != nil { - return nil, err - } - - chainID, err := client.ChainID(context.Background()) - if err != nil { - return nil, err - } - - opts := zcnbridge.CreateSignedTransaction(chainID, client, fromAddress, privateKey, gasLimitUnits) - valueWei := new(big.Int).Mul(value, big.NewInt(params.Wei)) - - opts.Nonce = big.NewInt(int64(nonce)) - opts.Value = valueWei // in wei - opts.GasLimit = gasLimitUnits // in units - opts.GasPrice = gasPriceWei // wei - - return opts, nil -} - -func AddPercents(gasLimitUnits uint64, percents int) *big.Int { - gasLimitBig := big.NewInt(int64(gasLimitUnits)) - factorBig := big.NewInt(int64(percents)) - deltaBig := gasLimitBig.Div(gasLimitBig, factorBig) - - origin := big.NewInt(int64(gasLimitUnits)) - gasLimitBig = origin.Add(origin, deltaBig) - - return gasLimitBig -} - -func CreateHDWallet() (*accounts.Account, string, error) { - entropy, err := bip39.NewEntropy(256) - if err != nil { - return nil, "", err - } - - mnemonic, err := bip39.NewMnemonic(entropy) - if err != nil { - return nil, "", err - } - - walletHd, err := hdwallet.NewFromMnemonic(mnemonic) - if err != nil { - return nil, "", err - } - - path := hdwallet.MustParseDerivationPath("m/44'/60'/0'/0/0") - account, err := walletHd.Derive(path, false) - if err != nil { - return nil, "", err - } - - return &account, mnemonic, err -} diff --git a/zcnswap/utils/ethutils_test.go b/zcnswap/utils/ethutils_test.go deleted file mode 100755 index f44b99abc..000000000 --- a/zcnswap/utils/ethutils_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package utils - -import ( - "github.com/stretchr/testify/require" - "math/big" - "testing" -) - -func TestEthUtils(t *testing.T) { - t.Run("Correct percentage", func(t *testing.T) { - value := new(big.Int).SetInt64(int64(2100)) - res := AddPercents(value.Uint64(), 10) - require.Equal(t, 2310, int(res.Int64())) - }) -} diff --git a/zcnswap/utils/units.go b/zcnswap/utils/units.go deleted file mode 100755 index d164c8ee5..000000000 --- a/zcnswap/utils/units.go +++ /dev/null @@ -1,29 +0,0 @@ -package utils - -const ( - Wei = "wei" - Kwei = "kwei" - Mwei = "mwei" - Gwei = "gwei" - Szabo = "szabo" - Finney = "finney" - Ether = "ether" - Kether = "kether" - Mether = "mether" - Gether = "gether" - Tether = "tether" -) - -var units = map[string]string{ - Wei: "1", - Kwei: "1000", - Mwei: "1000000", - Gwei: "1000000000", - Szabo: "1000000000000", - Finney: "1000000000000000", - Ether: "1000000000000000000", - Kether: "1000000000000000000000", - Mether: "1000000000000000000000000", - Gether: "1000000000000000000000000000", - Tether: "1000000000000000000000000000000", -} diff --git a/znft/example/go.mod b/znft/example/go.mod index a20b3f052..90a9c0756 100644 --- a/znft/example/go.mod +++ b/znft/example/go.mod @@ -5,13 +5,13 @@ go 1.18 require github.com/0chain/gosdk v1.8.9 require ( - github.com/btcsuite/btcd v0.23.2 // indirect - github.com/btcsuite/btcd/btcec/v2 v2.2.1 // indirect - github.com/btcsuite/btcd/btcutil v1.1.2 // indirect - github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect + github.com/btcsuite/btcd v0.23.4 // indirect + github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect + github.com/btcsuite/btcd/btcutil v1.1.3 // indirect + github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect - github.com/ethereum/go-ethereum v1.10.25 // indirect + github.com/ethereum/go-ethereum v1.10.26 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/google/uuid v1.3.0 // indirect @@ -19,12 +19,12 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/rjeczalik/notify v0.9.2 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect - github.com/tklauser/go-sysconf v0.3.10 // indirect - github.com/tklauser/numcpus v0.5.0 // indirect + github.com/tklauser/go-sysconf v0.3.11 // indirect + github.com/tklauser/numcpus v0.6.0 // indirect github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/yusufpapurcu/wmi v1.2.2 // indirect - golang.org/x/crypto v0.0.0-20221012134737-56aed061732a // indirect - golang.org/x/sys v0.1.0 // indirect + golang.org/x/crypto v0.6.0 // indirect + golang.org/x/sys v0.7.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/znft/example/go.sum b/znft/example/go.sum index 622919f78..6bdb94e8b 100644 --- a/znft/example/go.sum +++ b/znft/example/go.sum @@ -5,17 +5,21 @@ github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tj github.com/btcsuite/btcd v0.23.0/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= github.com/btcsuite/btcd v0.23.2 h1:/YOgUp25sdCnP5ho6Hl3s0E438zlX+Kak7E6TgBgoT0= github.com/btcsuite/btcd v0.23.2/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= +github.com/btcsuite/btcd v0.23.4/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA= github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE= github.com/btcsuite/btcd/btcec/v2 v2.2.1 h1:xP60mv8fvp+0khmrN0zTdPC3cNm24rfeE6lh2R/Yv3E= github.com/btcsuite/btcd/btcec/v2 v2.2.1/go.mod h1:9/CSmJxmuvqzX9Wh2fXMWToLOHhPd11lSPuIupwTkI8= +github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A= github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= github.com/btcsuite/btcd/btcutil v1.1.2/go.mod h1:UR7dsSJzJUfMmFiiLlIrMq1lS9jh9EdCV7FStZSnpi0= +github.com/btcsuite/btcd/btcutil v1.1.3/go.mod h1:UR7dsSJzJUfMmFiiLlIrMq1lS9jh9EdCV7FStZSnpi0= github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= @@ -43,6 +47,7 @@ github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0 github.com/edsrzf/mmap-go v1.0.0 h1:CEBF7HpRnUCSJgGUb5h1Gm7e3VkmVDrR8lvWVLtrOFw= github.com/ethereum/go-ethereum v1.10.25 h1:5dFrKJDnYf8L6/5o42abCE6a9yJm9cs4EJVRyYMr55s= github.com/ethereum/go-ethereum v1.10.25/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= +github.com/ethereum/go-ethereum v1.10.26/go.mod h1:EYFyF19u3ezGLD4RqOkLq+ZCXzYbLoNDdZlMt7kyKFg= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= @@ -113,9 +118,11 @@ github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70 github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/tklauser/go-sysconf v0.3.10 h1:IJ1AZGZRWbY8T5Vfk04D9WOA5WSejdflXxP03OUqALw= github.com/tklauser/go-sysconf v0.3.10/go.mod h1:C8XykCvCb+Gn0oNCWPIlcb0RuglQTYaQ2hGm7jmxEFk= +github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= github.com/tklauser/numcpus v0.4.0/go.mod h1:1+UI3pD8NW14VMwdgJNJ1ESk2UnwhAnz5hMwiKKqXCQ= github.com/tklauser/numcpus v0.5.0 h1:ooe7gN0fg6myJ0EKoTAf5hebTZrH52px3New/D9iJ+A= github.com/tklauser/numcpus v0.5.0/go.mod h1:OGzpTxpcIMNGYQdit2BYL1pvk/dSOaJWjKoflh+RQjo= +github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= github.com/urfave/cli/v2 v2.10.2 h1:x3p8awjp/2arX+Nl/G2040AZpOCHS/eMJJ1/a+mye4Y= @@ -127,6 +134,7 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20221012134737-56aed061732a h1:NmSIgad6KjE6VvHciPZuNRTKxGhlPfD6OA87W/PLkqg= golang.org/x/crypto v0.0.0-20221012134737-56aed061732a/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -149,11 +157,11 @@ golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba h1:O8mE0/t419eoIwhTFpKVkHiTs/Igowgfkj25AcZrtiE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -163,16 +171,12 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=