Skip to content

Commit

Permalink
chore: auto-detect Web3 call type
Browse files Browse the repository at this point in the history
  • Loading branch information
epiqueras committed Sep 6, 2020
1 parent 1bab6c5 commit 15ae304
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 15 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Expand Up @@ -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",
Expand Down
5 changes: 1 addition & 4 deletions _pages/profile/[id]/submit-profile-card.js
Expand Up @@ -26,10 +26,7 @@ export default function SubmitProfileCard() {
const { connect } = useWeb3();
const { loading, send } = useContract(
"proofOfHumanity",
"changeRequiredNumberOfVouches",
{
type: "send",
}
"changeRequiredNumberOfVouches"
);
return (
<Card
Expand Down
37 changes: 26 additions & 11 deletions components/web3-provider.js
Expand Up @@ -70,6 +70,13 @@ export default function Web3Provider({ infuraURL, contracts, children }) {
from: accounts[0],
...options,
});
acc[name].jsonInterfaceMap = acc[name]._jsonInterface.reduce(
(_acc, method) => {
_acc[method.name] = method;
return _acc;
},
{}
);
return acc;
},
{}
Expand Down Expand Up @@ -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";
Expand All @@ -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 })
)
Expand Down

0 comments on commit 15ae304

Please sign in to comment.