{"id":13408763,"url":"https://github.com/Elrond-Giants/erd-react-hooks","last_synced_at":"2025-03-14T13:31:56.759Z","repository":{"id":47165588,"uuid":"504119159","full_name":"elrond-giants/erd-react-hooks","owner":"elrond-giants","description":null,"archived":false,"fork":false,"pushed_at":"2023-10-31T13:49:43.000Z","size":493,"stargazers_count":11,"open_issues_count":1,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-10-14T03:06:55.903Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/elrond-giants.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-06-16T10:55:42.000Z","updated_at":"2023-09-06T19:57:03.000Z","dependencies_parsed_at":"2024-10-26T04:07:24.984Z","dependency_job_id":"f16034a0-eb1b-48f3-ad5c-2b1ed1dcac62","html_url":"https://github.com/elrond-giants/erd-react-hooks","commit_stats":{"total_commits":19,"total_committers":1,"mean_commits":19.0,"dds":0.0,"last_synced_commit":"ce30d86792fcce20f4026ee6b853bf9554b69530"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elrond-giants%2Ferd-react-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elrond-giants%2Ferd-react-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elrond-giants%2Ferd-react-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elrond-giants%2Ferd-react-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/elrond-giants","download_url":"https://codeload.github.com/elrond-giants/erd-react-hooks/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243584421,"owners_count":20314756,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T20:00:55.077Z","updated_at":"2025-03-14T13:31:56.750Z","avatar_url":"https://github.com/elrond-giants.png","language":"TypeScript","funding_links":[],"categories":["MultiversX community"],"sub_categories":["SDKs and dev tools"],"readme":"# Elrond React Hooks\n\n### Overview\n\nThis is a library of React hooks built for the MultiversX ecosystem. It aims to make it easy to authenticate, sign and\nsend\ntransactions, and query* smart contracts.\n\nIt makes authentication as easy as:\n\n```typescript jsx\nconst {login} = useAuth();\n\nawait login(AuthProviderType.WEBWALLET);\n```\n\n### Install\n\n```bash\nnpm install @elrond-giants/erd-react-hooks\n```\n\n`@elrond-giants/erd-react-hooks` requires react 16.8+\n\n### Hooks\n\n#### `useAuth`\n\nThis hook makes it easy to authenticate with xPortal App, Web Wallet, Extension, and Ledger. It offers a context provider\nto keep track of the authentication status.\n\n##### How to use\n\n1. Wrap your components in the provided AuthContextProvider.\n\n```typescript jsx\nimport {AuthContextProvider} from \"@elrond-giants/erd-react-hooks\";\n\n\n\u003cAuthContextProvider env={{chainId: \"D\"}}\u003e\n    .....\n\u003c/AuthContextProvider\u003e\n```\n\n2. Use the value provided by AuthContextProvider.\n\n```typescript jsx\nimport {useAuth} from \"@elrond-giants/erd-react-hooks\";\nimport {AuthProviderType} from \"@elrond-giants/erd-react-hooks/dist/types\";\n\n\nfunction AuthComponent() {\n    const {address, authenticated, guardian, login, logout} = useAuth();\n\n    return (\n        \u003cdiv\u003e\n            \u003cp\u003eaddress: {address}\u003c/p\u003e\n            \u003cp\u003eauthenticated: {authenticated ? \"yes\" : \"no\"}\u003c/p\u003e\n            \u003cp\u003eGuarded: {guardian.guarded ? \"Yes\" : \"No\"}\u003c/p\u003e\n            \u003cp\u003ePending Guardian: {guardian.pendingGuardian?.address.bech32()}\u003c/p\u003e\n            \u003cp\u003eActive Guardian: {guardian.activeGuardian?.address.bech32()}\u003c/p\u003e\n            \u003cbutton onClick={async () =\u003e {\n                await login(AuthProviderType.EXTENSION);\n            }}\u003e\n                Login\n            \u003c/button\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\nYou can pass an object with a `token` to the `login` method, and it will be included in the auth signature.\n\n```typescript\nconst {provider, login} = useAuth();\nconst token = \"some_token\";\n\nawait login(AuthProviderType.WALLET_CONNECT, {token});\nconst authSignature = provider.getSignature();\n```\n\n:grey_exclamation: When using the *Wallet Connect provider* (xPortal), you MUST set the Wallet Connect Project ID. \nYou can generate the Project ID at https://cloud.walletconnect.com/sign-in.\n\nTo set it, you simply add it to the AuthContextProvider.\n```typescript jsx\n\u003cAuthContextProvider env={{chainId: \"D\"}} projectId=\"some-id\"\u003e\n```\n\n:grey_exclamation: When using the *Wallet Connect provider* (xPortal), the login method will return a promise that\nresolves with a URL.\nIt's a usual practice to put this URL in a QR code and let users scan it with xPortal App.\n\n:grey_exclamation: When using the *Ledger provider* you MUST set the `ledgerAccountIndex` in the options object of\nthe `login` method.\n\nThe `getLedgerAccounts(page?: number | undefined, pageSize?: number | undefined): Promise\u003cstring[]\u003e` method can be used\nto get a list of accounts.\n\n```typescript\nconst {login, getLedgerAccounts} = useAuth();\nconst accounts = getLedgerAccounts();\n\n// --------\n\nconst selectedAccountIndex = 1;\nawait login(AuthProviderType.LEDGER, {ledgerAccountIndex: selectedAccountIndex});\n```\n\nTo use the Webview Provider, you must enable it by setting `enableWebview` to the AuthContextProvider.\n```typescript jsx\n\u003cAuthContextProvider env={{chainId: \"D\"}} enableWebview={true}\u003e\n```\n\nIf you want to set custom api and gateway urls, you can do it by setting `apiUrl` and `gatewayUrl` to the\nAuthContextProvider.\n\n```typescript jsx \n\u003cAuthContextProvider\n    env={{\n        chainId: \"D\",\n        apiUrl: \"https://elrond-api-devnet.public.blastapi.io\"\n    }}\n\u003e\n```\n\n:grey_exclamation: Keep in mind that if you don't set the `apiUrl` and `gatewayUrl`, the default ones (provided by\nMultiversX) will be used. The Devnet default urls are the ones pointing to the Devnet 2.\n\n\n#### `useTransaction`\n\nThis hook makes it easy to sign and broadcast a transaction.\n\n##### How to use\n\nMake sure that `useTransaction` is used inside `AuthContextProvider` and the user is authenticated before trying to make\na\ntransaction.\n\n```typescript jsx\nimport {AuthContextProvider} from \"@elrond-giants/erd-react-hooks\";\n\n\n\u003cAuthContextProvider env={{chainId: \"D\"}}\u003e\n    .....\n\n    \u003cTransactionComponent/\u003e\n\n\u003c/AuthContextProvider\u003e\n````\n\n```typescript jsx\nimport {useTransaction} from \"@elrond-giants/erd-react-hooks\";\n\n\nfunction TransactionComponent() {\n    const {requires2FACode, makeTransaction, whenCompleted} = useTransaction();\n\n    const sendTx = async () =\u003e {\n        const txHash = await makeTransaction({\n            transaction:{\n                receiver: \"erd.....\",\n                data: \"test\",\n                value: 1000,\n            },\n            onBeforeSign: () =\u003e {\n                console.log(\"Hey, sign the transaction!\");\n            },\n            onSigned: () =\u003e {\n                console.log(\"Transaction signed!!\");\n            }\n        });\n\n        const txResult = await whenCompleted(txHash, {interval: 2000});\n        if (txResult.status.isExecuted()) {\n            console.log(\"Hooray, the transaction was successful!\");\n        }\n    };\n\n    return \u003cbutton onClick={sendTx}\u003emake transaction\u003c/button\u003e;\n    \n}\n```\nThe transaction data can be either a `string` or a `TransactionPayload` object.\n\n```typescript jsx\nimport {useTransaction} from \"@elrond-giants/erd-react-hooks\";\nimport {TransactionPayload} from \"@elrondnetwork/erdjs/out\";\n\nconst {makeTransaction, whenCompleted} = useTransaction();\nconst data: string | TransactionPayload = TransactionPayload.contractCall()\n    .setFunction(new ContractFunction(\"SomeFunction\"))\n    .addArg(new BigUIntValue(10))\n    .build();\n\n```\n\n#### Account Guardians\n\nThe `useAuth` hook provides a `guardian` object that contains information about the account guardians.\n\n```typescript jsx\nimport {useAuth} from \"@elrond-giants/erd-react-hooks\";\n\n\nconst {guardian} = useAuth();\n\nreturn (\n    \u003cdiv\u003e\n        \u003cp\u003eGuarded: {guardian.guarded ? \"Yes\" : \"No\"}\u003c/p\u003e\n        \u003cp\u003ePending Guardian: {guardian.pendingGuardian?.address.bech32()}\u003c/p\u003e\n        \u003cp\u003eActive Guardian: {guardian.activeGuardian?.address.bech32()}\u003c/p\u003e\n    \u003c/div\u003e\n);\n\n```\n\nThe transactions made from a guarded account need to be signed by the guardian. The current option is to use a service\nprovided by MultiversX, which uses 2-Factor Authentication (2FA) to sign the transaction.\n\nThe `requires2FACode` property of the `useTransaction` hook can be used to check if the transactions require 2FA.\n\nWhen using the Browser Extension provider, the guarding is done by the extension and the 2FA is not required. For the\nother providers, the transactions need to be signed by the guardian.\n\nThis package handles all the steps in an easy-to-implement way.\n\nThe `requires2FACode` will be `true` when the account is guarded and it is authenticated with a provider that does not\nhandle 2FA code input, otherwise it will be `false`.\n\nYou should use the `requires2FACode` to decide if you need to ask the user for the 2FA code. If you don't want to use a\ncustom 2FA input, the package can handle it for you using a simple browser prompt - it needs to be enabled by\nsetting `use2FABrowserInput` to the `AuthContextProvider`.\n\nWhen you have the 2FA code, you can call the `makeTransaction` method, and pass the code to it. Then the guarding will\nbe handled by the package using the MultiversX service that guards transactions.\n\n:exclamation: If you don't provide the 2FA code and the `use2FABrowserInput` is not enabled, the transaction(s) will not be guarded\nand fail.\n\n```typescript jsx\nimport {Address, Transaction, TransactionPayload} from \"@multiversx/sdk-core/out\";\n\n\nconst {requires2FACode, makeTransaction} = useTransaction();\nconst [code, setCode] = useState\u003cstring\u003e();\nconst sendTransaction = async () =\u003e {\n    const transaction = new Transaction({\n        data: new TransactionPayload(\"test\"),\n        gasLimit: 1_000_000,\n        value: 1_000,\n        sender: Address.fromBech32(\"erd.....\"),\n        receiver: Address.fromBech32(\"erd.....\"),\n    });\n    transaction.setNonce(1);\n    \n    const txHash = await makeTransaction({\n        transaction,\n        guard2FACode: code\n    });\n};\n\nreturn (\n    \u003cdiv\u003e\n        {requires2FACode \u0026\u0026 (\n            \u003cinput\n                type=\"text\"\n                value={code}\n                onChange={(e) =\u003e setCode(e.target.value)}\n            /\u003e\n        )}\n        \u003cbutton onClick={sendTransaction}\u003eMake Tx\u003c/button\u003e\n    \u003c/div\u003e\n);\n\n\n\n```\n\n#### Caveats\n\n:grey_exclamation: You SHOULD always provide a value for `gasLimit`. In case it is not provided, it will be computed\nusing `GasEstimator().forEGLDTransfer()`.\n\n:grey_exclamation: You SHOULD always manage and set the `nonce` when sending multiple transactions.\n\n:grey_exclamation: :grey_exclamation: When the account is authenticated with web wallet, the user will be redirected to\nMultiversX website to complete the transaction and then back to your application.\n\nYou can set the `webReturnUrl` when calling `makeTransaction({webReturnUrl: \"\"})`. By default, it is set to\nbe `window.location.href`.\n\n:grey_exclamation: :grey_exclamation: When the account is authenticated with web wallet, the `makeTransactions()` method\nwill not work and will throw an error. \n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FElrond-Giants%2Ferd-react-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FElrond-Giants%2Ferd-react-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FElrond-Giants%2Ferd-react-hooks/lists"}