From 15ae30443b9a922e80f846ce883b268e7d6d3de1 Mon Sep 17 00:00:00 2001 From: epiqueras Date: Sun, 6 Sep 2020 10:54:29 -0400 Subject: [PATCH] chore: auto-detect Web3 call type --- .eslintrc.js | 1 + _pages/profile/[id]/submit-profile-card.js | 5 +-- components/web3-provider.js | 37 +++++++++++++++------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 51905187..0423319a 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -64,6 +64,7 @@ module.exports = { "no-useless-return": "error", "no-var": "error", "object-shorthand": "error", + "one-var": ["error", "never"], "operator-assignment": "error", "prefer-arrow-callback": "error", "prefer-const": "error", diff --git a/_pages/profile/[id]/submit-profile-card.js b/_pages/profile/[id]/submit-profile-card.js index 738a936a..50cd3b44 100644 --- a/_pages/profile/[id]/submit-profile-card.js +++ b/_pages/profile/[id]/submit-profile-card.js @@ -26,10 +26,7 @@ export default function SubmitProfileCard() { const { connect } = useWeb3(); const { loading, send } = useContract( "proofOfHumanity", - "changeRequiredNumberOfVouches", - { - type: "send", - } + "changeRequiredNumberOfVouches" ); return ( { + _acc[method.name] = method; + return _acc; + }, + {} + ); return acc; }, {} @@ -131,17 +138,18 @@ const sendStateReducer = ( return { ...state, error }; } }; -export function useContract( - contract, - method, - { args, type = "call", options } -) { +export function useContract(contract, method, { args, type, options } = {}) { const { web3 } = useWeb3(); + type = + type || + (web3.contracts[contract].jsonInterfaceMap[method].constant + ? "call" + : "send"); const run = useCallback( - (_args) => - web3.contracts[contract].methods[method](...(args || []), ..._args)[type]( - ...(options || []) - ), + (_args, _options) => + web3.contracts[contract].methods[method](...(args || []), ..._args)[ + type + ]({ ...options, ..._options }), [web3.contracts, contract, method, args, type, options] ); const isSend = type === "send"; @@ -153,8 +161,15 @@ export function useContract( {} ); const send = useCallback( - (..._args) => { - run(_args) + (...__args) => { + let _args; + let _options; + if (__args.length === 1) _args = __args; + else { + _args = __args.slice(0, -1); + _options = __args[__args.length - 1]; + } + run(_args, _options) .on("transactionHash", (transactionHash) => dispatch({ type: "transactionHash", transactionHash }) )