├── .gitbook.yaml
├── .gitignore
├── LICENSE
├── README.md
├── SUMMARY.md
├── assets
├── faq.md
├── new-asset.md
├── pr-fee.md
├── repository_details.md
├── requirements.md
└── universal_asset_id.md
├── barz-smart-wallet
├── barz-smart-wallet.md
├── build-with-trust-wallet-and-barz-aa-sdk.md
├── cutting-diamonds-how-to-make-accounts-awesome.md
├── introducing-barz-trustwallet-smart-wallet-solution.md
└── security-monitoring-system-liability-statement.md
├── dapps
├── debugging.md
├── listing-guide.md
└── mobile-optimize.md
├── develop-for-trust
├── browser-extension
│ ├── browser-extension.md
│ └── evm.md
├── deeplinking
│ └── deeplinking.md
├── develop-for-trust.md
└── mobile
│ └── mobile.md
├── index.md
├── media
├── add-recovery-facet.png
├── android-dapp-emulator.png
├── android-install-apk-emulator.png
├── assetapp.png
├── barz-deployment-initialization-flow.png
├── barz-diagram.png
├── barz-storage-management.png
├── barz-userop-validation-flow.png
├── bsc-abi.gif
├── bsc-twt.png
├── conventional-proxy-pattern.png
├── diamond-louper-dev.png
├── diamond-proxy-pattern.png
├── edge-inspect.png
├── edge-inspect2.png
├── facet-registry.png
├── gitassetapp.png
├── github-packages-token.png
├── js-eth-sign-console.png
├── js-eth-sign.png
├── louper-barz.png
├── sourcetrail-screenshot.png
├── staking-steps.png
├── tw-aa-sdk.png
├── wallet-core-banner.png
└── wallet-core.png
└── wallet-core
├── android-guide.md
├── building.md
├── contributing.md
├── coverage.md
├── faq.md
├── integration-guide.md
├── ios-guide.md
├── newblockchain.md
├── newevmchain.md
├── releasing.md
├── rpc-requirements.md
├── server-side.md
├── wallet-core-usage.md
├── wallet-core.md
└── walletconsole.md
/.gitbook.yaml:
--------------------------------------------------------------------------------
1 | root: ./
2 |
3 | structure:
4 | readme: README.md
5 | summary: SUMMARY.md
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.gem
2 | .bundle
3 | .sass-cache
4 | _site
5 | Gemfile.lock
6 | node_modules
7 | .idea
8 | .vscode/
9 | *~
10 | _book/
11 | *.swp
12 | .DS_Store
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2017-2023 Trust Wallet
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Trust Developer Documentation
2 |
3 | Welcome to the Trust Wallet developer documentation. Here you can find documentation on contributing to Trust Wallet as well as on using Trust Wallet libraries on your own projects.
4 |
5 | - [Developing for Trust Wallet platform](develop-for-trust/develop-for-trust.md)
6 | - [Browser Extension](develop-for-trust/browser-extension/browser-extension.md)
7 | - [Mobile (WalletConnect)](develop-for-trust/mobile/mobile.md)
8 | - [Deep Linking](develop-for-trust/deeplinking/deeplinking.md)
9 | - [Listing new dApps](dapps/listing-guide.md)
10 | - [Listing new assets](assets/new-asset.md)
11 | - [Wallet Core](wallet-core/wallet-core.md)
12 | - [Barz - Smart Wallet](barz-smart-wallet/barz-smart-wallet.md)
13 |
14 | Want to discuss more? join our [Trust Wallet Developers](https://discord.gg/trustwallet) on Discord.
15 |
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Table of contents
2 |
3 | - [Get Started](README.md)
4 | - [Developing for Trust Wallet platform](develop-for-trust/develop-for-trust.md)
5 | - [Browser Extension](develop-for-trust/browser-extension/browser-extension.md)
6 | - [Ethereum & EVM chains](develop-for-trust/browser-extension/evm.md)
7 | - [Mobile (WalletConnect)](develop-for-trust/mobile/mobile.md)
8 | - [Deep Linking](develop-for-trust/deeplinking/deeplinking.md)
9 | - [Listing new dApps](dapps/)
10 | - [A Complete Guide to Listing your dApp with Trust Wallet](dapps/listing-guide.md)
11 | - [Optimizing your dApp for Trust Wallet](dapps/mobile-optimize.md)
12 | - [Debugging](dapps/debugging.md)
13 | - [Listing new assets](assets/)
14 | - [Add Asset](assets/new-asset.md)
15 | - [Requirements](assets/requirements.md)
16 | - [Pull Request Fee](assets/pr-fee.md)
17 | - [FAQ](assets/faq.md)
18 | - [Repository Details](assets/repository_details.md)
19 | - [Universal Asset ID](assets/universal_asset_id.md)
20 | - [Wallet Core](wallet-core/wallet-core.md)
21 | - [New Blockchain Support](wallet-core/newblockchain.md)
22 | - [RPC / API Requirements](wallet-core/rpc-requirements.md)
23 | - [New EVM-compatible chain](wallet-core/newevmchain.md)
24 | - Developing the Library
25 | - [Contributing](wallet-core/contributing.md)
26 | - [Building](wallet-core/building.md)
27 | - [WalletConsole utility](wallet-core/walletconsole.md)
28 | - [Coverage](wallet-core/coverage.md)
29 | - [Releasing](wallet-core/releasing.md)
30 | - [Integration Guide](wallet-core/integration-guide.md)
31 | - [Usage Guide](wallet-core/wallet-core-usage.md)
32 | - [iOS Integration Guide](wallet-core/ios-guide.md)
33 | - [Android Integration Guide](wallet-core/android-guide.md)
34 | - [Server-Side](wallet-core/server-side.md)
35 | - References
36 | - [Swift API Reference](https://trustwallet.github.io/docc/documentation/walletcore/)
37 | - [Kotlin API Reference](https://trustwallet.github.io/dokka/)
38 | - [FAQ](wallet-core/faq.md)
39 | - [Barz - Smart Wallet](barz-smart-wallet/barz-smart-wallet.md)
40 | - [Introducing Barz. TrustWallet's Smart Wallet Solution](barz-smart-wallet/introducing-barz-trustwallet-smart-wallet-solution.md)
41 | - [Cutting Diamonds: How to make Accounts Awesome](barz-smart-wallet/cutting-diamonds-how-to-make-accounts-awesome.md)
42 | - [Build with Trust Wallet and Barz, A Comprehensive Guide to Integrating Barz with AA SDK](barz-smart-wallet/build-with-trust-wallet-and-barz-aa-sdk.md)
43 |
--------------------------------------------------------------------------------
/assets/faq.md:
--------------------------------------------------------------------------------
1 | ## FAQ
2 |
3 | ### Why is the build on my pull request red?
4 |
5 | Contributions in a pull request are verified by an automated build.
6 | The checks fail if something is wrong, like to logo is too large or an Ethereum contract is not in
7 | [checksum format](#checksum-format).
8 | Checks the exact error message in the build to find out the problem.
9 |
10 | ### Why is there a merge conflict in my pull request?
11 |
12 | A merge conflict happens if the same file has been modified in the pull request, and also in the master branch since the fork was created. With assets repo, this typically caused by using a fork that was created long ago.
13 | The simplest solution in this case is to delete your pull request, delete your fork, create a new fork, and create a new PR. Alternatively, a merge conflict can be resolved using git command line, but Git skills are required.
14 | A pull request can also happen when overriding an existing logo.
15 |
16 | ### Why I don't see my token in search after PR was merged?
17 |
18 | After PR was merged, it may take some time, but not longer than one hour, until search will show the new logo.
19 |
20 | ### Why do I still see old logo in Trust Wallet after uploaded new one?
21 |
22 | Both clients, Android and iOS keep old image cache for up to a few days. In order to see changes immediately, reinstall Trust Wallet. But as always, make sure you have a backup of all your wallets.
23 |
24 | ### What is smart contract deprecation?
25 |
26 | A process of removing smart contract information such as (token logo and info) from this repository.
27 | Removed contract address will be added to the denylist and, as a result, will no longer be present in token search results inside the TW app.
28 | Why would you want to do this ?.
29 | You are contract owner or just good samaritan who noticed contract to be no longer "active" and was an upgrade and abandoned by owning organization, involved in a scam, mimicking by its name or/and symbol a real contract. All facts must be supported with a link to any resource proving these statements.
30 |
31 | ### Why isn't my token's price displaying in the app?
32 |
33 | Token prices will only show up within Trust Wallet if the CoinMarketCap (CMC) listing has the correct contract address associated with it. You can submit changes to your CMC listing via their [online form](https://support.coinmarketcap.com/hc/en-us/requests/new). Once an asset's contract address has been added to it's CMC listing, and the asset has enough transaction volume, pricing data will automatically appear in Trust Wallet.
34 |
35 | Note: submitting an asset to the Trust Wallet repository does not guarantee that can pricing data can or will be associated by CMC. Please review CMC's listing criteria [here](https://support.coinmarketcap.com/hc/en-us/articles/360043659351-Listings-Criteria).
36 |
--------------------------------------------------------------------------------
/assets/new-asset.md:
--------------------------------------------------------------------------------
1 | # Trust Wallet Assets Info
2 |
3 |
4 |
5 | ## Overview
6 |
7 | The [Trust Wallet Token Repository](https://github.com/trustwallet/assets)
8 | is a comprehensive, up-to-date collection of information about several thousands of crypto tokens.
9 | [Trust Wallet](https://trustwallet.com) uses token logos from this source, alongside a number of third-party projects.
10 |
11 | The repository contains token info from several blockchains, info on dApps, staking validators, etc.
12 | For every token a logo and optional additional information is available (such data is not available on-chain).
13 |
14 | Such a large collection can be maintained only through a community effort, so _additions are welcome_,
15 | primarily from token projects.
16 |
17 |
18 |
19 |
20 |
21 | ⚠️ NOTE
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
All assets are subject to review before being approved; so-called "meme tokens", spammy, or assets identified as fradulent in nature will not be merged into the repository
31 |
Payment of the Pull Request Fee does not guarantee your asset will be approved. Fee is non-refundable
32 |
33 |
34 |
35 |
36 |
37 |
38 | ## Contribution Checklist
39 |
40 | This guide is for adding a logo for the following Trust Wallet supported blockchains:
41 |
42 | - [Ethereum ERC20 token](https://github.com/trustwallet/assets/tree/master/blockchains/ethereum/assets)
43 | - [Binance BEP2 token](https://github.com/trustwallet/assets/tree/master/blockchains/binance/assets)
44 | - [Smart Chain BEP20 token](https://github.com/trustwallet/assets/tree/master/blockchains/smartchain/assets)
45 | - [TRON TRC10, TRC20 token](https://github.com/trustwallet/assets/tree/master/blockchains/tron/assets)
46 |
47 | For **adding an token**:
48 |
49 | - [ ] Ensure your asset meets our [reqirements](requirements.md)
50 | - [ ] Visit the [Assets web app](https://assets.trustwallet.com) (GitHub account required), and fill out the requested information
51 | - [ ] Pay the [processing fee](pr-fee.md)
52 |
53 | Adding a DApp logo or other type of asset? Check the [DApps](../dapps/listing-guide.md) section or [contribution guidelines](repository_details.md#contribution-guidelines).
54 |
55 | ### Adding new Assets using Asset App
56 |
57 | This is a quick walkthrough on how to add your token using our Asset Web App.
58 |
59 | Every Trust Wallet user can submit his token using our Web App. Before initiating a Pull Request or going further, please take a look at the requirements in our documentation: https://developer.trustwallet.com/assets/requirements and make sure you follow the requirements!
60 |
61 | The steps for adding a new token through Asset App.
62 |
63 | - Access the **assets web app** via this link: https://assets.trustwallet.com
64 | 
65 |
66 | - Log in to your **GitHub account**. If you have not yet logged in (using the current browser), it is compulsory to log in to your GitHub account.
67 | 
68 |
69 | - If you are logging in for the first time you will need to authorize the Assets app to access your GitHub account
70 | - Upload the logo file.
71 | - Fill out the token contract.
72 | Note: For some tokens like (ERC20) some fields are auto-filled (symbol, decimals, etc.).
73 | - Fill in additional fields, symbols, decimals, descriptions, links, etc.
74 | - Press the \*\*Check button.
75 | - If all is **OK**, press the Create Pull Request button. A PR will be created.
76 |
77 | ### Fee
78 |
79 | Due to an increasing number of pull request (and proportional checking & merging effort),
80 | a modest fee is required for processing a pull request, payable in cryptocurrency.
81 | Follow the instructions in the pull request for completing the fee payment.
82 |
83 | A fee of **500TWT or 5BNB** is required for each Pull Request, you will see the message from the merge-fee-bot with details about the payment. \*\*Make sure to double-check the https://developer.trustwallet.com/assets/requirements, to minimize the risk of your PR being rejected.
84 |
85 | For more details about the payment fee for your assets, see https://developer.trustwallet.com/assets/pr-fee
86 | See also the [fee FAQ](pr-fee.md)
87 |
88 | ## Disclaimer
89 |
90 | Trust Wallet team allows anyone to submit new assets to this repository. However, this does not mean that we are in direct partnership with all of the projects.
91 |
92 | Trust Wallet team will reject projects that are deemed as scam or fraudulent after careful review.
93 | Trust Wallet team reserves the right to change the terms of asset submissions at any time due to changing market conditions, risk of fraud, or any other factors we deem relevant.
94 |
95 | Additionally, spam-like behavior, including but not limited to mass distribution of tokens to random addresses will result in the asset being flagged as spam and possible removal from the repository.
96 |
--------------------------------------------------------------------------------
/assets/pr-fee.md:
--------------------------------------------------------------------------------
1 | # Pull Request Fee -- FAQ
2 |
3 | Trust Wallet supports an insane number of assets/tokens requests.
4 | We are committed to supporting the tokens used by our users, but supporting millions of assets comes at a high cost. In terms of running the infrastructure, ensuring continuous integrations, handling a massive number of requests to the assets info, etc., and also avoiding a lot of spam/scam coins.
5 | We have introduced this crypto contribution in order to filter requests, so we have more time to handle genuine ones.
6 | We were partly inspired by Token Curated Registry.
7 |
8 | A fee of 500TWT or 5BNB is required for each Pull Request, you will see the message from the merge-fee-bot with details about the payment. Make sure to double-check the https://developer.trustwallet.com/assets/requirements to minimize the risk of your PR being rejected.
9 |
10 | ## Why the payment?\*\*
11 |
12 | - Due to a high number of pull requests, this led to a high cost of running infrastructure. A modest fee is required for processing a pull request, which is payable in cryptocurrency.
13 | - Cost is used to run the infrastructure that powers millions of Assets/tokens
14 | - Reducing spam/scam coins/tokens request
15 | - Ensuring smooth integration and handling of a massive number of assets request
16 |
17 | **How does this Fee fit with Open Source?**
18 |
19 | We believe in the power of open-source software, and essential parts of Trust Wallet are open-source to contribute to the community(Wallet-Core). But Trust Wallet is a branded product, and running its backend infrastructure, support, marketing, etc. has costs (done by a non-volunteer-based team).
20 | The assets repository is open source. You are free to use it and free to create your version (fork it and change it). But if you want to get into our app, you have to accept our rules, and we've chosen to ask for a contribution to include/change the information in the Trust Wallet product.
21 |
22 | **What do I have to pay attention to?**
23 |
24 | - Double-check the contribution guidelines, to minimize the risk of your PR being rejected.
25 | - Make sure to set the correct memo on your transfer.
26 |
27 | ## See FAQs question:
28 |
29 | **Is crypto payment for processing my Pull Request a scam?**
30 |
31 | No, it's not a scam!
32 | This is a legitimate request from the Trust Wallet team, but always be cautious when someone asks you for payment! Check that there is a description about it under Trust Wallet Developers' documentation (this page). Check that the app is under the trust wallet GitHub account, or that its owner belongs to the Trust Wallet group, and finally check thoroughly that you are using the correct URL: https://assets.trustwallet.com/
33 |
34 | **When is my payment evaluated?**
35 |
36 | Payment is handled automatically by our bot. The fee payment should be detected automatically (mostly within a minute).
37 |
38 | **What happens after I pay? Is merging automatically?**
39 |
40 | When the bot detects payment, it automatically places an “Accept Review” on the PR. This is a precondition for merging. But merging is currently not automatic, it is done by the maintainers.
41 |
42 | **I forgot to set a memo in my transfer, do I have to send another payment?**
43 |
44 | Yes. Crypto transactions are final and irreversible. As such, payments with missing memos or mistyped addresses cannot be recovered. Please verify all transaction details carefully before sending payment.
45 |
46 | **If you decide not to merge my PR, do I get my payment back?**
47 |
48 | The pull request fee is non-refundable and covers the processing only; payment is not a guarantee that your pull request will be merged. Please consult the contribution guidelines before paying the fee.
49 |
50 | **Do I need to pay the PR fee again to make updates to my submission?**
51 |
52 | If your asset is already accepted into the repository, subsequent updates will require payment of the fee to cover processing your changes. This includes changes made for name changes, logo changes, rebranding, etc.
53 |
54 | **Can the fee be waived?**
55 |
56 | Not really. Inclusions decided and performed by our team are done without fee, but for external-triggered changes, we require the fee.
57 |
58 | **What is Trust Wallet Token TWT?**
59 |
60 | TWT is the token of Trust Wallet, with uses such as our Referral Program. TWT lives in multiple chains and can be obtained on several exchanges (TWT Community page).
61 |
--------------------------------------------------------------------------------
/assets/repository_details.md:
--------------------------------------------------------------------------------
1 | ## Repository Details
2 |
3 | ### Collections
4 |
5 | The token repository contains the following collections:
6 |
7 | 1. [ERC20](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md), ERC223 tokens on Ethereum compatible networks such as:
8 | - [Ethereum (ETH)](https://ethereum.org/)
9 | - [Ethereum Classic (ETC)](https://ethereumclassic.org/)
10 | - [POA Network (POA)](https://poa.network/)
11 | - [TomoChain (TOMO)](https://tomochain.com/)
12 | - [GoChain (GO)](https://gochain.io/)
13 | - [Wanchain (WAN)](https://wanchain.org/)
14 | - [Callisto Network (CLO)](https://callisto.network/)
15 | - [Thunder Token (TT)](https://thundercore.com/), etc.
16 | 2. Binance DEX tokens (native marketplace on Binance Chain)
17 | - [BEP2](https://github.com/binance-chain/BEPs/blob/master/BEP2.md)
18 | - [BEP8](https://github.com/binance-chain/BEPs/blob/master/BEP8.md)
19 | 3. Tokens on TRON blockchain [(TRC10, TRC20)](https://developers.tron.network/docs/trc10-token)
20 | 4. DApp logos displayed in `Browser` section of the Trust Wallet app, and bookmarks icons
21 | - [Image naming requirements](#dapp-image-naming-requirements)
22 | - [Request listing in Trust Wallet DApp Browser](#dapp-submission-and-listing-requirements)
23 | 5. Staking validators information, such as name: `image`, `validator_id`, `website_url`
24 | - [Supported staking coins](https://trustwallet.com/staking/)
25 | - [Read requirements](#staking-validators-requirements).
26 | 6. Crypto price providers map: [CoinMarketCap](https://github.com/trustwallet/assets/blob/master/pricing/coinmarketcap/mapping.json)
27 | 7. Token and coin information
28 | 8. Smart contract deprecation/upgrade. [Read more](#update-and-remove-an-existing-asset)
29 |
30 | ### Repository structure
31 |
32 | The `blockchains` folder contains several subfolders corresponding to blockchain networks, such as
33 | `ethereum`, `binance`, etc.
34 |
35 | The `assets` subfolder contains token folders named by smart contract address,
36 | in [checksum format](#checksum-format) for Ethereum like networks.
37 | This folder should contain the `logo.png` image file, and the `info.json` file.
38 |
39 | For other networks the address must be specified as it was originated on the chain, e.g TRON TRC10: `1002000`, TRON TRC20: `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` etc.
40 |
41 | The `info` folder contains a `logo.png` that represents the coin image.
42 |
43 | The `validators` folder contains folders: `assets` same structure as above and `list.json` information about validators.
44 |
45 | The `denylist.json` and `allowlist.json`, present in some chain folders like `ethereum` and `binance`, contain list of approved tokens and banned tokens. Trust Wallet will never show denylisted tokens, and only allowlisted tokens are shown in the token search results.
46 |
47 | #### Checksum format
48 |
49 | For Ethereum like networks, contract folders must be named according to the so-called **Checksum Format**, with mixed lowercase and uppercase letters, such as `0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359`.
50 | Non-checksum addresses (e.g. all lowercase) are considered invalid.
51 |
52 | You can find the checksum address by searching on [etherscan.io](https://etherscan.io),
53 | for example stablecoin [DAI](https://etherscan.io/address/0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359)
54 | the checksum address is located at the top left corner of the page and has both uppercase and lowercase characters.
55 | Or [convert Ethereum address to Checksum address](https://piyolab.github.io/sushiether/RunScrapboxCode/?web3=1.0.0-beta.33&code=https://scrapbox.io/api/code/sushiether/web3.js_-_Ethereum_%E3%81%AE%E3%82%A2%E3%83%89%E3%83%AC%E3%82%B9%E3%82%92%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%82%B5%E3%83%A0%E4%BB%98%E3%81%8D%E3%82%A2%E3%83%89%E3%83%AC%E3%82%B9%E3%81%AB%E5%A4%89%E6%8F%9B%E3%81%99%E3%82%8B/demo.js).
56 |
57 | #### Layout
58 |
59 | ```
60 | .
61 | ├── blockchains
62 | │ └──ethereum
63 | │ │ └──assets
64 | │ │ │ └──0x0a2D9370cF74Da3FD3dF5d764e394Ca8205C50B6 // address folder
65 | │ │ │ └──logo.png // token logo
66 | | | | └──info.json // optional token info
67 | │ │ └──info
68 | │ │ │ └──logo.png // chain coin logo
69 | | | │ └──info.json // chain coin info
70 | │ │ └──allowlist.json // list of accepted tokens
71 | │ │ └──denylist.json // list of blocked tokens
72 | | |
73 | | └──binance
74 | │ │ └──assets
75 | │ │ │ └──ONE-5F9
76 | │ │ │ └──logo.png
77 | | | | └──info.json
78 | │ │ └──info
79 | │ │ └──logo.png
80 | | └──tron
81 | │ | └──assets
82 | │ | │ └──1002000
83 | │ | │ | └──logo.png
84 | | | | | └──info.json
85 | | | | └──TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
86 | | | | └──logo.png
87 | | | | └──info.json
88 | | | |
89 | │ | └──info
90 | │ | └──logo.png
91 | | | └──info.json
92 | | |
93 | | └──cosmos
94 | │ │ └──info
95 | | | | └──logo.png
96 | | | | └──info.json
97 | | | |
98 | │ │ └──validators
99 | │ │ | └──assets
100 | | | | └──cosmosvaloper1clpqr4nrk4khgkxj78fcwwh6dl3uw4epsluffn
101 | | | | └──logo.png
102 | | | |
103 | | | └──list.json
104 | ├── ...
105 | ```
106 |
107 | ## Contribution Guidelines
108 |
109 | ### Contribution Use Cases
110 |
111 | #### Add new asset
112 |
113 | 1. Prepare asset, look at [image requirements](#image-requirements), [dapp requirements](#dapp-image-naming-requirements).
114 | 2. Get familiar with our [folder structure](#repository-structure), it will give you an understanding where assets should be placed
115 | 3. [Add asset guide](#how-to-add-files)
116 | 4. Pay the merge [fee](#fee)
117 |
118 | #### Update and remove an existing asset
119 |
120 | Whenever you updating or deleting an asset on behalf of the asset owner or just found outdated information, please provide a link to the source saying about changes. That will help to speed up the review process.
121 |
122 | This instruction wil be helpfull if you want to:
123 |
124 | 1. Update information about the smart contract
125 |
126 | 2. [Deprecate](#what-is-smart-contract-deprecation) or update contract address
127 |
128 | Smart contract address update procedure:
129 |
130 | 1. Rename old contract address in coresponding coin folder to new contract e.g.:
131 |
132 | 1. Remove smart contract e.g.:
133 |
134 | ```bash
135 | `rm -r ./blockchains//assets//`
136 |
137 | `rm -r ./blockchains/ethereum/assets/0x19fFfd124CD9089E21026d10dA97f8cD6B442Bff/`
138 | ```
139 |
140 | 2. Commit changes and make a PR (pull request)
141 |
142 | ### Image Requirements
143 |
144 | - File location: must be placed in the correct folder and subfolder within the [folder structure](#repository-structure).
145 | - File name:`logo.png`, all lowercase. Extension: `png` (uppercase `PNG` is considered invalid).
146 | - Dimension: recommended `256 x 256 pixels`, maximum `512 x 512 pixels`, aspect ratio should be 1:1.
147 | - File size: maximum 100kB. Tip: optimize image size, e.g. using simple drag-and-drop online service [tinypng](https://tinypng.com/).
148 | - Edges and background:
149 | - Logos are displayed cropped to a circular mask, a circle fitting in the square shape. Thus the corners of the logo image will not be visible. The logo should fit in the circle, but also fill it as much as it possible, i.e. there should not be unused spaces on the sides/top/bottom.
150 | - Logos should look OK with white/lightgray background as well as on black/darkgray background (night mode). For dark themed logos use white contour lines to make sure they stand out on dark background as well.
151 | - Avoid using transparency inside the logo, as the color beneath the transparent layer is changing (light or dark). Use transparency only outside of the logo.
152 | - It is recommended to use the [Assets web app](https://assets.trustwallet.com) ([guide](https://community.trustwallet.com/t/how-to-submit-a-token-logo-using-assets-app/82957)), as it shows a preview of the logo with both light and dark background and circular cropping.
153 |
154 | ### Info.json Contents
155 |
156 | The `info.json` file contains basic information about the token/project.
157 |
158 | It has following required fields:
159 |
160 | - `name`: name of the token
161 | - `type`: such as ERC20, BEP2, BEP20, TRC20, TRC10, ...
162 | - `symbol`: the token symbol
163 | - `decimals`: number of decimal digits used in the amounts (e.g. 18 for ETH)
164 | - `description`: a few sentence summary of the token/project
165 | - `website`: project web site
166 | - `explorer`: URL of the token explorer page
167 | - `status`: `"active"`
168 | - `id`: the id/contract/address of the token, same as the subfolder name
169 | - `links`: Array with `name`/`url` pairs, for social media links, documentation, etc.
170 | List of currently supported types:
171 | `github`, `whitepaper`, `twitter`, `telegram`, `telegram_news`, `medium`, `discord`, `reddit`, `facebook`, `youtube`, `coinmarketcap`, `coingecko`, `blog`, `forum`, `docs`, `source_code`.
172 | Note: the `socials` section is no longer used.
173 | - `tags`: Assigning these tags to tokens helps place them on appropriate token menus and ensures your token is evaluated correctly in conditions.
174 | List of currently supported tags:
175 | `stablecoin`, `wrapped`, `synthetics`, `nft`, `governance`, `defi`, `staking`, `staking-native`, `privacy`, `nsfw`, `binance-peg`, `deflationary`, `memes`, `gamefi`.
176 |
177 | If in doubt about fields, look around / search in existing info.json files.
178 |
179 | Sample `info.json`:
180 |
181 | ```
182 | {
183 | "name": "Trust Wallet Token",
184 | "website": "https://trustwallet.com",
185 | "description": "Utility token to increase adoption of cryptocurrency.",
186 | "explorer": "https://explorer.binance.org/asset/TWT-8C2",
187 | "type": "BEP2",
188 | "symbol": "TWT",
189 | "decimals": 8,
190 | "status": "active",
191 | "id": "TWT-8C2",
192 | "links": [
193 | {
194 | "name": "github",
195 | "url": "https://github.com/trustwallet/"
196 | },
197 | {
198 | "name": "twitter",
199 | "url": "https://twitter.com/TrustWalletApp"
200 | },
201 | {
202 | "name": "reddit",
203 | "url": "https://reddit.com/r/trustapp"
204 | }
205 | ]
206 | "tags": [
207 | "governance"
208 | ]
209 | }
210 | ```
211 |
212 | ### dApp image naming requirements
213 |
214 | - [Folder for upload](https://github.com/trustwallet/assets/tree/master/dapps)
215 | - `..png` e.g:
216 | https://app.compound.finance/ => `app.compound.finance.png`
217 | https://kyberswap.com/ => `kyberswap.com.png`
218 |
219 | ### dApp submission and listing requirements
220 |
221 | - Upload [logo](https://github.com/trustwallet/assets/tree/master/dapps)
222 | – Make sure you follow rules for image requirements.
223 | - Integrate [deep linking](https://developer.trustwallet.com/deeplinking)
224 | - Add [logo](https://trustwallet.com/press) as dApp supported wallet
225 | - Test dApp inside Trust Wallet on iOS and Android devices
226 | - [Submit form for review](https://docs.google.com/forms/d/e/1FAIpQLSd5p9L78zKXIiu9E5yFRPf5UkvsLZ7TbUDLFBRIi1qMd8Td4A/viewform)
227 |
228 | ### Staking validators requirements
229 |
230 | 1. Add validator basic information to the bottom of the list, see example for: [Kava](https://github.com/trustwallet/assets/tree/master/blockchains/kava/validators/list.json), [Cosmos](https://github.com/trustwallet/assets/tree/master/blockchains/cosmos/validators/list.json), [Tezos](https://github.com/trustwallet/assets/tree/master/blockchains/tezos/validators/list.json), [Tron](https://github.com/trustwallet/assets/tree/master/blockchains/tron/validators/list.json), [Solana](https://github.com/trustwallet/assets/tree/master/blockchains/solana/validators/list.json), [Harmony](https://github.com/trustwallet/assets/tree/master/blockchains/harmony/validators/list.json)
231 | 2. Add validator logo image to `blockchains//validators/assets//logo.png` [see images requirements](#image-requirements)
232 | 3. Check chain [specific](#validators-specific-requirements) requirements.
233 |
234 | ### Common Uploads
235 |
236 | 1. Ethereum ERC20 [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/ethereum/assets)
237 | 2. Binance DEX BEP2, BEP8 token [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/binance/assets)
238 | 3. TRON TRC10, TRC20 token [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/tron/assets)
239 | 4. Add Cosmos validator image [](https://github.com/trustwallet/assets/tree/master/blockchains/cosmos/validators)
240 | 5. Add Tezos validator info [](https://github.com/trustwallet/assets/tree/master/blockchains/tezos/validators/list.json)
241 | 6. Add Ethereum contract address to denylist [](https://github.com/trustwallet/assets/tree/master/blockchains/ethereum/denylist.json)
242 | 7. Add TRON TRC10 ID or TRC20 owner contract address to allowlist [](https://github.com/trustwallet/assets/tree/master/blockchains/tron/allowlist.json)
243 |
244 | ### How To Add Files
245 |
246 | If you are not familiar with GitHub or Git, the process of adding new tokens may look complicated at first glance, but it consists of only a few steps, and is not very complicated.
247 |
248 | #### Basics, Prerequisites
249 |
250 | The assets repository is maintained in [GitHub](https://github.com), the largest hosting for open source projects.
251 | You need a GitHub account to interact with it.
252 |
253 | To do changes in the assets repository, you need to create a personal copy called a _fork_.
254 |
255 | Once the changes are prepared inside the fork, you need to create a _pull request_ to the main repository.
256 | Upon review the maintainers will accept your pull request, and the changes will be incorporated.
257 |
258 | #### Adding files using Assets App
259 |
260 | A new token can be submitted using the Assets application.
261 | See also: https://community.trustwallet.com/t/how-to-submit-a-token-logo-using-assets-app/82957
262 |
263 | 1. Open the assets web app: [https://assets.trustwallet.com](https://assets.trustwallet.com)
264 | 2. Press the Log in with Github button. If not yet logged in (in the current browser session), you need to log in to Github
265 | 3. First time you will need to authorize the Assets app to access your Github account.
266 | 4. Upload the logo file.
267 | 5. Fill the token contract. For some tokens (ERC20) some fields are auto-filled (symbol, decimals, etc.).
268 | 6. Fill in additional fields, symbol, decimals, description, links, etc.
269 | 7. Press the Check button.
270 | 8. If all is OK, press the Create Pull Request button. A PR will be created.
271 |
272 | ## Token Status
273 |
274 | `active` - Token meets the standard requirements in circulation (number of holders and transactions).
275 |
276 | `spam` - Token that is distribtued to a large number of recepients that have no inherent value or has been verified as a dishonest scheme or fraud.
277 |
278 | `abandoned` - Token with very low activity (below 100 token transfers a year), migrated to mainnet or to a new contract.
279 |
280 | No longer active
281 |
--------------------------------------------------------------------------------
/assets/requirements.md:
--------------------------------------------------------------------------------
1 | # Prerequisites
2 |
3 | Before submitting an asset to this repository, we recommend you have the following information handy:
4 |
5 | - Asset details
6 | - Token Name
7 | - Symbol
8 | - Contract Address
9 | - Decimals
10 | - BNB or TWT to cover the non-refundable [processing fee](pr-fee.md)
11 | - Logo
12 | - File Extension: `png` (Uppercase PNG is considered invalid)
13 | - File Name: logo.png
14 | - Size: 256px by 256px
15 | - Background: Preferably transparent
16 | - Token information file
17 | - File Extension: `json` (Uppercase JSON is considered invalid)
18 | - File Name: `info.json`
19 | - Required fields:
20 | - `name`: name of the token
21 | - `type`: such as ERC20, BEP2, BEP20, TRC20, TRC10, ...
22 | - `symbol`: the token symbol
23 | - `decimals`: number of decimal digits used in the amounts (e.g. 18 for ETH)
24 | - `description`: a few sentence summary of the token/project
25 | - `website`: project web site
26 | - `explorer`: URL of the token explorer page
27 | - `id`: the id/contract/address of the token, same as the subfolder name
28 | - `links`: array with name/url pairs, for social media links, documentation, etc.
29 | - `tags`: Assigning these tags to tokens helps place them on appropriate token menus and ensures your token is evaluated correctly in conditions.
30 | - Checksum address (for ERC20 and BEP20 tokens)
31 | - Checksum addresses can be found on [Etherscan](https://etherscan.io) or by using [this tool](https://piyolab.github.io/sushiether/RunScrapboxCode/?web3=1.0.0-beta.33&code=https://scrapbox.io/api/code/sushiether/web3.js_-_Ethereum_%E3%81%AE%E3%82%A2%E3%83%89%E3%83%AC%E3%82%B9%E3%82%92%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%82%B5%E3%83%A0%E4%BB%98%E3%81%8D%E3%82%A2%E3%83%89%E3%83%AC%E3%82%B9%E3%81%AB%E5%A4%89%E6%8F%9B%E3%81%99%E3%82%8B/demo.js)
32 |
33 | ## Listing Acceptance Guidelines
34 |
35 | The following criteria will be considered before an asset is accepted into the repository. Note that meeting all these criteria does not guarantee a submission will be accepted, the team reserves the right to reject projects deemed spammy, fraudulent, or otherwise low value.
36 |
37 | - Project has a website and a detailed white paper. A clear roadmap, tokenomics and use case is a must.
38 | - Has a social media presence and support team. No fake followers or bots.
39 | - A full token audit is completed by reputable security audit groups. Partial audits are subject for review.
40 | - No plagiarized content from other projects or companies. Copying names or logos are strictly prohibited.
41 | - Token should be listed on price tracking sites like CoinmarketCap
42 | - Detailed Token Information
43 | - Minimum 10,000 token holders and 15,000 transactions (**Airdrop tokens excluded**). This requirement is subject for review based on the project.
44 |
--------------------------------------------------------------------------------
/assets/universal_asset_id.md:
--------------------------------------------------------------------------------
1 | # Universal Asset ID
2 |
3 | UAI unique identifier of the asset, it's blockchain agnostic and provides ability to easily distinguish asset across blockchains.
4 |
5 | ## Params:
6 |
7 | - `c` - coin (required), for most coins it uses [slip 44 index](https://github.com/trustwallet/wallet-core/blob/master/docs/registry.md) conventions, There is some exceptions that it's using [coinId](https://github.com/trustwallet/wallet-core/blob/master/registry.json#L1472) based on Wallet Core config
8 | - `t` - token (optional), following standard of unique identifier on the blockhain as smart contract address or asset ID
9 |
10 | ## Examples:
11 |
12 | ### Coins:
13 |
14 | - Bitcoin: `c0`
15 | - Ethereum: `c60`
16 | - Binance Chain `c714`
17 |
18 | ### Tokens:
19 |
20 | - DAI (Ethereum): `c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F`
21 | - BUSD (Binance Chain): `c714_tBUSD-BD1`
22 | - USDT (Tron): `c195_tTR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`
23 | - DAI (Smart Chain): `c10000714_t0x6B175474E89094C44Da98b954EedeAC495271d0F`
24 |
25 | Template: `c{coin}_t{token_id}`
26 |
--------------------------------------------------------------------------------
/barz-smart-wallet/barz-smart-wallet.md:
--------------------------------------------------------------------------------
1 | # Barz. Smart Wallet Solution.
2 |
3 | ## Introduction
4 |
5 | [Barz](https://github.com/trustwallet/barz) is an [ERC 4337](https://eips.ethereum.org/EIPS/eip-4337) compatible Smart Contract Wallet focused on a secure and smarter experience for users through modular, upgradeable, and secure designs.
6 |
7 | 
8 |
9 | Check out our blog series for details!
10 |
11 | [1. Introducing Barz. Trust Wallet's Smart Wallet Solution](/barz-smart-wallet/introducing-barz-trustwallet-smart-wallet-solution.md)
12 |
13 | [2. Cutting Diamonds: How to Make Accounts Awesome](/barz-smart-wallet/cutting-diamonds-how-to-make-accounts-awesome.md)
14 |
15 | [3. Build with Trust Wallet and Barz, A Comprehensive Guide to Integrating Barz with AA SDK](/barz-smart-wallet/build-with-trust-wallet-and-barz-aa-sdk.md)
16 |
17 | [Github Codebase](https://github.com/trustwallet/barz)
18 |
19 | ## License
20 |
21 | Barz is available under the Apache-2.0 license. See the [LICENSE](https://github.com/trustwallet/barz/blob/main/LICENSE) file for more information.
22 |
--------------------------------------------------------------------------------
/barz-smart-wallet/build-with-trust-wallet-and-barz-aa-sdk.md:
--------------------------------------------------------------------------------
1 | # Build with Trust Wallet and Barz, A Comprehensive Guide to Integrating Barz with AA SDK
2 |
3 | By [Moncif Loukili](https://x.com/monciflo)
4 |
5 | ## Introduction
6 |
7 | In this article, we will explore how to seamlessly integrate [Trust Wallet’s Smart Accounts](https://trustwallet.com/swift) with the [permissionless.js](https://docs.pimlico.io/permissionless) framework, a library managed by [Pimlico](https://www.pimlico.io/) to deploy and manage Smart Accounts based on the ERC-4337 standard. Using our [SDK](https://docs.pimlico.io/permissionless/how-to/accounts/use-trustwallet-account), you can create Trust Smart Accounts for your users and enhance your dApp with features such as gasless and batched transactions and much more.
8 |
9 | ## Benefits of a Trust Smart Account
10 |
11 | - Batch transactions
12 | - Sponsored Transactions via Paymaster
13 | - Passkey support
14 |
15 | ## Prerequisites
16 |
17 | Before you begin, ensure you have the following prerequisites:
18 |
19 | - Node.js and npm installed on your development environment.
20 | - An active account with Pimlico for API access.
21 | - Create your Pimlico account [here](https://dashboard.pimlico.io/sign-up?after_sign_up_url=https%3A%2F%2Fdashboard.pimlico.io%2Fonboarding&after_sign_in_url=https%3A%2F%2Fdashboard.pimlico.io%2F)
22 |
23 | ## Get Started
24 |
25 | Simplify the user journey and onboard easily while leveraging the advantages of ERC-4337.
26 |
27 | Here is how to add smart accounts creation and usage in your dApp in very few steps.
28 |
29 | In this article, we’ll walk you through the development of the below demo together:
30 |
31 | [Try the live Demo](https://monceeef.github.io/TrustSmartAccDemo/)
32 |
33 | The full codebase is available here: https://github.com/trustwallet/trustsmartaccdemo
34 |
35 | 
36 |
37 | ## For New Projects
38 |
39 | If you're creating a new project, follow these steps:
40 |
41 | ### Step 1: Setup Your Project
42 |
43 | First, set up a new React project.
44 |
45 | ```bash
46 | pnpm create wagmi
47 | pnpm install && pnpm run dev
48 | cd [PROJECT NAME]
49 | ```
50 |
51 | ### Step 2: Install Dependencies
52 |
53 | Install the necessary dependencies:
54 |
55 | ```bash
56 | pnpm add permissionless
57 | ```
58 |
59 | ### Step 3: Configure Tailwind CSS
60 |
61 | Set up Tailwind CSS for styling your application.
62 |
63 | Install Tailwind CSS:
64 |
65 | ```bash
66 | pnpm add tailwindcss
67 | npx tailwindcss init
68 | ```
69 |
70 | Update `tailwind.config.js`:
71 |
72 | ```jsx
73 | /** @type {import('tailwindcss').Config} */
74 | module.exports = {
75 | content: ["./src/**/*.{js,ts,jsx,tsx}"],
76 | theme: {
77 | extend: {
78 | colors: {
79 | // Add your colors
80 | primary: "...",
81 | },
82 | },
83 | },
84 | plugins: [],
85 | };
86 | ```
87 |
88 | Add Tailwind directives to your CSS file:
89 |
90 | ```css
91 | /* src/index.css */
92 | @tailwind base;
93 | @tailwind components;
94 | @tailwind utilities;
95 | ```
96 |
97 | ## For Existing Projects
98 |
99 | If you're integrating Trust Smart Accounts into an existing React project, start from the following steps:
100 |
101 | ### Step 4: Install Dependencies
102 |
103 | Navigate to your project directory and install the necessary dependencies:
104 |
105 | ```bash
106 | pnpm add wagmi permissionless viem
107 | ```
108 |
109 | ### Step 5: Connect Your Wallet
110 |
111 | Create a component to connect your wallet using the `wagmi` library.
112 |
113 | ```tsx
114 | import React from "react";
115 | import { Connector } from "wagmi";
116 |
117 | interface SignerConnectProps {
118 | connectors: readonly Connector[];
119 | connect: (params: { connector: Connector }) => void;
120 | }
121 |
122 | const SignerConnect: React.FC = ({
123 | connectors,
124 | connect,
125 | }) => {
126 | return (
127 |
352 | );
353 | };
354 |
355 | export default App;
356 | ```
357 |
358 | ## Conclusion
359 |
360 | By following this guide, you have successfully integrated Trust Smart Accounts into your project and enabled the creation of gasless NFTs. This setup leverages the power of account abstraction, giving a better experience to your users in order to interact with your dApps.
361 |
362 | ## Frequently Asked Questions (FAQs)
363 |
364 | Which networks are supported?
365 |
366 | - Ethereum
367 | - Arbitrum
368 | - Optimism
369 | - BNB
370 | - Polygon
371 | - Avalanche
372 | - opBNB
373 | - Base
374 |
375 | Testnets:
376 |
377 | - Sepolia
378 |
379 | Are there any costs associated to using Smart Accounts?
380 |
381 | - No. Only costs are related to paymaster.
382 |
383 | ### Security Information
384 |
385 | - **Audits:** Our smart contracts have undergone thorough audits by high-profile security firms, ensuring robust protection against vulnerabilities.
386 | - Certik https://github.com/trustwallet/barz-dev/blob/main/audit/Certik_Trustwallet-barz-Audit.pdf
387 | - Halborn https://github.com/trustwallet/barz-dev/blob/main/audit/Halborn_Trustwallet-barz-Audit.pdf
388 | - **Open Source:** Barz, our smart contract wallet solution, is open-sourced, promoting transparency and allowing the community to review and contribute to its development. https://trustwallet.com/blog/introducing-barz-smart-contract-wallet-solution
389 | - **Passkeys Support:** Trust Smart Accounts support passkeys for an additional layer of security, providing a more secure and user-friendly authentication mechanism.
390 | - **On-chain security monitoring service**: All Trust Wallet smart accounts are automatically monitored by our security monitoring infrastructure for free. All users will be able to maintain a highly secure state and could get immediately notified when a hack occurs. For detailed explanation, please reference this [doc](https://docs.pimlico.io/permissionless/how-to/accounts/use-trustwallet-account).
391 |
392 | ### Resources
393 |
394 | - [How to create and use a Trust smart account with permissionless.js](https://docs.pimlico.io/permissionless/how-to/accounts/use-trustwallet-account)
395 | - [Pimlico](https://www.pimlico.io/)
396 | - [Barz](https://github.com/trustwallet/barz-dev)
397 | - [Security Liability Statement](https://github.com/trustwallet/developer/blob/master/barz-smart-wallet/security-monitoring-system-liability-statement.md)
398 |
--------------------------------------------------------------------------------
/barz-smart-wallet/introducing-barz-trustwallet-smart-wallet-solution.md:
--------------------------------------------------------------------------------
1 | By [David Kim](https://twitter.com/0xDavidKim)
2 |
3 |
4 | Special thanks to [Luis Ocegueda](https://twitter.com/luis_oce) and [Artem Goryunov](https://twitter.com/ArtemGoryunov) for their feedback and contributions.
5 |
6 |
7 |
8 | This is the first of an article series on Barz.
9 |
10 | 1. [Introducing Barz: Trust Wallet’s Smart Wallet Solution](/introducing-barz-trustwallet-smart-wallet-solution)
11 | 2. [Cutting Diamonds: How to make Accounts Awesome](/cutting-diamonds-how-to-make-accounts-awesome)
12 | 3. For Builders By Builders: Introducing the Barz SDK
13 | 4. Multi-tier Module system. A secure foundation for open innovation
14 |
15 | In February 2024, we successfully launched [Swift Wallet](https://trustwallet.com/swift), an Account Abstraction Wallet to offer our users a more secure, smarter wallet. Swift Wallet introduced innovative features including Passkeys, gas payment with 200+ tokens, 1 step swap & bridging.
16 |
17 | Today, we are open sourcing our robust Smart Wallet solution “Barz”.
18 |
19 | Let’s dive into the details of how we got here!
20 |
21 | # Why we built Barz
22 |
23 | Trust Wallet, empowers more than 122 million Web3 users worldwide, understands the common issues and inconveniences users face when using wallets.
24 |
25 | Many users struggle with:
26 |
27 | - Improper management of their Mnemonic Phrases
28 | - Granting excessive privileges to a dApp for a single transaction.
29 | - Ability to create multiple automated tasks, e.g. schedule payments.
30 |
31 | While the issues and challenges with mnemonic seed phrases are well known, there are larger security and UX issues as more users are onboarded to Web3.
32 |
33 | To provide a solution to these challenges and limitations and ultimately drive more adoption of Web3, we decided to develop a Smart Wallet through Account Abstraction, which offers a fundamental solution overcoming these limitations - **Barz**.
34 |
35 | # Barz
36 |
37 | [Barz](https://github.com/trustwallet/barz) is an [ERC 4337](https://eips.ethereum.org/EIPS/eip-4337) compatible Smart Contract Wallet focused on a secure and smarter experience for users through modular, upgradeable, and secure designs.
38 |
39 | We aggregated the benefits from each wallet and pioneered new approaches to provide best-in-class service to users. Barz is also one of the first Passkeys based 4337 account that launched in production.
40 |
41 | Barz, at its core is a proxy contract that utilizes the [Diamond Proxy Pattern(EIP 2535)](https://eips.ethereum.org/EIPS/eip-2535) for a scalable and secure addition of use cases with high security threshold.
42 |
43 | Barz system currently has 12 fully built Facet implementations that can provide features of:
44 |
45 | - Account Recovery
46 | - Lock
47 | - Signature Migration
48 | - Guardian
49 | - Restrictions (Custom Rules for Transactions)
50 | - Diverse Validation Mechanisms
51 | - Secp256k1 - Default EVM Scheme (e.g., Mnemonic phrase)
52 | - Secp256r1 - Passkeys, Okta
53 | - Multi-sig
54 |
55 | 
56 |
57 | Let’s dive into Diamond Proxy pattern and how it works with ERC 4337. We’ll dive into the optimization points we made to Diamond for Barz in our next article.
58 |
59 | ## Diamond
60 |
61 | Diamond is a modular smart contract system enabled by a multi-faceted proxy stated in EIP-2535.
62 |
63 | A multi-faceted proxy is different from the conventional proxy pattern like [UUPS(Universal Upgradeable Proxy Standard)](https://eips.ethereum.org/EIPS/eip-1822) and TransparentUpgradeable where they have a single implementation to route the call to.
64 |
65 | 
66 |
67 | For example, a UUPS based proxy smart contract stores the single implementation contract address in the EIP-1967 based storage slot and performs upgrade by modifying the storage slot.
68 |
69 | ```solidity
70 | /**
71 | * @dev Storage slot with the address of the current implementation.
72 | * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
73 | */
74 | // solhint-disable-next-line private-vars-leading-underscore
75 | bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
76 | ```
77 |
78 | ```solidity
79 | /**
80 | * @dev Stores a new address in the ERC-1967 implementation slot.
81 | */
82 | function _setImplementation(address newImplementation) private {
83 | if (newImplementation.code.length == 0) {
84 | revert ERC1967InvalidImplementation(newImplementation);
85 | }
86 | StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
87 | }
88 | ```
89 |
90 | The proxy would then delegate all calls to the implementation contract through a fallback function that makes a `delegatecall` for all calls that comes with `msg.data`.
91 |
92 | ```solidity
93 | fallback() external payable virtual {
94 | assembly {
95 | // Copy msg.data. We take full control of memory in this inline assembly
96 | // block because it will not return to Solidity code. We overwrite the
97 | // Solidity scratch pad at memory position 0.
98 | calldatacopy(0, 0, calldatasize())
99 |
100 | // Call the implementation.
101 | // out and outsize are 0 because we don't know the size yet.
102 | let result := delegatecall(gas(), _implementation(), 0, calldatasize(), 0, 0)
103 |
104 | // Copy the returned data.
105 | returndatacopy(0, 0, returndatasize())
106 |
107 | switch result
108 | // delegatecall returns 0 on error.
109 | case 0 {
110 | revert(0, returndatasize())
111 | }
112 | default {
113 | return(0, returndatasize())
114 | }
115 | }
116 | }
117 | ```
118 |
119 | Unlike the UUPS pattern we saw above, Diamond Proxy has multiple “implementation” smart contracts, which are called Facets.
120 |
121 | But Diamond not only includes how Proxy and Facets interact but proposes a comprehensive approach to manage the following components of a proxy contract:
122 |
123 | - upgrade
124 | - view
125 | - storage
126 |
127 | Let’s dive into the details of how Diamond works under the hood.
128 |
129 | 
130 |
131 | Considering Diamond has multiple implementation contracts called Facets, Diamond requires a routing logic to route the function call to the correct corresponding facet.
132 |
133 | The core routing logic is implemented through a mapping of `bytes4` type which holds the function selector as the key and an `address` which holds the Facet contract address as value.
134 |
135 | ```solidity
136 | mapping (bytes4 => address) public selectorTofacet;
137 | ```
138 |
139 | When a function call is made to the contract and gets routed to the `fallback` function, the `fallback` function will fetch the function selector from the `calldata` through `msg.sig` and make a `delegatecall` to the facet if the corresponding facet exists and reverts otherwise.
140 |
141 | ```solidity
142 | // Find facet for function that is called and execute the
143 | // function if a facet is found and return any value.
144 | fallback() external payable {
145 | // get facet from function selector
146 | address facet = selectorTofacet[msg.sig];
147 | require(facet != address(0));
148 | // Execute external function from facet using delegatecall and return any value.
149 | assembly {
150 | // copy function selector and any arguments
151 | calldatacopy(0, 0, calldatasize())
152 | // execute function call using the facet
153 | let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
154 | // get any return value
155 | returndatacopy(0, 0, returndatasize())
156 | // return any return value or error back to the caller
157 | switch result
158 | case 0 {revert(0, returndatasize())}
159 | default {return (0, returndatasize())}
160 | }
161 | }
162 | ```
163 |
164 | This multi-faceted proxy pattern provides a benefit of modular implementation designs by enabling each facet to be grouped into a specific domain of functionality.
165 |
166 | For example, Account Facet could hold account related logic like `execute()`, `executeBatch()` while Token Receiver Facet could hold logic like `onERC721Received()`, `tokensReceived()`.
167 |
168 | For a better separation of Facet logic and storage, the Diamond standard also provides an approach of `DiamondStorage` mainly for a specific Facet’s storage and `AppStorage` which is more suitable for shared storage between Facets.
169 |
170 | `DiamondStorage` relies on a Solidity struct that contains set variables for the Facet and stores it in the designated namespace storage slot. It is particularly good for isolating or compartmenting state variables to specific facets or functionality.
171 |
172 | ```solidity
173 | /* Example of Diamond Storage */
174 | struct Secp256k1VerificationStorage {
175 | address signer;
176 | }
177 |
178 | bytes32 constant K1_STORAGE_POSITION =
179 | keccak256(
180 | "v0.trustwallet.diamond.storage.Secp256k1VerificationStorage"
181 | );
182 |
183 | function k1Storage()
184 | internal
185 | pure
186 | returns (Secp256k1VerificationStorage storage ds)
187 | {
188 | bytes32 storagePosition = K1_STORAGE_POSITION;
189 | assembly {
190 | ds.slot := storagePosition
191 | }
192 | }
193 | ```
194 |
195 | As the storage slot will be intentionally different to prevent storage collision, this provides a scalable approach of utilizing storage with Multiple Facets compared to the approach of using the default EVM Storage Slot.
196 |
197 | This concept is also utilized in the Barz implementation to detach the storage between facets.
198 |
199 | 
200 |
201 | In contrast, `App Storage` is another type of storage pattern that is more suitable for storage variables that are shared among facets.
202 |
203 | App Storage also uses the Struct to define the storage, however, uses the storage slot `0` unlike the Diamond Storage which used a custom storage slot.
204 |
205 | For example, Barz stores the address of the `EntryPoint` contract and `signerMigration` flag which is shared across multiple facets.
206 |
207 | ```solidity
208 | struct AppStorage {
209 | mapping(uint256 => InitializersStorage) initStorage;
210 | uint8 signerMigration;
211 | bytes4 validateOwnerSignatureSelector;
212 | IEntryPoint entryPoint;
213 | IFacetRegistry facetRegistry;
214 | mapping(uint256 => Lock) locks;
215 | }
216 |
217 | function appStorage() internal pure returns (AppStorage storage ds) {
218 | assembly {
219 | ds.slot := 0
220 | }
221 | }
222 | ```
223 |
224 | Let’s have a look on how Diamonds perform upgrades.
225 |
226 | To register a new facet or remove/replace them from Diamond, the contract should comply with the standard interface of `diamondCut()`.
227 |
228 | ```solidity
229 | interface IDiamondCut {
230 |
231 | enum FacetCutAction {Add, Replace, Remove}
232 | // Add=0, Replace=1, Remove=2
233 |
234 | struct FacetCut {
235 | address facetAddress;
236 | FacetCutAction action;
237 | bytes4[] functionSelectors;
238 | }
239 |
240 | function diamondCut(
241 | FacetCut[] calldata _diamondCut,
242 | address _init,
243 | bytes calldata _calldata
244 | ) external;
245 |
246 | }
247 | ```
248 |
249 | `diamondCut()` normally performs 4 main steps
250 |
251 | 1. Ownership Check
252 | 1. This is crucial considering that a malicious Diamond can overwrite storage or perform malicious activities
253 | 2. Facet Check
254 | 1. Check if the Facet is indeed a contract, check if the selector is okay to be added.
255 | Diamond does not allow multiple facets from registering an identical function selector.
256 | 3. Add/Remove/Replace Facet’s function selector and its corresponding actions
257 | 4. Perform Diamond Init
258 | 1. Diamond Init is an approach for one-time initialization for Diamonds similar to constructor.
259 |
260 | Once the `diamondCut()` is called to the Diamond, the Diamond should store the mapping of `functionSelectors` and the `Facet address` to route the call from the `fallback` function.
261 |
262 | Within the `diamondCut()` execution, Diamond also performs a process called `Diamond Init` for initializing/uninitializing state variables. This is useful during the installation and uninstallation of Facets to clean up storage.
263 |
264 | This is enabled by making a `delegatecall` to the `_init` address with the provided `calldata` from `diamondCut()`.
265 |
266 | For example, below is an implementation of Diamond Init contract to add ERC-165 based `supportedInterfaces()` check.
267 |
268 | ```solidity
269 | // You can add parameters to this function in order to pass in
270 | // data to set your own state variables
271 | function init() external {
272 | // adding ERC165 data
273 | LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
274 | ds.supportedInterfaces[type(IERC165).interfaceId] = true;
275 | ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true;
276 | ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true;
277 | ds.supportedInterfaces[type(IERC173).interfaceId] = true;
278 | }
279 | ```
280 |
281 | Now as we’ve checked how storage and upgrade work for Diamonds, let’s check the approaches to view the status of the Diamond - `DiamondLoupe`.
282 |
283 | `DiamondLoupe` is a standardized interface to look into Diamond. This allows external components and entities to check which Facet and Function Selectors are registered to the `Diamond`.
284 |
285 | ```solidity
286 | // A loupe is a small magnifying glass used to look at diamonds.
287 | // These functions look at diamonds
288 | interface IDiamondLoupe {
289 | struct Facet {
290 | address facetAddress;
291 | bytes4[] functionSelectors;
292 | }
293 |
294 | /// @notice Gets all facet addresses and their four byte function selectors.
295 | /// @return facets_ Facet
296 | function facets() external view returns (Facet[] memory facets_);
297 |
298 | /// @notice Gets all the function selectors supported by a specific facet.
299 | /// @param _facet The facet address.
300 | /// @return facetFunctionSelectors_
301 | function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
302 |
303 | /// @notice Get all the facet addresses used by a diamond.
304 | /// @return facetAddresses_
305 | function facetAddresses() external view returns (address[] memory facetAddresses_);
306 |
307 | /// @notice Gets the facet that supports the given selector.
308 | /// @dev If facet is not found return address(0).
309 | /// @param _functionSelector The function selector.
310 | /// @return facetAddress_ The facet address.
311 | function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
312 | }
313 | ```
314 |
315 | The method `facets()` returns the whole information about its Facet mappings.
316 |
317 | `facetFunctionSelectors()` returns the list of function selectors corresponding to the given facet.
318 |
319 | `facetAddresses()` returns the list of all facets registered to the Diamond.
320 |
321 | `facetAddress()` returns the facet address of the corresponding function selector.
322 |
323 | By complying with this standard interface, Diamond can transparently show its state to external entities while being compatible with tools like [louper.dev](http://louper.dev).
324 |
325 | For example, this is an overview of Barz seen from [louper.dev](http://louper.dev) tool:
326 |
327 | [Overview of Barz from Louper - The Ethereum Diamond Inspector](https://louper.dev/diamond/0xbD741C9A6c3C197F863F0657A15D2E9070534BE3?network=polygon)
328 |
329 | 
330 |
331 | ## ERC 4337 Account with Diamond
332 |
333 | From an ERC 4337 account contract perspective, there are 2 main aspects to handle:
334 |
335 | - Validation
336 | - Execution
337 |
338 | For Validation, the account should implement the `IAccount` interface specified in the ERC 4337 standard.
339 |
340 | ```solidity
341 | interface IAccount {
342 | function validateUserOp
343 | (UserOperation calldata userOp, bytes32 userOpHash, address aggregator, uint256 missingAccountFunds)
344 | external returns (uint256 sigTimeRange);
345 | }
346 | ```
347 |
348 | For execution, it can implement its own execution methods like `execute()` and `executeBatch()` .
349 |
350 | An example of Barz handling the 4337 logic in a modular approach through Diamond can be seen from the separation of Account Facet and Verification Facet during initialization and execution.
351 |
352 | In the `BarzFactory` code below, users can create an account with any verification facet with their preferred signature scheme by providing the address in the `_verificationFacet` and the corresponding `_owner` for initialization.
353 |
354 | ```solidity
355 | /**
356 | * @notice Creates the Barz with a single call. It creates the Barz contract with the given verification facet
357 | * @param _verificationFacet Address of verification facet used for creating the barz account
358 | * @param _owner Public Key of the owner to initialize barz account
359 | * @param _salt Salt used for deploying barz with create2
360 | * @return barz Instance of Barz contract deployed with the given parameters
361 | */
362 | function createAccount(
363 | address _verificationFacet,
364 | bytes calldata _owner,
365 | uint256 _salt
366 | ) external override returns (Barz barz) {
367 | address addr = getAddress(_verificationFacet, _owner, _salt);
368 | uint codeSize = addr.code.length;
369 | if (codeSize > 0) {
370 | return Barz(payable(addr));
371 | }
372 | barz = new Barz{salt: bytes32(_salt)}(
373 | accountFacet,
374 | _verificationFacet,
375 | entryPoint,
376 | facetRegistry,
377 | defaultFallback,
378 | _owner
379 | );
380 | emit BarzDeployed(address(barz));
381 | }
382 | ```
383 |
384 | Signer will be initialized using the `verificationFacet` provided in the `createAccount()` function.
385 |
386 | This allows `BarzFactory` and `AccountFacet`, together with all the remaining Facets to be ***agnostic*** to the signature validation mechanism and focus on its core logic.
387 |
388 | 
389 |
390 | This can also be applied during the validation of UserOperation e.g., `validateUserOp()`.
391 |
392 | With the separation of Account and Verification logic through modular designs, it enables the account to dynamically switch the signer and signature scheme depending on user’s needs and wants.
393 |
394 | It also helps the codebase to be clean and focus on its domain logic which helps reduce potential code bugs and unwanted complexity coming from interdependencies between logic.
395 |
396 | ```solidity
397 | function _validateSignature(
398 | UserOperation calldata _userOp,
399 | bytes32 _userOpHash
400 | ) internal override returns (uint256 validationData) {
401 | // Get Facet with Function Selector
402 | address facet = LibLoupe.facetAddress(s.validateOwnerSignatureSelector);
403 | if (facet == address(0))
404 | revert AccountFacet__NonExistentVerificationFacet();
405 |
406 | // Make function call to VerificationFacet
407 | bytes memory validateCall = abi.encodeWithSelector(
408 | s.validateOwnerSignatureSelector,
409 | _userOp,
410 | _userOpHash
411 | );
412 | (bool success, bytes memory result) = facet.delegatecall(validateCall);
413 | if (!success) revert AccountFacet__CallNotSuccessful();
414 | validationData = uint256(bytes32(result));
415 | if (validationData == 0) emit VerificationSuccess(_userOpHash);
416 | else emit VerificationFailure(_userOpHash);
417 | }
418 | ```
419 |
420 | `Account Facet` delegates the validation of UserOperation signature to the `Verification Facet` and only propagates the result from the `Verification Facet`.
421 |
422 | 
423 |
424 | # Conclusion
425 |
426 | The Barz Smart Wallet Architecture utilizing Diamond allows modular and flexible development of a wide array of use cases. It allows each Facets to focus on its specific business logic while providing the flexibility to easily switch each component and maintain interoperability.
427 |
428 | In our next article, we’ll share the optimizations we did to make Diamonds much better for building smart wallets.
429 |
430 | Stay tuned for our next article series and releases of powerful use cases of smart wallet built on [Barz](https://github.com/trustwallet/barz).
431 |
432 | *If you have questions or want to use Trust Wallet’s AA SDK in your service or any ideas for collaboration, reach out in smartwallet channel in our [Trust Wallet Discord](https://discord.gg/trustwallet)*
--------------------------------------------------------------------------------
/barz-smart-wallet/security-monitoring-system-liability-statement.md:
--------------------------------------------------------------------------------
1 | # Security Monitoring System Liability Statement
2 |
3 | 1. Trust Wallet provides a security monitoring system for all smart contract wallets using the `BarzFactory` at address `0x729c310186a57833f622630a16d13f710b83272a`.
4 | This includes smart contract wallets deployed through SDKs(e.g., permissionless) and wallets deployed within the Trust Wallet SWIFT (in-app).
5 | 2. Trust Wallet does not have any liability or responsibility for any type of incidents or exploits that may happen by using Barz or AA SDK provided by Trust Wallet.
6 | Full liability is on the project that uses Barz and AA SDK for their service.
7 | 3. The security monitoring system is an open tool provided by Trust Wallet for projects to help with their security, but we explicitly state that Trust Wallet does not have any liability for incidents or financial losses that may incur.
8 |
9 | Use it at your own risk.
10 |
--------------------------------------------------------------------------------
/dapps/debugging.md:
--------------------------------------------------------------------------------
1 | # How to debug your DApp on Trust Wallet
2 |
3 | Make sure you have the latest app version, check if there is any new update on Google Play or App Store
4 |
5 | ## 1. Install a mobile web console
6 |
7 | we use [vConsole](https://github.com/Tencent/vConsole) on our test dapp: https://js-eth-sign.surge.sh/, click the bottom green `vConsole` button to see logs.
8 |
9 |
10 |
11 | ## 2. [Android] Chrome Rmote debugging
12 |
13 | Download Trust Wallet apk from [trustwallet.com](https://trustwallet.com) and drag it to your emulator. (app installed from Google Play won't work)
14 |
15 | Open the dapp in Trust Wallet (1inch.io as example)
16 |
17 |
18 |
19 | Visit `chrome://inspect/#devices` or `edge://inspect/#devices` to inspect the web console
20 |
21 | 
22 | 
23 |
24 | ## 3. [iOS] Safari WebView debugging
25 |
26 | iOS doesn't support debugging app built for distribution, you can try to build this iOS demo in [trust-web3-provider](https://github.com/trustwallet/trust-web3-provider) and check if it can connect to your DApp or not, please follow this [guide](https://webkit.org/web-inspector/enabling-web-inspector/) to inspect.
27 |
28 | ## Contact us
29 |
30 | If above doesn't help, please create an issue on [trust-web3-provider](https://github.com/trustwallet/trust-web3-provider) and elaborate your question as detail as possible.
31 |
32 | 1. What's your app version and OS version?
33 | 2. Do you see any js error?
34 | 3. How to reproduce? please record a video if possible
35 | 4. what's the url of your dapp?
36 |
--------------------------------------------------------------------------------
/dapps/listing-guide.md:
--------------------------------------------------------------------------------
1 | # A Complete Guide to Listing your dApp with Trust Wallet
2 |
3 | Joining the Trust Wallet ecosystem with an already established base of users, projects, and communities is a great opportunity for your dApp project to leapfrog its growth. Before you can be listed alongside the other top dApps partnered with Trust Wallet, there is a documented process that needs to be carefully followed and completed.
4 |
5 | Trust Wallet is proud of the high standards of quality required for listed dApps, where the user and their experience are the key areas of focus. The app is one of the most popular wallets available for easy access to digital assets and dApps in one place.
6 |
7 | By improving the functionality of your project and its overall optimization, you allow users already familiar with the Trust Wallet space the best chance of using your dApp. Taking advantage of the vibrant [community](https://twitter.com/trustwalletapp) is a logical step to take. Marketing efforts also help, so get in touch with the Trust Wallet team via [Trust Wallet Community](https://community.trustwallet.com/) to explore more promotional opportunities.
8 |
9 | Missing out on just any one part of the optimization and application process will ultimately lead to an unsuccessful application. The journey involves rounds of:
10 |
11 | 1. [Optimization](dApps/mobile-optimize.md)
12 | 2. [Upload Assets via Github Pull Request (involves nominal fee)](#technical-requirements-and-preperation)
13 | 3. [Application Form](https://trustwallet.com/submit-dApp)
14 |
15 | The whole process can be divided into these key stages, along with some recommended marketing activities to help give your project a better chance of success.
16 |
17 | - [ ] Optimization of your dApp for the Trust Wallet browser
18 | - [ ] Optimization of your dApp for desktop users
19 | - [ ] Uploading of required logo assets
20 | - [ ] Application to join the Trust Wallet dApp listing
21 | - [ ] Hosting a Trust Wallet AMA session
22 | - [ ] Creating a Barn of Trust staking vault
23 |
24 | Only by following closely the clearly defined instructions and recommendations will your dApp be able to join the list after careful scrutiny from the Trust Wallet team.
25 |
26 | ### Technical Requirements and Preparation
27 |
28 | Optimizing your application will require checking off a series of key areas noted in the following optimization sections. Some technical preparation will however be required whenever assets are added to the Trust Wallet GitHub repo.
29 |
30 | Therefore, it is required that you have a [GitHub](https://github.com) account to interact with the [Assets repo](https://github.com/trustwallet/assets) and submit your dApp logo for listing. Before uploading any image files, you must make sure they meet the following requirements:
31 |
32 | - File Extension: `png`
33 | - Uppercase `PNG` is considered invalid
34 | - File Name:logo.png
35 | - Size: 256px by 256px
36 | - Background: Avoid transparency. White is preferred to fit in with app white/dark theme designs.
37 | - File size: maximum 100kB. Tip: optimize your image size using a simple drag-and-drop online service such as tinypng. Your logo’s file name must also meet the following criteria: ..png
38 | - For example: https://app.compound.finance/ => app.compound.finance.png
39 | https://kyberswap.com/ => kyberswap.com.png
40 |
41 | Some basic information is also required on your dApp project as part of the submission process. This includes:
42 |
43 | - A short and clear explanation of your dApp functionality
44 | - Your Telegram channel
45 | - A description of your dApp for listing
46 | - Your dApp name for the listing
47 | - The URL of your dApp for listing
48 |
49 | ### Pull Request Fee
50 |
51 | Pull requests made to Trust Wall repositories have an associated fee to pay in either TWT or BNB. Due to the number of tokens, coins, and projects supported by Trust Wallet, a large number of requests are made that must be processed.
52 |
53 | Contributing a fee filters spam requests and ensures that there is more time to handle genuine submissions.
54 |
55 | More details are available on the [pull request fee](../assets/pr-fee.md) that explains how this fits in with Trust Wallet’s open-source ethos.
56 |
57 | **NOTE:** Paying the fee does not guarantee that your asset will be listed in the repository.
58 |
59 | ### Applying for the Trust Wallet dApp Listing
60 |
61 | Adding your dApp to the official Trust Wallet listing provides users with a guarantee of the quality and service provided by your dApp. Not every project that is submitted to the listing is approved. _Upon review, a member of the Trust Wallet team will reach out with additional information or follow up questions if necessary_.
62 |
63 | Trust Wallet is proud of the standards set in place to ensure that only the best projects are presented. Once you’ve applied, a member of the Trust Wallet team will reach out should we feel your app is a good candidate based on UX, mobile optimization, responsiveness, value proposition relative to other apps, etc.
64 |
65 | The aim of the Trust Wallet dApp Directory is twofold:
66 |
67 | 1. It empowers users to discover high-quality dApps within Trust Wallet.
68 | 2. It allows developers to showcase their work to millions of users as part of a developed and supported ecosystem.
69 |
70 | #### Curation Guidelines
71 |
72 | dApp listing submissions are considered on a case-by-case basis. While there isn’t a strict formula that dictates which apps we decide to list, the safety and experience of our users are of the utmost importance to us. For that reason, the dApp Directory is curated with the following set of guidelines:
73 |
74 | - We believe the dApp ecosystem should be open and allow for the expression of diverse ideas and opinions. dApp submissions with content or behavior that fails to meet a “common sense” bar for respecting different ideas or users will be rejected.
75 | - Attempts to misrepresent or otherwise deceive the listing and review process will result in your dApp being rejected or delisted from the directory.
76 | - Stronger consideration will be given to dApps that demonstrate a unique value proposition relative to other existing/popular apps
77 | - Good design is a critical component to increasing the accessibility of crypto and Defi. We look for dApps that scale gracefully across screen sizes and devices, and appropriate management of complex user flows through thoughtful UI
78 |
79 | Before submitting your dApp and filling out the submission form, you should ensure that your dApp is fully compliant with our submission criteria.
80 |
81 | You are responsible for the use of ad networks, analytics services, and third-party SDKs used within your dApp, so review and choose them carefully.
82 |
83 | #### Safety and Security
84 |
85 | Trust Wallet users require confidence that using dApps won’t jeopardize their funds, personal information, or device security.
86 |
87 | Additionally, dApps that contain malware are strictly prohibited. This includes any functionality that seeks to gain or provide unauthorized access or control to a user’s device.
88 |
89 | #### Objectionable and misleading content
90 |
91 | Trust Wallet will reject any dApp submitted for listing that contains or promotes spam, violence, pornography, fake news, or other inappropriate content not suitable for a decentralized application.
92 |
93 | #### Legal & Business
94 |
95 | Ensure that your dApp is compliant with all relevant laws and regulations where you plan on making it available. dApps that encourage or solicit criminal or reckless behavior will not be tolerated and may result in notifying law enforcement.
96 |
97 | ### Support and Questions
98 |
99 | Should you at any point find yourself with questions about any of the processes laid out in this guide, then don’t hesitate to get in touch at the [Trust Wallet Community](https://community.trustwallet.com/).
100 |
101 | It should be noted that this guide contains the minimum needed to begin the submission process and is not exhaustive. There may be other qualities that are considered for listing, but completing the process of optimization and following our guidelines will get you the best chance of success.
102 |
--------------------------------------------------------------------------------
/dapps/mobile-optimize.md:
--------------------------------------------------------------------------------
1 | # Optimizing Your Dapp for the Trust Wallet
2 |
3 | Users of the Trust Wallet app enjoy the ease and experience of accessing their wallets, assets, and DApps all at the same time. This is made possible through the Trust Wallet DApp browser and WalletConnect. Without needing to swap between apps, users can trade and browse in a fluid, uninterrupted experience.
4 |
5 | Optimizing your DApp for the Trust Wallet is an integral part of making sure your project is up to scratch for listing. We recommend that you take a considerable amount of time to ensure fully that your app has at least the basic levels of optimization laid out below.
6 |
7 | ## Preparing your DApp for Trust Wallet
8 |
9 | The Trust Wallet App currently offers the following functionality:
10 |
11 | - A Web3 browser for interacting with decentralized applications
12 | - A range of tools to provide a seamless connection between the DApps and the user on the Ethereum, Solana, Cosmos, BNB Smart Chain, Polygon, Osmosis, EVMOS, Aptos and many more EVM and Cosmos compatible networks.
13 | - A fully optimized, integrated interface experience for mobile users
14 |
15 | There are simple steps for blockchain developers to implement to take full advantage of these key features. Most are basic tips but none can be missed out.
16 |
17 | ## Metamask/Phantom/Keplr/Petra is a good place to start
18 |
19 | Familiarity with MetaMask interaction for Ethereum DApps, Phantom for Solana, Keplr for Cosmos or Petra for Aptos puts you off to a good start in terms of optimizing or developing a DApps for Trust Wallet. The web3 development process is the same when using MetaMask/Phantom/Keplr/Petra as a dev tool. It’s our recommended choice for DApp development and gives you a quick, golden rule to use: if it works well with MetaMask, Phantom, Keplr or Petra it works well with Trust Wallet.
20 |
21 | ## Create a UI that Is mobile-friendly
22 |
23 | It can’t be forgotten that Trust Wallet is accessed by two groups of people: those using the app on [Android](https://trustwallet.com/referral) and those using an iOS device. Your project must be developed to have a mobile-friendly UI as the Trust Wallet inbuilt browser is the primary point of access for the majority of our users.
24 |
25 | iOS users require the latest build from Apple App Store. UI/UX design needs to also be considered in your mobile design to provide the best in-wallet experience.
26 |
27 | ## Master Web3
28 |
29 | All Ethereum DApps should be [EIP1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md) (Ethereum Improvement Protocol 1193) compatible. This allows for a high degree of wallet interoperability when exposing an API through JavaScript objects in the Ethereum DApp.
30 |
31 | If you have decided upon using MetaMask as your dev tool, do not forget their [Provider Migration Guide](https://docs.metamask.io/guide/provider-migration.html). This will seriously affect the degree of compatibility between your DApp and the Trust Wallet browser without proper planning.
32 |
33 | For Solana integration the best way would be to use the official [Wallet Adapter](https://github.com/solana-labs/wallet-adapter) which supports Trust Wallet and include it as the connection point to your DApp.
34 |
35 | For Cosmos you can refer to the official [Keplr guide](https://docs.keplr.app/api/), just make sure to use `window.trustwallet.cosmos` instead of `window.keplr`.
36 |
37 | For Aptos please follow the official [Petra guide](https://petra.app/docs/sending-a-transaction). `window.trustwallet.aptos` is also preferred over `window.aptos`, although both will work.
38 |
39 | Consider including an explicit Trust Wallet icon or button in your DApp. This will help Trust Wallet users connect to your DApp for the first time.
40 |
41 | Recommended steps to improve the user experience when a user clicks or taps the Trust Wallet icon:
42 |
43 | 1. Check [How to Identify Trust Provider](https://github.com/trustwallet/trust-web3-provider#how-to-identify-trust-provider) guide.
44 | 2. Verify that the DApp is open in desktop browsers or no `window.trustwallet.(ethereum/solana/cosmos/aptos)` -> Display the WalletConnect pairing popup
45 | 3. Verify that the DApp is open in the Trust Wallet DApp browser -> Access the `window.trustwallet.(ethereum/solana/cosmos/aptos)` directly.
46 |
47 | ## Test your DApp on both iOS and Android
48 |
49 | Trust Wallet users access their wallets on both Android and iOS devices, so your app must be thoroughly tested for both operating systems. Issues may occur on one operating system but not on the other.
50 |
51 | This is one of the most important areas to optimize for but is often brushed over. Just open up your DApp with the Trust Wallet browser on both an iOS and Android device, then test the DApps functionalities such as sending or depositing tokens.
52 |
53 | ## Flag issues in the trust-web3-provider repo
54 |
55 | It may be that you have issues with the TrustWeb3Provider while optimizing your DApp. The web3 javascript wrapper provider allows you to directly file any issues through [GitHub](https://github.com/trustwallet/trust-web3-provider). The Trust Wallet team will then provide support for any queries you have in due time.
56 |
57 | ## Implement deep links
58 |
59 | There is no native support for Web3 in iOS or Android mobile browsers. Your DApp’s links must be [deep links](deeplinking/deeplinking.md) that combine numerous steps into one simple, easy click. Without them, users will need to follow tedious and long chains of links that greatly impact the user experience.
60 |
61 | ## References
62 |
63 | Web3 is incredibly powerful for developing DApps and outlining their interactions with Ethereum or Solana nodes. The most up-to-date Web3 open-source [Ethereum JavaScript library](https://github.com/ethers-io/ethers.js/) or [Solana JavaScript library](https://solana-labs.github.io/solana-web3.js/modules.html) needs to be implemented for your DApp to be well optimized for the Trust Wallet browser.
64 |
--------------------------------------------------------------------------------
/develop-for-trust/browser-extension/browser-extension.md:
--------------------------------------------------------------------------------
1 | # Browser Extension
2 |
3 | Interacting with a web3 wallet is typical for all websites that want to communicate with a blockchain. A web3 wallet is an application that allows users to send and receive funds and execute actions like swapping tokens in decentralized exchanges or buying NFTs on various marketplaces. Many wallets exist for different platforms (mobile/desktop/browser extension). Most browser extension wallets support EVM-compatible blockchains such as Ethereum, Binance Smart Chain, Avalanche, etc. In contrast, others support only specific blockchains like Solana, Aptos, etc.
4 |
5 | > Trust Wallet Browser Extension currently supports only Ethereum & EVM chains, but support for more networks is in progress.
6 |
--------------------------------------------------------------------------------
/develop-for-trust/deeplinking/deeplinking.md:
--------------------------------------------------------------------------------
1 | # Deeplinking
2 |
3 | All deeplink routes can be used with either `https://link.trustwallet.com` or `trust://`.
4 |
5 | The `https://link.trustwallet.com` domain will route the user to a download landing page where the user can download the app for iOS, Android, or web extension. If the user already has the app installed, they will get a pop-up deeplinking them to the actual route page in the app.
6 |
7 | The `trust://` URI will directly deeplink route the user to the corresponding in-app page and should be used in campaigns where it is known that all users clicking on the link already have the Trust Wallet app installed.
8 |
9 | ## DApp Browser
10 |
11 | Open dapp browser with a specific url and network
12 |
13 | - `coin` slip44 index
14 | - `url` website url
15 |
16 | `https://link.trustwallet.com/open_url?coin_id=60&url=https://compound.finance`
17 |
18 | ## Assets
19 |
20 | ### Open coin
21 |
22 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
23 |
24 | `https://link.trustwallet.com/open_coin?asset=c60`
25 |
26 | ### Add asset
27 |
28 | Asset will be added to local storage and will show up on the wallet screen.
29 |
30 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
31 |
32 | `https://link.trustwallet.com/add_asset?asset=c60_t0x514910771af9ca656af840dff83e8264ecf986ca`
33 |
34 | ## Payment
35 |
36 | ### Redeem Code:
37 |
38 | - `code` unique code
39 | - `provider` provider url
40 |
41 | `https://link.trustwallet.com/redeem?code=abc123`
42 |
43 | ### Send Payment:
44 |
45 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
46 | - `address` Recipient address
47 | - `amount` Optional. Payment amount
48 | - `memo` Optional. Memo
49 | - `data` Optional. Data
50 |
51 | `https://link.trustwallet.com/send?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F&address=0x650b5e446edabad7eba7fa7bb2f6119b2630bfbb&amount=1&memo=test`
52 |
53 | ### Referral:
54 |
55 | `https://link.trustwallet.com/referral`
56 |
57 | ## Staking
58 |
59 | ### Stake details:
60 |
61 | - `coin` slip44 index
62 |
63 | `https://link.trustwallet.com/stake?coin=118`
64 |
65 | ### Stake / Delegate:
66 |
67 | - `coin` slip44 index
68 | - `id` validator / delegator to be selected. Optional
69 |
70 | `https://link.trustwallet.com/stake_delegate?coin=118&id=cosmosvaloper156gqf9837u7d4c4678yt3rl4ls9c5vuursrrzf`
71 |
72 | ### Unstake / Undelegate:
73 |
74 | - `coin` slip44 index
75 |
76 | `https://link.trustwallet.com/stake_undelegate?coin=118`
77 |
78 | ### Claim Rewards:
79 |
80 | - `coin` slip44 index
81 |
82 | `https://link.trustwallet.com/stake_claim_rewards?coin=118`
83 |
84 | ## Exchange
85 |
86 | ### Open Swap:
87 |
88 | - `from` asset in [UAI format](/assets/universal_asset_id.md)
89 | - `to` asset in [UAI format](/assets/universal_asset_id.md)
90 |
91 | `https://link.trustwallet.com/swap?from=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F&to=c60`
92 |
93 | ### Open Buy Crypto
94 |
95 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
96 | - `provider` Specifies the fiat ramp provider (e.g., moonpay, mercuryo, ramp). Optional.
97 | - `payment_method` Specifies the payment method (e.g., credit_card, bank_transfer, apple_pay, google_pay, digital_wallet). Optional.
98 | - `sub_payment_method` Specifies the sub payment method (e.g., paypal, skrill, blik). Optional.
99 | - `fiat_currency` Specifies the currency for the amount (e.g., USD, GBP). Optional.
100 | - `fiat_quantity` Specifies the default quantity of the asset to buy (e.g., 3, 0.25). Optional.
101 |
102 | `https://link.trustwallet.com/buy?asset=c60&provider=moonpay&payment_method=digital_wallet&sub_payment_method=paypal&fiat_currency=USD&fiat_quantity=300`
103 |
104 | ### Open Sell Crypto
105 |
106 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
107 |
108 | `https://link.trustwallet.com/sell?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F`
109 |
110 | ### Open Market Info
111 |
112 | - `asset` asset in [UAI format](/assets/universal_asset_id.md)
113 |
114 | `https://link.trustwallet.com/market?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F`
115 |
116 | ### Open Notifications
117 |
118 | `https://link.trustwallet.com/notifications`
119 |
120 | ### Open Price alerts
121 |
122 | `https://link.trustwallet.com/alerts`
123 |
124 | ## WalletConnect
125 |
126 | ### Connect to a WalletConnect session
127 |
128 | `https://link.trustwallet.com/wc?uri=wc%3Aca1fccc0-f4d1-46c2-90b7-c07fce1c0cae%401%3Fbridge%3Dhttps%253A%252F%252Fbridge.walletconnect.org%26key%3Da413d90751839c7628873557c718fd73fcedc5e8e8c07cfecaefc0d3a178b1d8`
129 |
130 | ## NFTs
131 |
132 | Open NFTs tab.
133 |
134 | `https://link.trustwallet.com/nfts`
135 |
136 | ## Quest
137 |
138 | Open the quest page.
139 |
140 | `https://link.trustwallet.com/quest`
141 |
142 | ## Launchpool
143 |
144 | Open the Launchpool page.
145 |
146 | `https://link.trustwallet.com/launchpool`
147 |
148 | ## Hot Tokens
149 |
150 | Open the Hot Tokens tab on the Swap page.
151 |
152 | `https://link.trustwallet.com/hot_tokens`
153 |
154 | ### Open Hot category and all networks
155 |
156 | - `category_id` category identifier
157 |
158 | `https://link.trustwallet.com/hot_tokens?category_id=hot`
159 |
160 | ### Open Hot category and specific network
161 |
162 | - `category_id` category identifier
163 | - `network` network identifier (slip44 index)
164 |
165 | `https://link.trustwallet.com/hot_tokens?category_id=hot&network=c0`
166 |
167 | ## Settings
168 |
169 | ### Open the notification settings page
170 |
171 | `https://link.trustwallet.com/notification_settings`
172 |
--------------------------------------------------------------------------------
/develop-for-trust/develop-for-trust.md:
--------------------------------------------------------------------------------
1 | # Developing for Trust Wallet platform
2 |
3 | If you are new to the web3 space, you may have many questions: How do we interact with smart contracts and web3 wallets, what is “the Provider”, and what libraries do we use? A certain amount of frustration comes with it, even for developers with many years of experience in web development that just transitioned into this space. However, you won’t have to relearn anything; you just have to understand the building blocks. This is an introduction dedicated to you and to every aspiring developer who wants to explore this fascinating space.
4 |
5 | **Prerequisites**
6 |
7 | This guide will walk you through the basic concepts and examples to get you started developing using web3 technologies. We assume you have prior experience with the JavaScript ecosystem, although the examples presented do not relate to any specific front-end frameworks or libraries.
8 |
--------------------------------------------------------------------------------
/develop-for-trust/mobile/mobile.md:
--------------------------------------------------------------------------------
1 | # Mobile (WalletConnect)
2 |
3 | [WalletConnect](https://walletconnect.org/) is an open source protocol for connecting dApps to mobile wallets with QR code scanning or deep linking, basically it's a websocket JSON-RPC channel.
4 |
5 | There are two common ways to integrate: Standalone Client and Web3Model (Web3 Provider)
6 |
7 | ## Standalone Client
8 |
9 | Trust extends WalletConnect 1.x with aditional JSON-RPC methods to support multi-chain **dApps**. Currently, you can get all accounts and sign transactions [for any blockchain](https://github.com/trustwallet/wallet-core/blob/master/docs/registry.md) implements `signJSON` method in wallet core.
10 |
11 | **Supported Coins**
12 |
13 | - Binance Chain
14 | - Ethereum and forks
15 | - Cosmos, Kava and other sdk based chains
16 | - Tezos
17 | - Nano
18 | - Filecoin
19 | - Harmony
20 | - Solana
21 | - Zilliqa
22 |
23 | ### Installation
24 |
25 | ```bash
26 | npm install --save @walletconnect/client @walletconnect/qrcode-modal
27 | ```
28 |
29 | ### Initiate Connection
30 |
31 | Before you can sign transactions, you have to initiate a connection to a WalletConnect bridge server, and handle all possible states:
32 |
33 | ```javascript
34 | import WalletConnect from "@walletconnect/client";
35 | import QRCodeModal from "@walletconnect/qrcode-modal";
36 |
37 | // Create a connector
38 | const connector = new WalletConnect({
39 | bridge: "https://bridge.walletconnect.org", // Required
40 | qrcodeModal: QRCodeModal,
41 | });
42 |
43 | // Check if connection is already established
44 | if (!connector.connected) {
45 | // create new session
46 | connector.createSession();
47 | }
48 |
49 | // Subscribe to connection events
50 | connector.on("connect", (error, payload) => {
51 | if (error) {
52 | throw error;
53 | }
54 |
55 | // Get provided accounts and chainId
56 | const { accounts, chainId } = payload.params[0];
57 | });
58 |
59 | connector.on("session_update", (error, payload) => {
60 | if (error) {
61 | throw error;
62 | }
63 |
64 | // Get updated accounts and chainId
65 | const { accounts, chainId } = payload.params[0];
66 | });
67 |
68 | connector.on("disconnect", (error, payload) => {
69 | if (error) {
70 | throw error;
71 | }
72 |
73 | // Delete connector
74 | });
75 | ```
76 |
77 | code snippet above is copied from https://docs.walletconnect.org/quick-start/dapps/client#initiate-connection, please check out the original link for standard methods.
78 |
79 | ### Get multiple chain accounts from Trust
80 |
81 | Once you have `walletconnect client` set up, you will be able to get user's accounts:
82 |
83 | ```javascript
84 | const request = connector._formatRequest({
85 | method: "get_accounts",
86 | });
87 |
88 | connector
89 | ._sendCallRequest(request)
90 | .then((result) => {
91 | // Returns the accounts
92 | console.log(result);
93 | })
94 | .catch((error) => {
95 | // Error returned when rejected
96 | console.error(error);
97 | });
98 | ```
99 |
100 | The result is an array with following structure:
101 |
102 | ```javascript
103 | [
104 | {
105 | network: number,
106 | address: string,
107 | },
108 | ];
109 | ```
110 |
111 | ### Sign multi chain transaction
112 |
113 | Once you have the account list, you will be able to sign a transaction, please note that the json structure is based on [WalletCore's proto messages](https://github.com/trustwallet/wallet-core/tree/master/src/proto), we suggest using `protobuf.js` or [@trustwallet/wallet-core](https://github.com/trustwallet/wallet-core/packages/294430) to generate it properly.
114 |
115 | ```javascript
116 | const network = 118; // Atom (SLIP-44)
117 | const account = accounts.find((account) => account.network === network);
118 | // Transaction structure based on Trust's protobuf messages.
119 | const tx = {
120 | accountNumber: "1035",
121 | chainId: "cosmoshub-2",
122 | fee: {
123 | amounts: [
124 | {
125 | denom: "uatom",
126 | amount: "5000",
127 | },
128 | ],
129 | gas: "200000",
130 | },
131 | sequence: "40",
132 | sendCoinsMessage: {
133 | fromAddress: account.address,
134 | toAddress: "cosmos1zcax8gmr0ayhw2lvg6wadfytgdhen25wrxunxa",
135 | amounts: [
136 | {
137 | denom: "uatom",
138 | amount: "100000",
139 | },
140 | ],
141 | },
142 | };
143 |
144 | const request = connector._formatRequest({
145 | method: "trust_signTransaction",
146 | params: [
147 | {
148 | network,
149 | transaction: JSON.stringify(tx),
150 | },
151 | ],
152 | });
153 |
154 | connector
155 | ._sendCallRequest(request)
156 | .then((result) => {
157 | // Returns transaction signed in json or encoded format
158 | console.log(result);
159 | })
160 | .catch((error) => {
161 | // Error returned when rejected
162 | console.error(error);
163 | });
164 | ```
165 |
166 | The result can be either a string JSON or an HEX encoded string. For Atom, the result is JSON:
167 |
168 | ```json
169 | {
170 | "tx": {
171 | "fee": {
172 | "amount": [
173 | {
174 | "amount": "5000",
175 | "denom": "uatom"
176 | }
177 | ],
178 | "gas": "200000"
179 | },
180 | "memo": "",
181 | "msg": [
182 | {
183 | "type": "cosmos-sdk/MsgSend",
184 | "value": {
185 | "amount": [
186 | {
187 | "amount": "100000",
188 | "denom": "uatom"
189 | }
190 | ],
191 | "from_address": "cosmos135qla4294zxarqhhgxsx0sw56yssa3z0f78pm0",
192 | "to_address": "cosmos1zcax8gmr0ayhw2lvg6wadfytgdhen25wrxunxa"
193 | }
194 | }
195 | ],
196 | "signatures": [
197 | {
198 | "pub_key": {
199 | "type": "tendermint/PubKeySecp256k1",
200 | "value": "A+mYPFOMSp6IYyXsW5uKTGWbXrBgeOOFXHNhLGDsGFP7"
201 | },
202 | "signature": "m10iqKAHQ5Ku5f6NcZdP29fPOYRRR+p44FbGHqpIna45AvYWrJFbsM45xbD+0ueX+9U3KYxG/jSs2I8JO55U9A=="
203 | }
204 | ],
205 | "type": "cosmos-sdk/MsgSend"
206 | }
207 | }
208 | ```
209 |
210 | ## Web3Modal
211 |
212 | [Web3Modal](https://github.com/Web3Modal/web3modal) is an easy-to-use library to help developers add support for multiple providers (including WalletConnect) in their apps with a simple customizable configuration.
213 |
214 | ### Installation
215 |
216 | ```bash
217 | npm install --save web3modal web3 @walletconnect/web3-provider
218 | ```
219 |
220 | ### Customize chain id
221 |
222 | Sample code for configuring WalletConnect with Binance Smart Chain
223 |
224 | ```js
225 | import Web3 from "web3";
226 | import WalletConnectProvider from "@walletconnect/web3-provider";
227 | import Web3Modal from "web3modal";
228 |
229 | // set chain id and rpc mapping in provider options
230 | const providerOptions = {
231 | walletconnect: {
232 | package: WalletConnectProvider,
233 | options: {
234 | rpc: {
235 | 56: "https://bsc-dataseed1.binance.org",
236 | },
237 | chainId: 56,
238 | },
239 | },
240 | };
241 |
242 | const web3Modal = new Web3Modal({
243 | network: "mainnet", // optional
244 | cacheProvider: true, // optional
245 | providerOptions, // required
246 | });
247 |
248 | const provider = await web3Modal.connect();
249 | await web3Modal.toggleModal();
250 |
251 | // regular web3 provider methods
252 | const newWeb3 = new Web3(provider);
253 | const accounts = await newWeb3.eth.getAccounts();
254 |
255 | console.log(accounts);
256 | ```
257 |
--------------------------------------------------------------------------------
/index.md:
--------------------------------------------------------------------------------
1 | # Trust Wallet Developer Documentation
2 |
3 | Here you will find all documentation for developing for Trust Wallet or using
4 | Trust Wallet's open-source libraries Wallet Core.
5 |
--------------------------------------------------------------------------------
/media/add-recovery-facet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/add-recovery-facet.png
--------------------------------------------------------------------------------
/media/android-dapp-emulator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/android-dapp-emulator.png
--------------------------------------------------------------------------------
/media/android-install-apk-emulator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/android-install-apk-emulator.png
--------------------------------------------------------------------------------
/media/assetapp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/assetapp.png
--------------------------------------------------------------------------------
/media/barz-deployment-initialization-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/barz-deployment-initialization-flow.png
--------------------------------------------------------------------------------
/media/barz-diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/barz-diagram.png
--------------------------------------------------------------------------------
/media/barz-storage-management.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/barz-storage-management.png
--------------------------------------------------------------------------------
/media/barz-userop-validation-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/barz-userop-validation-flow.png
--------------------------------------------------------------------------------
/media/bsc-abi.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/bsc-abi.gif
--------------------------------------------------------------------------------
/media/bsc-twt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/bsc-twt.png
--------------------------------------------------------------------------------
/media/conventional-proxy-pattern.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/conventional-proxy-pattern.png
--------------------------------------------------------------------------------
/media/diamond-louper-dev.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/diamond-louper-dev.png
--------------------------------------------------------------------------------
/media/diamond-proxy-pattern.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/diamond-proxy-pattern.png
--------------------------------------------------------------------------------
/media/edge-inspect.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/edge-inspect.png
--------------------------------------------------------------------------------
/media/edge-inspect2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/edge-inspect2.png
--------------------------------------------------------------------------------
/media/facet-registry.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/facet-registry.png
--------------------------------------------------------------------------------
/media/gitassetapp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/gitassetapp.png
--------------------------------------------------------------------------------
/media/github-packages-token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/github-packages-token.png
--------------------------------------------------------------------------------
/media/js-eth-sign-console.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/js-eth-sign-console.png
--------------------------------------------------------------------------------
/media/js-eth-sign.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/js-eth-sign.png
--------------------------------------------------------------------------------
/media/louper-barz.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/louper-barz.png
--------------------------------------------------------------------------------
/media/sourcetrail-screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/sourcetrail-screenshot.png
--------------------------------------------------------------------------------
/media/staking-steps.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/staking-steps.png
--------------------------------------------------------------------------------
/media/tw-aa-sdk.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/tw-aa-sdk.png
--------------------------------------------------------------------------------
/media/wallet-core-banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/wallet-core-banner.png
--------------------------------------------------------------------------------
/media/wallet-core.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trustwallet/developer/74efe1cf1913960f856f452d9ff80e53fdb586c1/media/wallet-core.png
--------------------------------------------------------------------------------
/wallet-core/android-guide.md:
--------------------------------------------------------------------------------
1 | # Android Integration Guide
2 |
3 | Wallet Core is available on the Android platform, through Java/JNI bindings.
4 | In this guide we show how to use it.
5 |
6 | A sample application is available at: https://github.com/trustwallet/wallet-core/tree/master/samples/android .
7 |
8 | ## Prerequisites
9 |
10 | - _Android Studio_
11 | - _Android NDK Support plugin_
12 |
13 | ## Adding Library Dependency
14 |
15 | Android releases are hosted on [GitHub packages](https://github.com/trustwallet/wallet-core/packages/700258), It needs authentication to download packages, please checkout [this guide from GitHub](https://docs.github.com/en/packages/guides/configuring-gradle-for-use-with-github-packages#installing-a-package) for more details.
16 |
17 | We recommend to create a non-expiring and readonly token for accessing GitHub packages, and add it to `local.properties` of your Android Studio project locally.
18 |
19 | Generate a token [here](https://github.com/settings/tokens):
20 |
21 | 
22 |
23 | Add this dependency to build.gradle:
24 |
25 | ```groovy
26 | dependencies {
27 | implementation "com.trustwallet:wallet-core:"
28 | }
29 | ```
30 |
31 | Add `maven` and `credentials` (`local.properties` for local or system environment variables CI)
32 |
33 | ```groovy
34 |
35 | Properties properties = new Properties()
36 | File localProps = new File(rootDir.absolutePath, "local.properties")
37 | if (localProps.exists()) {
38 | properties.load(localProps.newDataInputStream())
39 | } else {
40 | println "local.properties not found"
41 | }
42 |
43 | allprojects {
44 | repositories {
45 | maven {
46 | url = uri("https://maven.pkg.github.com/trustwallet/wallet-core")
47 | credentials {
48 | username = properties.getProperty("gpr.user") as String?: System.getenv("GITHUB_USER")
49 | password = properties.getProperty("gpr.key") as String?: System.getenv("GITHUB_TOKEN")
50 | }
51 | }
52 | }
53 | }
54 | ```
55 |
56 | ## Code Examples
57 |
58 | In the following sections we show code examples for some common funcions.
59 | Please refer to the [Wallet Usage Guide](wallet-core-usage.md) for detailed explanations.
60 |
61 | ### Wallet Management
62 |
63 | First thing we need is to load JNI library
64 |
65 | ```kotlin
66 | init {
67 | System.loadLibrary("TrustWalletCore")
68 | }
69 | ```
70 |
71 | Creating or Importing a Multi-Coin HD Wallet
72 |
73 | ```kotlin
74 | val wallet = HDWallet(128, "")
75 | ```
76 |
77 | ```kotlin
78 | val wallet = HDWallet("ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", "")
79 | ```
80 |
81 | ### Account Address Derivation
82 |
83 | Generating the Default Address for a Coin
84 |
85 | ```kotlin
86 | val addressBTC = wallet.getAddressForCoin(CoinType.BITCOIN)
87 | val addressETH = wallet.getAddressForCoin(CoinType.ETHEREUM)
88 | val addressBNB = wallet.getAddressForCoin(CoinType.BINANCE)
89 | ```
90 |
91 | Generating an Address Using a Custom Derivation Path (Expert)
92 |
93 | ```kotlin
94 | val key = wallet.getKey("m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0
95 | val address = CoinType.ETHEREUM.deriveAddress(key)
96 | ```
97 |
98 | ### Transaction Signing
99 |
100 | In general, when creating a new blockchain transaction, a wallet has to:
101 |
102 | 1. Put together a transaction with relevant fields (source, target, amount, etc.)
103 | 2. Sign the transaction, using the account private key. This is done by Wallet Core.
104 | 3. Send to a node for broadcasting to the blockchain network.
105 |
106 | Ethereum Transaction Signing
107 |
108 | Code example to fill in signer input parameters, perform signing, and retrieve encoded result:
109 |
110 | ```kotlin
111 | val signerInput = Ethereum.SigningInput.newBuilder().apply {
112 | chainId = ByteString.copyFrom(BigInteger("01").toByteArray())
113 | gasPrice = BigInteger("d693a400", 16).toByteString() // decimal 3600000000
114 | gasLimit = BigInteger("5208", 16).toByteString() // decimal 21000
115 | toAddress = dummyReceiverAddress
116 | transaction = Ethereum.Transaction.newBuilder().apply {
117 | transfer = Ethereum.Transaction.Transfer.newBuilder().apply {
118 | amount = BigInteger("0348bca5a16000", 16).toByteString()
119 | }.build()
120 | }.build()
121 | privateKey = ByteString.copyFrom(secretPrivateKey.data())
122 | }.build()
123 | val output = AnySigner.sign(signerInput, CoinType.ETHEREUM, Ethereum.SigningOutput.parser())
124 | println("Signed transaction: \n${signerOutput.encoded.toByteArray().toHexString()}")
125 | ```
126 |
--------------------------------------------------------------------------------
/wallet-core/building.md:
--------------------------------------------------------------------------------
1 | # Building and Testing
2 |
3 | Find here instructions for building the Wallet Core library locally.
4 |
5 | ## Platforms
6 |
7 | The following _target platforms_ are supported:
8 |
9 | - **iOS** (Swift language is used)
10 | - **Android**
11 | - **Wasm** (Emscripten)
12 |
13 | The following _development platforms_ are supported:
14 |
15 | - **macOS**: is the _primary_ development platform, as it supports compiling for both target platforms.
16 | - **Linux**: is supported as a development platform if you only need to build C++ and Wasm targets.
17 |
18 | ## Build Methods
19 |
20 | Wallet Core can be build inside a Docker image, or natively.
21 |
22 | - Inside **Docker** image: This way is easier to get the prerequisites, as they are all inside a Docker image. However, all building has to be done inside the Docker image.
23 | - Natively, in your dev OS (macOS, Linux).
24 |
25 | ## Prerequisites
26 |
27 | Use one top-level script to install all required dependencies and prepare WalletCore for building:
28 |
29 | ```shell
30 | ./bootstrap.sh all
31 | ```
32 |
33 | Please note that the script configures the environment for all target platforms: Native, Android, iOS (on MacOS), and WASM.
34 | If you intend to use WalletCore on specific platforms only, you can specify those platforms in the arguments:
35 |
36 | ```shell
37 | ./bootstrap.sh android ios
38 | ```
39 |
40 | Otherwise, consider installing the required prerequisites manually below.
41 |
42 | ### Prerequisites on macOS
43 |
44 | - CMake `brew install cmake`
45 | - Boost `brew install boost`
46 | - Xcode
47 | - Xcode command line tools: `xcode-select --install`
48 | - Ruby `brew install ruby`
49 | - Other tools: `brew install git ninja autoconf automake libtool xcodegen clang-format ccache cocoapods`
50 | - [Android Studio](https://developer.android.com/studio/index.html)
51 | - [Android NDK](https://developer.android.com/ndk/guides/)
52 | - Rust: `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh`
53 | - [emscripten (for WASM)](https://emscripten.org/docs/introducing_emscripten/about_emscripten.html)
54 |
55 | ### Prerequisites on Linux
56 |
57 | Ubuntu as a example:
58 |
59 | - Various essential packages `sudo apt-get install build-essential libtool autoconf pkg-config ninja-build ccache`
60 | - Clang `sudo apt-get install clang-14 llvm-14 libc++-dev libc++abi-dev`
61 | - Ruby `sudo apt-get install ruby-full`
62 | - Boost `sudo apt-get install libboost-all-dev`
63 | - CMake `sudo apt-get install cmake` or (from https://github.com/Kitware/CMake/releases)
64 | - [Android Studio](https://developer.android.com/studio/index.html)
65 | - Rust: `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh`
66 | - [emscripten (for WASM)](https://emscripten.org/docs/introducing_emscripten/about_emscripten.html)
67 |
68 | ### Managed Prerequisites
69 |
70 | Additionally, the following prerequisites are also needed, but they are managed by Wallet Core. The script `tools/install-dependencies` downloads and compiles them (see below).
71 |
72 | - Google test (gtest)
73 | - libcheck
74 | - nolhmann json
75 | - Protobuf
76 |
77 | ## Full Build
78 |
79 | WalletCore is ready to be built after installing all prerequisites.
80 | Building for each platform is different.
81 |
82 | ### Native building and testing
83 |
84 | To build and run tests on the native platform (Linux, MacOS), run the following command:
85 |
86 | ```shell
87 | ./tools/build-and-test
88 | ```
89 |
90 | Or, broken up in smaller steps:
91 |
92 | 1. This script generates source files, coin- and protobuf files.
93 | Needs to be re-run whenever `registry.json`, or protobuf files, or `./include` interface, or Rust codebase are changed.
94 |
95 | ```shell
96 | ./tools/generate-files
97 | ```
98 |
99 | 2. Standard CMake and make commands for building the library. The `cmake` command needs to be re-run whenever a new C++ source file is added.
100 |
101 | ```shell
102 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug
103 | ```
104 |
105 | 3. Build TrezorCrypto and WalletCore C++ tests.
106 |
107 | ```shell
108 | make -Cbuild -j12 tests TrezorCryptoTests
109 | ```
110 |
111 | 4. Run TrezorCrypto and WalletCore C++ tests.
112 |
113 | ```shell
114 | ./build/tests/tests tests --gtest_filter=*
115 | ```
116 |
117 | If you'd rather use and IDE for building and debugging you can specify the `-G` option to cmake. For instance to use Xcode call `cmake -Bxcode -GXcode -DCMAKE_BUILD_TYPE=Debug` and use the generated project in the xcode folder.
118 |
119 | ### Wasm building
120 |
121 | Configure WASM environment with either running a bootstrap:
122 |
123 | ```shell
124 | ./bootstrap.sh wasm
125 | ```
126 |
127 | Or installing [Emscripten SDK](https://emscripten.org/docs/introducing_emscripten/about_emscripten.html) (emsdk) manually:
128 |
129 | ```shell
130 | `tools/install-wasm-dependencies`
131 | ```
132 |
133 | Activate `emsdk`:
134 |
135 | ```shell
136 | `source emsdk/emsdk_env.sh`
137 | ```
138 |
139 | After WASM environment is configured, build WalletCore for WASM:
140 |
141 | ```shell
142 | tools/wasm-build
143 | ```
144 |
145 | Run Wasm tests:
146 |
147 | ```shell
148 | cd wasm
149 | npm install && npm run copy:wasm && npm run build
150 | npm run test
151 | ```
152 |
153 | ## Testing Rust library
154 |
155 | Rust library can be tested separately from the C++ part.
156 |
157 | ```shell
158 | cd rust
159 | cargo test
160 | ```
161 |
162 | ## Checking Rust lints
163 |
164 | We use [rustfmt](https://github.com/rust-lang/rustfmt), [clippy](https://github.com/rust-lang/rust-clippy) to check
165 | if the Rust code is formatted and does not contain common warnings/errors.
166 |
167 | Run Rust lints:
168 |
169 | ```shell
170 | ./tools/rust-lints
171 | ```
172 |
173 | ## Building inside Docker image
174 |
175 | Here are the instructions to build Wallet Core with the provided `Dockerfile`.
176 |
177 | Prerequisite is a working Docker installation.
178 |
179 | The command for building the Docker image:
180 |
181 | ```shell
182 | docker build docker/wallet-core --tag wallet-core-dev
183 | ```
184 |
185 | Then launch the container:
186 |
187 | ```shell
188 | docker run -i -t wallet-core-dev /bin/bash
189 | ```
190 |
191 | Inside the container the build commands can be executed (as described above; note that install-dependencies is not necessary):
192 |
193 | ```shell
194 | cd wallet-core
195 | ./tools/build-and-test
196 | ```
197 |
198 | ## Executing inside Docker image
199 |
200 | The Docker image also contains a pre-built, runnable version of the library, so it is possible to run it, 'toy around' with it without any building.
201 | _Note:_ this may not be the most recent version!
202 |
203 | Unit tests and [wallet console utility](walletconsole.md) can be executed straight from this Docker image:
204 |
205 | ```shell
206 | docker run -i -t trustwallet/wallet-core
207 | cd wallet-core
208 | ./build/tests/tests tests
209 | ./build/walletconsole/walletconsole
210 | exit
211 | ```
212 |
213 | ## Linux
214 |
215 | Building on Linux is possible, it requires some extra work. If you have access to macOS we highly recommend developing on that platform. Using the Docker image is also recommended.
216 | Otherwise, the prerequisites have to be installed manually. We recommend using Ubuntu 22.04 LTS, same as [Wallet Core CI](https://github.com/trustwallet/wallet-core/blob/master/.github/workflows/linux-ci.yml).
217 |
218 | ## Unit tests with Coverage
219 |
220 | For executing tests locally with coverage measurement, some extra `cmake` settings are needed;
221 | see [section on coverage instructions](coverage.md).
222 |
223 | ## All CMake options
224 |
225 | We enable these options on CI: `-DCMAKE_BUILD_TYPE=Debug -DTW_UNITY_BUILD=ON -DTW_CODE_COVERAGE=ON -DTW_ENABLE_CLANG_TIDY=ON -DTW_CLANG_ASAN=ON`
226 |
227 | | Name | Description | How to enable it | Notes |
228 | | --------------------- | ----------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
229 | | TW_IDE_CLION | Specify that your IDE is CLion, way to enable coverage is different on CLion | -DTW_IDE_CLION=ON | Do not enable multiple IDE options at the same time Off by default |
230 | | TW_IDE_VSCODE | Specify that your IDE is vscode, way to use PVS-studio is different on VSCode | -DTW_IDE_VSCODE=ON | Do not enable multiple IDE options at the same time Off by default |
231 | | TW_UNITY_BUILD | Specify that you want to use UNITY BUILD in the project, use it in order to build faster. | -DTW_UNITY_BUILD=ON | To be used for CI environment. Off by default |
232 | | TW_ENABLE_CLANG_TIDY | Specify that you want to build with clang-tidy static analyzer. | -DTW_ENABLE_CLANG_TIDY=ON | Do not use it at the same time as `TW_ENABLE_PVS_STUDIO` Clang-tidy must be installed Off by default |
233 | | TW_ENABLE_PVS_STUDIO | Specify that you want to build with pvs-studio static analyzer | -DTW_ENABLE_PVS_STUDIO=ON | Do not use it at the same time as `TW_ENABLE_CLANG_TIDY` PVS-Studio must be installed and configured. Can be combined with `TW_IDE_VSCODE` Off by default |
234 | | TW_CLANG_ASAN | Specify that you want to build with ASAN dynamic analyzer. | -DTW_CLANG_ASAN=ON | use it in Debug for optimal result. Do not mix with other runtime analyzer. Off by default |
235 | | TW_COMPILE_WASM | Specify that you are targeting WASM. | -DTW_COMPILE_WASM=ON | Off by default |
236 | | TW_CODE_COVERAGE | Specify that you want to build with coverage support | -DTW_CODE_COVERAGE=ON | Can be combined with `TW_IDE_CLION` Off by default |
237 | | TW_WARNINGS_AS_ERRORS | Specify that you want to treat all the warnings as error | -DTW_WARNINGS_AS_ERRORS=ON | Adviced to be used locally, during development. Off by default |
238 | | TW_ENABLE_CCACHE | Specify that you want to use CCACHE | -DTW_ENABLE_CCACHE=ON | On by default |
239 | | TW_UNIT_TESTS | Specify that you want to enable unit tests in the project | -DTW_UNIT_TESTS=ON | On by default on native platforms |
240 | | TW_BUILD_EXAMPLES | Specify that you want to enable examples in the project | -DTW_BUILD_EXAMPLES=ON | On by default on native platforms |
241 |
--------------------------------------------------------------------------------
/wallet-core/contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want to make Trust Wallet Core as good as it can be. If you want to contribute your help is greatly appreciated. Contributing is also a great way to learn more about blockchain technology and improve Trust Wallet. To make the process as smooth as possible please read this document and follow our guidelines. We are happy to review your code but please ensure that you have a [clean pull request](contributing.md#pull-requests).
4 |
5 | Wallet Core implements the cryptographic functionality of blockchains. This includes elliptic curve cryptography, hashing, address derivation and transaction signing. However it _does not_ implement other aspects like networking and UI. Wallet core behaves like a black box for higher level users like Trust Wallet; it takes inputs from the blockchain and the user \(for instance UTXOs, private keys, etc.\) and produces an output \(like a signed and encoded transaction\). Keep this in mind when adding functionality.
6 |
7 | This is a diagram representing how Trust Wallet interacts with Trust Wallet Core.
8 |
9 | 
10 |
11 | ## Library Design Guidelines
12 |
13 | This library is designed so that it can be used from any other programming languages, and that every language has an idiomatic interface. Design goals also include minimizing the binary size and maximizing performance.
14 |
15 | With these goals in mind we chose C/C++ for the implementation and a strict subset of C for the interface. This C interface is used to generate the idiomatic interfaces for every supported language. To augment the expressivity of the interface we also use Protocol Buffer objects that get serialized across the interface.
16 |
17 | Keep this in mind when adding to the library:
18 |
19 | - Only expose C headers. Clients should not have access to the C++ interfaces.
20 | - C headers need to have annotations for the code generation tool, see below.
21 | - Use Protocol Buffers to represent models. C doesn't have good abstractions for variable-sized types.
22 | - Every time you modify the interface run the code generation tool and make sure the interface also makes sense in target languages.
23 |
24 | There is a [Sourcetrail](https://github.com/CoatiSoftware/Sourcetrail) [project file](https://github.com/trustwallet/wallet-core/blob/master/wallet_core.srctrlprj) might help you explore all the code (after build and run `bootstrap.sh`).
25 |
26 | 
27 |
28 | ## Pull Requests
29 |
30 | Please follow these instructions when submitting a pull request \(PR\):
31 |
32 | - Create a personal fork of the project on GitHub.
33 | - Clone the fork on your local machine. Your remote repo on Github is called `origin`.
34 | - Add the official repository as a remote called `upstream`.
35 | - If you created your fork a while ago be sure to pull upstream changes into your local repository.
36 | - Create a new branch to work on! Branch from the latest `upstream/master`.
37 | - Implement/fix your feature, comment your code.
38 | - Write or adapt tests as needed.
39 | - Follow the code style of the project, including indentation. Use `clang-format` if you are unsure.
40 | - Run the tests.
41 | - Modify your commit history so that it tells a story using git's [interactive rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History). Create a new branch if necessary.
42 | - Write your commit messages in the present tense. Your commit message should describe what the commit, when applied, does to the code, not what you did to the code.
43 | - Push your branch to your fork on Github, the remote `origin`.
44 | - From your fork open a pull request in the correct branch. Target the project's `master` branch.
45 | - If we request further changes push them to your branch. The PR will be updated automatically.
46 | - Once the pull request is approved and merged you can pull the changes from `upstream` to your local repo and delete
47 |
48 | your extra branch\(es\).
49 |
50 | Is it not uncommon for a PR to accumulate commits and merges with time. The library is in constant change. If your PR falls out of sync with the upstream master you need to rebase. We can't reliably review code that is spread over too many other changes to the codebase. Please use git's [interactive rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History) and if necessary create a new PR.
51 |
52 | ## Project organization
53 |
54 | This project has a number of different pieces. Each piece lives in its own subfolder.
55 |
56 | - The `docs` folder contains documentation.
57 | - The `src` folder contains the C++ implementation of the core functionality.
58 | - The `include` folder contains the public C header files used to expose a cross-platform interface.
59 | - The `codegen` folder contains the code and templates used to generate code for different platforms and languages.
60 | - The `jni` folder contains the generated JNI interface and Java classes.
61 | - The `android` folder contains the Android Studio project and integration tests.
62 | - The `swift` folder contains the generated Swift code and Xcode project.
63 | - The `trezor-crypto` folder contains a fork of [https://github.com/trezor/trezor-crypto/](https://github.com/trezor/trezor-crypto/) with modifications.
64 | - The `tests` folder contains unit tests.
65 | - The `tools` folder contains scripts to automate common tasks.
66 | - The `samples` folder contains sample applications.
67 |
68 | ## Prerequisites and Building
69 |
70 | Please refer to [build instructions](building.md) for building the library locally.
71 |
72 | ## Testing
73 |
74 | After running `bootstrap.sh` run `make -C build tests && build/tests/tests tests` to run all the C++ unit tests. To run integration tests on each platform run the respective script in the tools folder:
75 |
76 | - Android: run `tools/android-test` or import `android` folder to Android Studio
77 | - iOS: run `tools/ios-test` or cd `swift` folder and open `TrustWalletCore.xcworkspace`
78 |
79 | To run all tests in one go use the `tools/tests` script.
80 |
81 | ## C Headers
82 |
83 | The wallet core code generator parses C headers for class and struct definitions. Headers need to be in the `include/TrustWalletCode` folder and start with the `TW` prefix followed by the class or sturct name. Inside each header file there needs to be exactly one class or struct defition.
84 |
85 | A class definition starts with the `TW_EXPORT_CLASS` macro followed by a forward-declared struct. For example:
86 |
87 | ```c
88 | TW_EXPORT_CLASS
89 | struct TWPrivateKey;
90 | ```
91 |
92 | Similarly, a struct definition start with the `TW_EXPORT_STRUCT` macro followed by an inline-declared struct. For example:
93 |
94 | ```c
95 | TW_EXPORT_STRUCT
96 | struct TWPublicKey {
97 | uint8_t bytes[TWPublicKeyUncompressedSize];
98 | };
99 | ```
100 |
101 | You can also define enumerations using the `TW_EXPORT_ENUM()` macro:
102 |
103 | ```text
104 | TW_EXPORT_ENUM(uint32_t)
105 | enum TWCoinType {
106 | TWCoinTypeBitcoin = 0,
107 | };
108 | ```
109 |
110 | After the class or struct definition you can declare as many methods and properties as necessary. There are four types of declarations: static method, static property, method, and property. Each is declared by `TW_EXPORT_STATIC_METHOD`, `TW_EXPORT_STATIC_PROPERTY`, `TW_EXPORT_METHOD`, and `TW_EXPORT_PROPERTY` respectively. Each method or property name needs to start with the type name. For instance `TWPublicKeyIsValid` gets translated to the `isValid` property in the `PublicKey` type.
111 |
112 | The types that methods can take and return are restricted to: `bool`, `int`, `size_t`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `TWData`, `TWString`, and any defined classses, structs or enums.
113 |
114 | Methods always take the type as their first argument. The type needs to be a pointer if the type is a class and a struct if the type is a struct. Properties need to take the type as its only argument.
115 |
116 | Static property declarations can take no arguments. Static methods can take any arguments.
117 |
118 | Since C interface doesn't know how to handle C++ exception, we should catch all possible exceptions in the C implementation.
119 |
120 | ## Coin definition
121 |
122 | The wallet core code generator also parses coin configuration defined in `registry.json`, the generated code will be located at `src/Generated/Coins.cpp`.
123 | See the documentation of the fields here: https://github.com/trustwallet/wallet-core/blob/master/docs/registry-fields.md.
124 |
125 | Example:
126 |
127 | ```json
128 | {
129 | "id": "bitcoin",
130 | "name": "Bitcoin",
131 | "coinId": 0,
132 | "symbol": "BTC",
133 | "decimals": 8,
134 | "blockchain": "Bitcoin",
135 | "derivation": [
136 | {
137 | "name": "segwit",
138 | "path": "m/84'/0'/0'/0/0",
139 | "xpub": "zpub",
140 | "xprv": "zprv"
141 | },
142 | {
143 | "name": "legacy",
144 | "path": "m/44'/0'/0'/0/0",
145 | "xpub": "xpub",
146 | "xprv": "xprv"
147 | }
148 | ],
149 | "curve": "secp256k1",
150 | "publicKeyType": "secp256k1",
151 | "p2pkhPrefix": 0,
152 | "p2shPrefix": 5,
153 | "hrp": "bc",
154 | "publicKeyHasher": "sha256ripemd",
155 | "base58Hasher": "sha256d",
156 | "explorer": {
157 | "url": "https://blockchair.com",
158 | "txPath": "/bitcoin/transaction/",
159 | "accountPath": "/bitcoin/address/",
160 | "sampleTx": "0607f62530b68cfcc91c57a1702841dd399a899d0eecda8e31ecca3f52f01df2",
161 | "sampleAccount": "17A16QmavnUfCW11DAApiJxp7ARnxN5pGX"
162 | },
163 | "info": {
164 | "url": "https://bitcoin.org",
165 | "source": "https://github.com/trezor/blockbook",
166 | "rpc": "",
167 | "documentation": "https://github.com/trezor/blockbook/blob/master/docs/api.md"
168 | }
169 | }
170 | ```
171 |
172 | ## Protocol Buffers
173 |
174 | Since the C language doesn't provide good abstractions for variable-sized arrays and strings, the C interface uses [Protocol Buffers](https://developers.google.com/protocol-buffers/). All models are defined in the `src/proto` folder. These models can then be used in the C interface by using the proto model name with underscores. For instance `TW_Binance_Proto_SigningInput`.
175 |
176 | The proto file will be used to generate C++ classes and also classes in each supported client language \(Swift, Java, etc.\). The code generator will also generate the protobuf serialization code so that library clients don't have to worry about serialization. To generate the Protocol Buffers code run the `tools/generate-files` script when you modify the `src/TrustWalletCore.proto` file.
177 |
178 | ## Code Style
179 |
180 | Wallet core follows the [LLVM Coding Standards](http://llvm.org/docs/CodingStandards.html) for C++. We use `clang-format` to ensure a consistent code sytle. **Do not** reformat files that you didn't modify, or the header files in the `include` folder. You can install a clang-format extension for your IDE.
181 |
182 | ## More
183 |
184 | - [Build instructions](building.md)
185 | - [Adding Support for a New Blockchain](newblockchain.md)
186 | - [Releasing](releasing.md)
187 |
--------------------------------------------------------------------------------
/wallet-core/coverage.md:
--------------------------------------------------------------------------------
1 | # Coverage Measurement
2 |
3 | Wallet-core is a stable project, we value stability and safety over new features.
4 |
5 | Test coverage is one important facet of assuring code quality, and we are strict about high test coverage.
6 |
7 | ## Checking Coverage Summary in CI build
8 |
9 | The `Linux CI` and `Linux CI Rust` CI builds (executed on PRs and commits) contain coverage measurement, and summary is available in the build output:
10 |
11 | ```
12 | Summary coverage rate:
13 | lines......: 94.5% (14576 of 15426 lines)
14 | functions..: 95.0% (2688 of 2830 functions)
15 | ```
16 |
17 | ## Detailed Coverage Report
18 |
19 | Detailed coverage report can be generated locally. It includes file and line-level info on coverage.
20 |
21 | Steps:
22 |
23 | - Run `tools/generate-file` to make sure new added files are generated
24 |
25 | - Run `cmake` with `-DCODE_COVERAGE=ON` to enable coverage measurement
26 |
27 | ```shell
28 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCODE_COVERAGE=ON
29 | ```
30 |
31 | - Build tests
32 |
33 | ```shell
34 | make -Cbuild -j12 tests TrezorCryptoTests
35 | ```
36 |
37 | - Cleanup any old coverage files, and run unit tests
38 |
39 | ```shell
40 | find . -name "*.gcda" -exec rm {} \;
41 | ./build/trezor-crypto/crypto/tests/TrezorCryptoTests
42 | ./build/tests/tests tests --gtest_output=xml
43 | ```
44 |
45 | - Generate coverage info (slow). With the `html` argument the script will generate HTML report as well:
46 |
47 | ```shell
48 | ./tools/coverage html
49 | ```
50 |
51 | if you see genhtml (from lcov) error on macOS like below:
52 |
53 | ```shell
54 | c++filt: Unknown command line argument '--no-strip-underscores'. Try: '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++filt --help'
55 | c++filt: Did you mean '--no-strip-underscore'?
56 | genhtml: ERROR: c++filt output not as expected (0 vs 11) lines
57 | ```
58 |
59 | please upgrade `lcov` to min. `1.16`, or patch `genhtml` (for example /usr/local/Cellar/lcov/1.15/libexec/bin/), change `--no-strip-underscores` to `--no-strip-underscore`
60 |
61 | Open the generated `coverage/index.html` to view the report.
62 |
63 | See also
64 | [tools/coverage](https://github.com/trustwallet/wallet-core/blob/master/tools/coverage) and
65 | [linux-ci.yml](https://github.com/trustwallet/wallet-core/blob/master/.github/workflows/linux-ci.yml)
66 |
67 | # Detailed Rust Coverage Report
68 |
69 | Detailed Rust coverage report can be generated locally. It includes file and line-level info on coverage.
70 |
71 | Steps:
72 |
73 | - Switch to the nightly toolchain and install dev dependencies
74 |
75 | ```shell
76 | tools/install-rust-dependencies dev
77 | ```
78 |
79 | - Run Rust tests and generate coverage info (slow). With the `html` argument the script will generate HTML report as well:
80 |
81 | ```shell
82 | ./tools/rust-coverage html
83 | ```
84 |
--------------------------------------------------------------------------------
/wallet-core/faq.md:
--------------------------------------------------------------------------------
1 | # Frequently Asked Questions
2 |
3 | ## General
4 |
5 | ### Does Wallet Core support Windows?
6 |
7 | A: We don't support Windows officially, the community has a fork for Windows, you can find it [here](https://github.com/kaetemi/wallet-core-windows).
8 |
9 | ### Does Wallet Core support Dart / Flutter?
10 |
11 | A: We don't support it officially, the community has a fork for Dart / Flutter, you can find it [here](https://github.com/weishirongzhen/flutter_trust_wallet_core)
12 |
13 | ### Does Wallet Core support React Native?
14 |
15 | A: Not now, but you can try to wrap it using [Native Module](https://reactnative.dev/docs/native-modules-intro) or [JavaScript Interfaces (JSI)](https://reactnative.dev/architecture/glossary#javascript-interfaces-jsi), one example is [here](https://github.com/Liamandrew/react-native-wallet-core).
16 |
17 | ### I can't install Wallet Core for my Android project!
18 |
19 | A: Take a look at `Adding Library Dependency` section in [Android Integration Guide](android-guide.md), we have detailed instructions for installing the package.
20 |
21 | ### Is there any HTTP API to use Trust Wallet service?
22 |
23 | A: Nope.
24 |
25 | ## API
26 |
27 | ### Does Wallet Core support WIF?
28 |
29 | A: No, Here are some reasons:
30 |
31 | - WIF (Wallet Import Format) is just a private key encoded in Base58-check format, you can decode it using `Base58` class.
32 | - It's cumbersome to support different prefix byte for all networks (mainly Bitcoin and forks)
33 | - Hex string encoding is a more widely used format.
34 |
35 | ### Does Wallet Core have a method to verify an address format?
36 |
37 | A: Yes, There is a generic `AnyAddress` class to represent an address for any blockchain you can use `AnyAddress.isValid()` to validate if an address is valid.
38 |
39 | ### How to create `HDWallet` from private key?
40 |
41 | A: `HDWallet` class is short for `Hierarchical Deterministic Wallet`, which is a way to deterministically generate a tree of keys from a single seed (aka bip39 recovery phrase). If you only have a private key, you can use `PrivateKey` class directly, no way to create `HDWallet`.
42 |
43 | You can read [bip32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), [bip39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki), [bip44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) for more information.
44 |
45 | ### Where do I find transaction signing examples?
46 |
47 | A: You can find some on [Usage Guide](https://developer.trustwallet.com/wallet-core/integration-guide/wallet-core-usage), the comprehensive and up-to-date examples are in tests folder:
48 |
49 | - C++ tests:
50 | - Swift tests:
51 | - Kotlin tests:
52 | - TypeScript tests:
53 |
54 | ## Blockchain
55 |
56 | ### How to query the balance / tokens of an address?
57 |
58 | A: Wallet Core doesn't provide this feature yet, it also differs from chain to chain, you should check out the blockchain's official RPC or API to see how to query the balance.
59 |
60 | For instance, you can use [`eth_getbalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance) and [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call) to query the balance (and token balance) of an Ethereum or EVM compatible address.
61 |
62 | ### How to send signed transaction?
63 |
64 | A: Wallet Core doesn't provide this feature yet, it also differs from chain to chain, you should check out the blockchain's official RPC or API to see how to send a signed transaction.
65 |
66 | For instance, you can use [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction) to send a signed raw transaction to Ethereum or EVM compatible chain.
67 |
68 | ### Bitcoin signing error :Invalid transaction. Error: bad-txns-inputs-missingorspent
69 |
70 | A: Usually this error means the node can't find the unspent transaction (UTXO) you are trying to spend, you can check if the transaction hash is correct, Bitcoin implementation in Wallet Core expects the transaction id is network byte order (big endian), you can try to reverse the bytes of the transaction hash.
71 |
72 | ### Does it support Bitcoin / Ethereum testnet?
73 |
74 | A: Wallet Core doesn't support any testnet in general:
75 |
76 | - no testnet network entry in `registry.json`
77 | - no method to generate testnet address for Bitcoin etc.
78 | - extra maintenance effort and we always require mainnet transaction signing test.
79 |
80 | But for some networks like Ethereum, the testnet just has a different chain id, you can specify chain id when you signing a transaction.
81 |
82 | ### How to generate legacy Bitcoin address?
83 |
84 | A: `AnyAddress` generates SegWit address by default for Bitcoin, Wallet Core offers another class `BitcoinAddress` for legacy address, you can see all the methods [here](https://github.com/trustwallet/wallet-core/blob/master/include/TrustWalletCore/TWBitcoinAddress.h).
85 |
86 | ### Does it support ERC20 / BEP20?
87 |
88 | A: Yes
89 |
90 | ### Different Polkadot address derived from same secret phrase.
91 |
92 | A: Polkadot supports multiple elliptic curve and signature schemes:
93 |
94 | - The vanilla `ed25519` implementation using Schnorr signatures.
95 | - The Schnorrkel/Ristretto `sr25519` variant using Schnorr signatures.
96 | - ECDSA signatures on `secp256k1`
97 |
98 | It's might be incompatible with other wallets because Wallet Core currently only supports `ed25519`.
99 |
100 | For more information, please refer to [Polkadot Wiki](https://wiki.polkadot.network/docs/learn-keys#account-keys).
101 |
--------------------------------------------------------------------------------
/wallet-core/integration-guide.md:
--------------------------------------------------------------------------------
1 | # Wallet Core Integration Guide
2 |
3 | This Integration Guide is intended for developers building on top of Wallet Core. Typical projects using Wallet Core are _mobile wallets_ -- iOS and/or Android apps, and potentially desktop wallets.
4 | Wallet Core functionality can prove to be helpful in some backend-side projects as well.
5 |
6 | The guide has the following outline:
7 |
8 | - [Wallet Core Usage Guide](wallet-core-usage.md).
9 | In this general guide we describe the basic wallet operations (_wallet creation_, _address derivation_, _transaction signing_) in detail, with some code examples. This is recommended first.
10 |
11 | - [iOS Integration Guide](ios-guide.md).
12 | This is a walkthrough of a sample iOS wallet application.
13 |
14 | - [Android Integration Guide](android-guide.md).
15 | This is a walkthrough of a sample Android wallet application.
16 |
17 | - [Server-Side GoLang Guide](server-side.md).
18 | Here we provide instructions on how to integrate Wallet Core into a _Go_ languge backend-side project.
19 |
--------------------------------------------------------------------------------
/wallet-core/ios-guide.md:
--------------------------------------------------------------------------------
1 | # iOS Integration Guide
2 |
3 | Wallet Core is available on the iOS platform, it comes with _Swift_ bindings.
4 | In this guide we show how to use it.
5 |
6 | A sample application is available at: https://github.com/trustwallet/wallet-core/tree/master/samples/osx .
7 |
8 | ## Prerequisites
9 |
10 | - [_CocoaPods_](https://cocoapods.org/). If you don't have it, install it by
11 | `gem install cocoapods`.
12 | - _Xcode_ toolchain
13 | - Wallet Core library
14 |
15 | ## Adding Library Dependency
16 |
17 | An easy way to add Wallet Core dependency to an iOS project is through _CocoaPods_, like this (the exact version may change in the future):
18 |
19 | ```
20 | pod 'TrustWalletCore'
21 | ```
22 |
23 | The dependency can be installed simply by `pod install`:
24 |
25 | ```shell
26 | pod install
27 | ```
28 |
29 | SPM is also supported, download latest `Package.swift` from [GitHub Releases](https://github.com/trustwallet/wallet-core/releases) and put it in a local `WalletCore` folder.
30 |
31 | Add this line to the `dependencies` parameter in your `Package.swift`:
32 |
33 | ```swift
34 | .package(name: "WalletCore", path: "../WalletCore"),
35 | ```
36 |
37 | Or add remote url + `master` branch, it points to recent (not always latest) binary release.
38 |
39 | ```swift
40 | .package(name: "WalletCore", url: "https://github.com/trustwallet/wallet-core", .branchItem("master")),
41 | ```
42 |
43 | Then add libraries to target's `dependencies`:
44 |
45 | ```swift
46 | .product(name: "WalletCore", package: "WalletCore"),
47 | .product(name: "SwiftProtobuf", package: "WalletCore"),
48 | ```
49 |
50 | ## Code Examples
51 |
52 | In the following sections we show code examples for some common funcions.
53 | Please refer to the [Wallet Usage Guide](wallet-core-usage.md) for detailed explanations.
54 |
55 | Accessing Wallet Core functionality requires one import statement:
56 |
57 | ```swift
58 | import WalletCore
59 | ```
60 |
61 | ### Wallet Management
62 |
63 | Creating or Importing a Multi-Coin HD Wallet
64 |
65 | ```swift
66 | let wallet = HDWallet(strength: 128, passphrase: "")
67 | ```
68 |
69 | ```swift
70 | let wallet = HDWallet(mnemonic: "ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", passphrase: "")!
71 | ```
72 |
73 | ### Account Address Derivation
74 |
75 | Generating the Default Address for a Coin
76 |
77 | ```swift
78 | let addressBTC = wallet.getAddressForCoin(coin: .bitcoin)
79 | let addressETH = wallet.getAddressForCoin(coin: .ethereum)
80 | let addressBNB = wallet.getAddressForCoin(coin: .binance)
81 | ```
82 |
83 | Generating an Address Using a Custom Derivation Path (Expert)
84 |
85 | ```swift
86 | let key = wallet.getKey(derivationPath: "m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0
87 | let address = CoinType.ethereum.deriveAddress(privateKey: key)
88 | ```
89 |
90 | ### Transaction Signing
91 |
92 | In general, when creating a new blockchain transaction, a wallet has to:
93 |
94 | 1. Put together a transaction with relevant fields (source, target, amount, etc.)
95 | 2. Sign the transaction, using the account private key. This is done by Wallet Core.
96 | 3. Send to a node for broadcasting to the blockchain network.
97 |
98 | Ethereum Transaction Signing
99 |
100 | Code example to fill in signer input parameters, perform signing, and retrieve encoded result:
101 |
102 | ```swift
103 | let signerInput = EthereumSigningInput.with {
104 | $0.chainID = Data(hexString: "01")!
105 | $0.gasPrice = Data(hexString: "d693a400")! // decimal 3600000000
106 | $0.gasLimit = Data(hexString: "5208")! // decimal 21000
107 | $0.toAddress = "0xC37054b3b48C3317082E7ba872d7753D13da4986"
108 | $0.transaction = EthereumTransaction.with {
109 | $0.transfer = EthereumTransaction.Transfer.with {
110 | $0.amount = Data(hexString: "0348bca5a16000")!
111 | }
112 | }
113 | $0.privateKey = wallet.getKeyForCoin(coin: .ethereum).data
114 | }
115 | let output: EthereumSigningOutput = AnySigner.sign(input: signerInput, coin: .ethereum)
116 | print(" data: ", output.encoded.hexString)
117 | ```
118 |
--------------------------------------------------------------------------------
/wallet-core/newblockchain.md:
--------------------------------------------------------------------------------
1 | # Adding Support for a New Blockchain
2 |
3 | If you haven't, first read the [guide to contributing](contributing.md). It contains important information about the library and how to contribute.
4 |
5 | ## Blockchains, Coins and Tokens
6 |
7 | - If you are interested in adding a new Token, e.g. ERC20, in this case no code changes are needed, see the [Assets](../assets/new-asset.md) section for more details.
8 | - If you are adding an EVM-compatible chain, that is much simpler, see [EVM Chain docs](newevmchain.md).
9 | - For new coins you need to implement address handling and signing functionality in wallet-core (described in this section). For new coins on already supported blockchains, or variations of already supported blockchains, please consider proper reuse of existing implementation.
10 |
11 | ## Integration Criteria
12 |
13 | The Trust Wallet development team is always striving to add more blockchains that will be essential for developers and wallet users. We choose blockchains carefully based on the impact they will have for our community.
14 |
15 | Please keep in mind that Wallet Core is open source and used in many other projects besides Trust Wallet, so adding it to Wallet Core is a prerequisite but not a sufficient condition for adding it to Trust Wallet.
16 |
17 | The general integration criteria is as follows:
18 |
19 | - The blockchain has launched mainnet and has stably run for at least 3 ~ 6 months without major security incidents.
20 | - The blockchain has extensive public documentation and tools available for developers to use.
21 | - The native coin is listed in the top 100 coins on CoinMarketCap and proposal gets approved on [https://governance.trustwallet.com].
22 | - The project needs to provide API/JSON-RPC access to the node with a load balancing setup for private use, see detail requirements [here](https://developer.trustwallet.com/wallet-core/rpc-requirements).
23 | - The native coin is tradable on major exchanges.
24 |
25 | After integrating into Trust Wallet projects are expected to provide timely support for any urgent matters.
26 |
27 | ## Overview
28 |
29 | Adding support for a new coin consists of these steps:
30 |
31 | - Add **coin definition** -- contains basic parameters of the new coin, several definition source files are generated from the definitions
32 | - Extend a few **central files**. There are a few central source files that need to be extended (some definitions, dispatching logic to coin implementations).
33 | - **Rust implementation** of **address** handling and **signing** functionality. Optionally protobuf definitions might be needed for more complex parameters.
34 | - **Unit tests** for coin definitions, address and signing functionality
35 | - **C interface** (basis for mobile integration)
36 | - **Kotlin** and **Swift** bindings -- these are generated
37 | - **Integration tests** for testing through C interface, and through JN and Swift interfaces.
38 |
39 | It helps to pick an existing coin, and refer to its implementation. Try to pick an existing coin that is similar to the new one, and check how/where is it implemented, tested, etc.
40 |
41 | Note that unit **tests** are crucial in ensuring quality needed for multi-coin support. Functionality here can be well unit-tested, so don't ignore them.
42 | Coverage must not decrease! This is enforced automatically in the valiation of the pull requests.
43 |
44 | ## Blockchain definition
45 |
46 | The first step to add a blockchain is to define its coin configuration. Add the definition to the `registry.json` file.
47 | Consult a similar blockchain (or simply copy & modify).
48 |
49 | The fields are documented here: https://github.com/trustwallet/wallet-core/blob/master/docs/registry-fields.md.
50 |
51 | ## Skeleton generation
52 |
53 | Execute the command `cd codegen-v2 && cargo run -- new-blockchain `, where `` is the ID of the new coin from `registry.json`.
54 | This will generate the following files, crates and structures:
55 | - `src/proto/.proto` - Blockchain Protobuf interface.
56 | - `rust/chains/tw_` - Rust crate that will contain all necessary code related to the new blockchain.
57 | - `rust/tw_any_coin/tests/chains/tw_` - Rust integration tests.
58 | - `src//Entry.h` - Intermediate layer between an end-user app and the Rust codebase.
59 | - `BlockchainType::` - Rust enum variant and its dispatching within the `rust/tw_coin_registry` crate.
60 | - `TWBlockchain` and `TWCoinType` - C++ enum variants.
61 | - `tests/chains/` - C++ integration tests.
62 |
63 | Run `tools/generate-files` to generate message proto files.
64 |
65 | Run `cmake` to include the new files in the build (`cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug`), and build the project.
66 |
67 | ## Definition tests, first commit
68 |
69 | Review tests in `tests/chains//TWCoinTypeTests.cpp` (where `X` is the name of the blockchain), exactly as in other blockchains.
70 | Run `cd rust && cargo check --tests` and `make -Cbuild -j12 tests TrezorCryptoTests` to check if Rust and C++ compile successfully.
71 |
72 | You should create a commit with this change, \(but don't create a pull request yet\).
73 |
74 | _Note:_ don't forget to add new files to git.
75 | _Note:_ don't forget to re-run `cmake` before building, to include new files in the build.
76 |
77 | ## Rust implementation
78 |
79 | Implement the required functionality in Rust. The code should be placed in the `rust/chains/tw_` folder.
80 |
81 | Don't just dump an existing codebase in the repo. The code needs to follow the code style and use existing hashing and cryptographic functionality if possible.
82 | Adding new dependencies is something we want to avoid as much as possible. We want to keep the codebase and the binary library as small as we can.
83 |
84 | If you do need to add a new cryptographic function or other building block please do so as a separate PR from the blockchain implementation.
85 |
86 | ### Entry point for coin functionality
87 |
88 | The Rust's `Entry` structure implements the [CoinEntry](https://github.com/trustwallet/wallet-core/blob/dev/rust/tw_coin_entry/src/coin_entry.rs) trait that is responsible for address management and the transaction signing.
89 | It should be kept minimal, have no logic, just call into relevant Address, Signer, etc. classes.
90 | Ensure that it fits well with the existing infrastructure and conventions.
91 |
92 | _Note:_ Do not forget to implement trait methods and declare associated types similar to [tw_ethereum/entry.rs](https://github.com/trustwallet/wallet-core/blob/dev/rust/tw_ethereum/src/entry.rs).
93 |
94 | ### Address encoding/decoding
95 |
96 | The first step is to support the address format specific to the blockchain. Start with the generated source files `rust/chains/X/src/address.rs` (where `X` is the blockchain name).
97 |
98 | At minimum the address needs a string validation static method, a string constructor, a constructor from a public key, and a method to convert back to a string.
99 | Make sure you can parse a string representation of an address and detect invalid addresses. Write unit tests for this. Also make sure that you can derive an address string from a private key. Write unit tests for this as well.
100 |
101 | For an example of this have a look at Ethereum [address.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_evm/src/address.rs).
102 |
103 | Make sure the dispatcher of address validation and derivation in `rust/chains/tw_/src/entry.rs` is also extended.
104 |
105 | ### Transaction signing
106 |
107 | The second step is supporting signing of transactions. Work on the `rust/chains/tw_/src/signer.rs` source file.
108 | Make sure you can generate a valid signature and a valid signed and encoded transaction. Write a unit tests for this.
109 |
110 | For an example of this have a look at Aptos's [signer.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_aptos/src/signer.rs).
111 |
112 | ### Unit Tests
113 |
114 | Unit tests are used to test public and non-public, usually, a single structure, method or function.
115 | Rust allows to test non-public identities straightforward.
116 | Unit tests can be placed in any Rust source file (under the `#[cfg(test)]` attribute) or in a test file under the `rust/chains/tw_/tests` directory.
117 | _Note:_ All Rust code needs to be unit tested.
118 |
119 | For an example of this have a look at Ethereum's Unit tests: [tw_evm/tests/signer.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_evm/tests/signer.rs) and [tw_evm/src/address.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_evm/src/address.rs).
120 |
121 | The Rust implementation with tests should be a separate commit.
122 |
123 | ### Rust Integration Tests
124 |
125 | Integration tests are used to test if the blockchain implementation can be accessed through the `TWAnySigner`, `TWAnyAddress`, ... public interfaces.
126 | They should be placed in the `rust/tw_any_coin/tests/chains/` directory.
127 |
128 | Usually you don't need to change the generated FFI interfaces, those interfaces are made as small as possible so that clients don't need to worry about implementation details.
129 |
130 | For an example of this have a look at Cosmos's Integration tests: [cosmos_address.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_any_coin/tests/chains/cosmos/cosmos_address.rs), [cosmos_sign.rs](https://github.com/trustwallet/wallet-core/blob/master/rust/tw_any_coin/tests/chains/cosmos/cosmos_sign.rs).
131 |
132 | ## C++ routing
133 |
134 | At this moment, every blockchain implemented in Rust must be routed through an intermediate C++ layer.
135 | The `src/X/Entry.h` is generated the way, so it passes requests to sign transactions, generate or validate addresses to Rust through FFI. So it can be considered as a bridge between an end-user app and the Rust codebase.
136 | _Note:_ FFI forwarding is derived from the `src/rust/RustCoinEntry` base class.
137 | _Note:_ Currently, blockchains in Rust do not support JSON signing as it is deprecated and will be removed in the future. Instead, if the blockchain should support JSON signing, consider overriding `RustCoinEntry::signJSON` method as in Ethereum: [src/Ethereum/Entry.h](https://github.com/trustwallet/wallet-core/blob/master/src/Ethereum/Entry.cpp).
138 |
139 | ### C++ Integration Tests
140 |
141 | Once you are satisfied with your Rust implementation, time to write some tests for C interface.
142 | C++ integration tests can help us to ensure if the Rust functionality is routed correctly, and available to be used by end-user apps.
143 |
144 | ## Mobile Integration Tests
145 |
146 | It is also required to test the interface on Android, iOS.
147 | Run `./codegen/bin/newcoin-mobile-tests ` to generate mobile integration tests:
148 | - `android/app/src/androidTest/java/com/trustwallet/core/app/blockchains/foobar/TestAddress.kt` - Address integration tests.
149 | - `android/app/src/androidTest/java/com/trustwallet/core/app/blockchains/foobar/TestSigner.kt` - Signing integration tests.
150 | - `swift/Tests/Blockchains/Tests.swift` - Address, signing and compiling integration tests.
151 |
152 | ## Blockchain checklist
153 |
154 | The above steps are summarized below as a checklist:
155 |
156 | - [ ] Coin Definition:
157 | - [ ] Add the coin definition to `registry.json`.
158 | - [ ] Execute `pushd codegen-v2 && cargo run -- new-blockchain && popd` to generate blockchain skeleton and configure integration tests.
159 | - [ ] Execute `tools/generate-files`.
160 | - [ ] Execute `pushd rust && cargo check --tests && popd` to check if Rust codebase compiles successfully.
161 | - [ ] Execute `make -Cbuild -j12 tests TrezorCryptoTests` to check if C++ codebase compiles successfully.
162 | - [ ] Add relevant constants in `Curve`, `Hasher` etc., in C++ and Rust, as necessary.
163 | - [ ] Implement functionality in Rust.
164 | - [ ] Entry at `rust/chains/tw_/src/entry.rs`.
165 | - [ ] Address at `rust/chains/tw_/src/address.rs`.
166 | - [ ] Transaction \(if necessary\) at `rust/chains/tw_/src/transaction.rs`.
167 | - [ ] Signer at `rust/chains/tw_/src/signer.rs`.
168 | - [ ] Compiler at `rust/chains/tw_/src/compiler.rs`.
169 | - [ ] Write unit tests. Put them in the `rust/chains/tw_/tests` directory.
170 | - [ ] Write Rust integration tests. Put them in a subfolder of `rust/tw_any_coin/tests/chains/`
171 | - [ ] Transaction signing tests, at least one mainnet transaction test.
172 | - [ ] Add stake, unstake, get rewards tests if the blockchain is PoS like.
173 | - [ ] Write C++ integration tests. Put them in a subfolder of `tests/chains/`.
174 | - [ ] Validate generated code in Android an iOS projects. Write integration tests for each.
175 | - [ ] Extend central derivation and validation tests: make sure the following tests are extended with the new coin: `CoinAddressDerivationTests.cpp` and
176 | `coin_address_derivation_test.rs`,
177 | `CoinAddressValidationTests.cpp`,
178 | `TWHRPTests.cpp`,
179 | `CoinAddressDerivationTests.kt`,
180 | `CoinAddressDerivationTests.swift`.
181 |
182 | - [ ] Upload coin icon to [trustwallet/assets](https://github.com/trustwallet/assets/#how-to-add-asset) if necessary.
183 |
184 | ### Bitcoin forks checklist
185 |
186 | If you're adding a Bitcoin fork, you might not neeed to implement new Address or Signer class, please complete this checklist before you submit a pull request:
187 |
188 | - [ ] Derive address according to definition in `registry.json`, `p2pkh` address for `bip44` or native `bech32` segwit address for `bip84`.
189 | - [ ] Check [SLIP-0132 :Registered HD version bytes](https://github.com/satoshilabs/slips/blob/master/slip-0132.md).
190 | - [ ] Check fee preference, use static fee or not, Trust will use fee that can be confirmed with in 2 blocks.
191 | - [ ] Add tests to validate all possible addresses, `p2pkh`, `p2sh` and `bech32`.
192 | - [ ] Add tests to derive `xpub` / `xprv` and cross check the values with other wallets, like ledger or trezor.
193 | - [ ] Add tests to derive address from `xpub` at random index.
194 | - [ ] Add tests to cover lock scripts for all addresses.
195 | - [ ] Add tests to make sure transaction detail url in block explorer is correct.
196 | - [ ] Add a mainnet transaction test, you can construct it by using wallet core and validate it by broadcasting it.
197 |
--------------------------------------------------------------------------------
/wallet-core/newevmchain.md:
--------------------------------------------------------------------------------
1 | # Adding an EVM Chain
2 |
3 | Adding support for a new fully EVM-compatible chain to Wallet Core requires only a few changes, follow the steps here.
4 | For more complex chain integrations, see [general new blockchain docs](newblockchain.md).
5 |
6 | ## Prerequisties / Needed information
7 |
8 | - `ChainID`. EVM chains have a unique ChainID, such as `8217`.
9 | - `Derivation path` used. Most EVM chains use Ethereum derivation path, `"m/44'/60'/0'/0/0"` (but not all).
10 | - `CoinID`. Most EVM chains do not have a SLIP 44 CoinID, but some do. We'll see below what to use if one is not available.
11 |
12 | ## Steps
13 |
14 | - Start with an up-to-date workspace ([more info](contributing.md)).
15 | - Add chain information to `registry.json`. Some notable fields:
16 | - blockchain: "Ethereum",
17 | - coinId: If own coinID is available, use that. Otherwise, use: `10000000 + chainID`, such as `10008217`.
18 | - Run `cd codegen-v2 && cargo run -- new-evmchain ` to generate template source files, where is the chain `id` from registry.
19 | - The result will be a new line in `TWCoinType.h` and a new test file `tests//TWCoinTypeTests.cpp`.
20 | - There are some test cases test derivation for all coins. Extend these with the new chain.
21 | If the new chain reuses Ethereum address, it can reuse the Ethereum case in the switch statements.
22 |
23 | ```
24 | rust/tw_any_coin/tests/coin_address_derivation_test.rs
25 | tests/common/CoinAddressDerivationTests.cpp
26 | android/app/src/androidTest/java/com/trustwallet/core/app/blockchains/CoinAddressDerivationTests.kt
27 | kotlin/wallet-core-kotlin/src/commonTest/kotlin/com/trustwallet/core/test/CoinAddressDerivationTests.kt
28 | swift/Tests/CoinAddressDerivationTests.swift
29 | ```
30 |
31 | - Update generated sources, build the project, execute unit tests (see [building](building.md)):
32 |
33 | ```
34 | ./tools/build-and-test
35 | ```
36 |
37 | - If all is fine, create a PR with the changes.
38 |
39 | ## Some Sample PRs:
40 |
41 | - [github.com/trustwallet/wallet-core/pull/2307](https://github.com/trustwallet/wallet-core/pull/2307)
42 | - [github.com/trustwallet/wallet-core/pull/2157](https://github.com/trustwallet/wallet-core/pull/2157)
43 |
--------------------------------------------------------------------------------
/wallet-core/releasing.md:
--------------------------------------------------------------------------------
1 | # Releasing
2 |
3 | Before releasing please update the version numbers in `android/gradle.properties` and `TrustWalletCore.podspec` and commit this change. Then create a new git tag for that number and push \(replace 0.0.0 with the actual version number\):
4 |
5 | ```text
6 | git tag 0.0.0
7 | git push
8 | git push origin 0.0.0
9 | ```
10 |
11 | ## iOS
12 |
13 | Run `bootstrap.sh` then `tools/ios-release`. This will build, archive and upload a Cocoapod. You need to be registered as an owner for the pod.
14 |
15 | ## Android
16 |
17 | Run `bootstrap.sh` then `tools/android-release`. This will build and upload to [Bintray](https://bintray.com/trust/wallet-core/com.trustwallet.wallet-core) and [JFrog](https://oss.jfrog.org/webapp/#/home).
18 |
19 | You need to have this credentials as environment variables in order to upload to Bintray
20 |
21 | ```text
22 | BINTRAY_USER=user
23 | BINTRAY_KEY=key
24 | ```
25 |
26 | ## Docker Hub
27 |
28 | We need to release a new prebuilt Docker image every time our dependencies or sources change.
29 | To build the docker image(s), see `tools/docker-build`. Use `docker push` to upload to Docker Hub.
30 |
--------------------------------------------------------------------------------
/wallet-core/rpc-requirements.md:
--------------------------------------------------------------------------------
1 | # RPC / API Requirements
2 |
3 | Trust Wallet is a light client wallet, which means it needs to get data / information from remote nodes (either light nodes or full nodes). In order to integrate your blockchain into Trust Wallet smoothly, you must also fulfill RPC / API requirements. We list all needed APIs or RPCs plus an example below for your reference.
4 |
5 | ## for Trust Wallet:
6 |
7 | We need API or RPC to:
8 |
9 | - [ ] query account / address balance
10 | - [ ] query transaction details
11 | - [ ] query fee / nonce for sending transaction
12 | - [ ] query blockchain status (block height etc)
13 | - [ ] send raw transaction
14 |
15 | ## for Backend:
16 |
17 | Used to create transaction list index and notify users about incoming/outgoing transactions.
18 |
19 | - [ ] query transactions in a block
20 |
21 | ## Example
22 |
23 | We will take XRP as an example here, it supports WebSocket, JSON-RPC (including over HTTP)
24 |
25 | ### Query account / address balance:
26 |
27 | - [x] JSON RPC method: `account_info` (https://xrpl.org/account_info.html)
28 |
29 | ### Query transaction details:
30 |
31 | - [x] JSON RPC method: `tx` (https://xrpl.org/tx.html)
32 |
33 | ### Query fee / nonce for sending transaction:
34 |
35 | - [x] fee: JSON RPC method: `fee` (https://xrpl.org/fee.html)
36 | - [x] nonce: same as `account_info`, you can find `Sequence` in response.
37 |
38 | ### Query blockchain status (block height etc):
39 |
40 | - [x] JSON RPC method: `server_state` (https://xrpl.org/server_state.html)
41 |
42 | ### Send raw transaction:
43 |
44 | - [x] JSON RPC method: `submit` (https://xrpl.org/submit.html)
45 |
46 | ### Query sent / received transactions for an account / address:
47 |
48 | - [x] REST API: https://xrpl.org/data-api.html#get-account-transaction-history
49 |
50 | ### Query transactions in a block:
51 |
52 | - [x] REST API: https://xrpl.org/data-api.html#get-ledger
53 |
--------------------------------------------------------------------------------
/wallet-core/server-side.md:
--------------------------------------------------------------------------------
1 | # Server-Side Guide
2 |
3 | If your server application (most likely on Linux) language supports [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) to C, it is possible to call wallet core.
4 |
5 | ## Golang
6 |
7 | Here is a step by step example of [cgo](https://golang.org/cmd/cgo/), using Wallet Core docker image.
8 |
9 | 1. Run `docker run -it trustwallet/wallet-core`
10 | The librabry is already built in this image (Build instructions [here](building.md)) Note: may not be the most recent version.
11 |
12 | 2. Install go: `apt-get update && apt-get install golang`
13 | (or download from here [go1.13.3](https://dl.google.com/go/go1.13.3.linux-amd64.tar.gz), configure `GOROOT` and append `GOROOT/bin` to `PATH`).
14 | 3. Save the sample code below to file called `main.go`
15 |
16 | ```go
17 | package main
18 |
19 | // #cgo CFLAGS: -I/wallet-core/include
20 | // #cgo LDFLAGS: -L/wallet-core/build -L/wallet-core/build/trezor-crypto -lTrustWalletCore -lprotobuf -lTrezorCrypto -lc++ -lm
21 | // #include
22 | // #include
23 | // #include
24 | // #include
25 | // #include
26 | // #include
27 | import "C"
28 |
29 | import "fmt"
30 | import "unsafe"
31 | import "encoding/hex"
32 |
33 | // C.TWString -> Go string
34 | func TWStringGoString(s unsafe.Pointer) string {
35 | return C.GoString(C.TWStringUTF8Bytes(s))
36 | }
37 |
38 | // Go string -> C.TWString
39 | func TWStringCreateWithGoString(s string) unsafe.Pointer {
40 | cStr := C.CString(s)
41 | defer C.free(unsafe.Pointer(cStr))
42 | str := C.TWStringCreateWithUTF8Bytes(cStr)
43 | return str
44 | }
45 |
46 | // C.TWData -> Go byte[]
47 | func TWDataGoBytes(d unsafe.Pointer) []byte {
48 | cBytes := C.TWDataBytes(d)
49 | cSize := C.TWDataSize(d)
50 | return C.GoBytes(unsafe.Pointer(cBytes), C.int(cSize))
51 | }
52 |
53 | // Go byte[] -> C.TWData
54 | func TWDataCreateWithGoBytes(d []byte) unsafe.Pointer {
55 | cBytes := C.CBytes(d)
56 | defer C.free(unsafe.Pointer(cBytes))
57 | data := C.TWDataCreateWithBytes((*C.uchar)(cBytes), C.ulong(len(d)))
58 | return data
59 | }
60 |
61 | func main() {
62 | fmt.Println("==> calling wallet core from go")
63 | str := TWStringCreateWithGoString("confirm bleak useless tail chalk destroy horn step bulb genuine attract split")
64 | emtpy := TWStringCreateWithGoString("")
65 | defer C.TWStringDelete(str)
66 | defer C.TWStringDelete(emtpy)
67 |
68 | fmt.Println("<== mnemonic is valid: ",C.TWMnemonicIsValid(str))
69 |
70 | wallet := C.TWHDWalletCreateWithMnemonic(str, emtpy)
71 | defer C.TWHDWalletDelete(wallet)
72 |
73 | key := C.TWHDWalletGetKeyForCoin(wallet, C.TWCoinTypeBitcoin)
74 | keyData := C.TWPrivateKeyData(key)
75 | keyHex := hex.EncodeToString(TWDataGoBytes(keyData))
76 | fmt.Println("<== bitcoin private key: ", keyHex)
77 |
78 | pubKey, _ := hex.DecodeString("0288be7586c41a0498c1f931a0aaf08c15811ee2651a5fe0fa213167dcaba59ae8")
79 | pubKeyData := TWDataCreateWithGoBytes(pubKey)
80 | defer C.TWDataDelete(pubKeyData)
81 |
82 | fmt.Println("<== bitcoin public key is valid: ", C.TWPublicKeyIsValid(pubKeyData, C.TWPublicKeyTypeSECP256k1))
83 |
84 | address := C.TWHDWalletGetAddressForCoin(wallet, C.TWCoinTypeBitcoin)
85 | fmt.Println("<== bitcoin address: ", TWStringGoString(address))
86 | }
87 | ```
88 |
89 | 4. Compile it by `go build -o main`
90 | 5. Run `./main` and you will see the output below:
91 |
92 | ```shell
93 | ==> calling wallet core from go
94 | <== mnemonic is valid: true
95 | <== bitcoin private key: 945f423798858e24aa1ab490648013db63ad1f539ebbb8cb1399edd1d0b59716
96 | <== bitcoin public key is valid: true
97 | <== bitcoin address: bc1qw29x4hrt6tahz4jvuhzrq6y5el3spqt499zuay
98 | ```
99 |
100 | 6. You might want to copy and run `main` outside of the docker container, make sure you have `libc++1` and `libc++abi1` installed in your host Ubuntu.
101 |
102 | ## Node.js
103 |
104 | 1. Install from NPM or GPR
105 |
106 | ```shell
107 | npm install @trustwallet/wallet-core
108 | ```
109 |
110 | 2. Check [tests](https://github.com/trustwallet/wallet-core/tree/master/wasm/tests) for API usage
111 |
--------------------------------------------------------------------------------
/wallet-core/wallet-core-usage.md:
--------------------------------------------------------------------------------
1 | # Wallet Core Usage Guide
2 |
3 | We present here an overview of the basic wallet operations. Language-specific samples are provided in step-by-step [guides](integration-guide.md).
4 |
5 | The covered basic operations are:
6 |
7 | - Wallet management
8 | - Creating a new multi-coin wallet
9 | - Importing a multi-coin wallet
10 | - Address derivation (receiving)
11 | - Generating the default address for a coin
12 | - Generating an address using a custom derivation path (expert)
13 | - Transaction signing (e.g. for sending)
14 |
15 | For the examples we use _Bitcoin_, _Ethereum_ and _Binance Coin_ as sample coins/blockchains.
16 |
17 | Note: Wallet Core does not cover communication with blockchain networks (nodes):
18 | address derivation is covered, but address balance retrieval not;
19 | transaction signing is covered, but broadcasting transactions to the network not.
20 |
21 | In this guide we use small code examples from a Swift sample application, but the focus is on the explanations.
22 |
23 | ## Wallet Management
24 |
25 | ### Multi-Coin Wallet
26 |
27 | The Multi-Coin Wallet is a structure allowing accounts for many coins, all controlled by a single recovery phrase.
28 | It is a standard HD Wallet (Hierarchically Derived), employing the standard derivation schemes, interoperable with many other wallets:
29 | **BIP39** for recovery phrase, **BIP44**/**BIP84** for account derivation.
30 |
31 | ### Creating a New Multi-Coin Wallet
32 |
33 | When a new wallet is created, a new seed (and thus recovery phrase) is chosen at random.
34 | _After creation, the user has to be informed and guided to backup the recovery phrase._
35 |
36 | The random generation employs secure random generation, as available on the device.
37 |
38 | ```swift
39 | let wallet = HDWallet(strength: 128, passphrase: "")
40 | ```
41 |
42 | | Input parameter | Description |
43 | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44 | | _strength_ | The strength of the secret seed. Higher seed means more information content, longer recovery phrase. Default value is **128**, but 256 is also possible. |
45 | | _passphrase_ | Optional passphrase, used to scramble the seed. If specified, the wallet can be imported and opened only with the passphrase (Not to be confused with recovery phrase). |
46 |
47 | ### Importing a Multi-Coin Wallet
48 |
49 | A previously created wallet can be imported using the recovery phrase. Typical usecases for import are:
50 |
51 | - re-importing a wallet later, into a later installation, or
52 | - importing into another device, or
53 | - importing into another wallet app.
54 |
55 | If the wallet was created with a passphrase, it is also required.
56 |
57 | ```swift
58 | let wallet = HDWallet(mnemonic: "ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", passphrase: "")
59 | ```
60 |
61 | | Input parameter | Description |
62 | | --------------- | ----------------------------------------------------------------------------------------- |
63 | | _mnemonic_ | a.k.a. _recovery phrase_. The string of several words that was used to create the wallet. |
64 | | _passphrase_ | Optional passphrase, used to encrypt the seed. |
65 |
66 | ## Account Address Derivation
67 |
68 | Each coin needs a different account, with matching address. Addresses are derived from the multi-coin wallet.
69 | Derivation is based on a _derivation path_, which is unique for each coin, but can have other parameters as well.
70 | Each coin has a default derivation path, such as `"m/84'/0'/0'/0/0"` for Bitcoin and `"m/44'/60'/0'/0/0"` for Ethereum.
71 |
72 | ### Generating the Default Address for a Coin
73 |
74 | The simplest is to get the default address for a coin -- this requires no further inputs.
75 | The address is generated using the default derivation path of the coin.
76 |
77 | For example, the default BTC address, derived for the wallet with the mnemonic shown above, with the default BTC derivation path (`m/84'/0'/0'/0/0`) is:
78 | `bc1qpsp72plnsqe6e2dvtsetxtww2cz36ztmfxghpd`.
79 | For Ethereum, this is `0xA3Dcd899C0f3832DFDFed9479a9d828c6A4EB2A7`.
80 |
81 | Here is the sample code fort obtaining the default address for different coins:
82 |
83 | ```swift
84 | let addressBTC = wallet.getAddressForCoin(coin: .bitcoin)
85 | let addressETH = wallet.getAddressForCoin(coin: .ethereum)
86 | let addressBNB = wallet.getAddressForCoin(coin: .binance)
87 | ```
88 |
89 | ### Generating an Address Using a Custom Derivation Path (Expert)
90 |
91 | It is also possible to derive addresses using custom derivation paths.
92 | This can be done in two steps: first a derived private key is obtained, then an address from it.
93 |
94 | > **Warning**: use this only if you are well aware of the semantics of the derivation path used!
95 |
96 | > **Security Warning**: if secrets such as private keys are handled by the wallet, even if for a short time, handle with care!
97 | > Avoid any risk of leakage of secrets!
98 |
99 | ```swift
100 | let key = wallet.getKey(derivationPath: "m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0
101 | let address = CoinType.ethereum.deriveAddress(privateKey: key)
102 | ```
103 |
104 | For example, a second Ethereum address can be derived using the custom derivation path `”m/44'/60’/1’/0/0”` (note the 1 in the third position),
105 | yielding address `0x68eF4e5660620976a5968c7d7925753D3Cc40809`.
106 |
107 | ## Transaction Signing
108 |
109 | In general, when creating a new blockchain transaction, a wallet has to:
110 |
111 | 1. Put together a transaction with relevant fields (source, target, amount, etc.)
112 | 2. Sign the transaction, using the account private key. This is done by Wallet Core.
113 | 3. Send to a node for broadcasting to the blockchain network.
114 |
115 | The exact fields needed for a transaction are different for each blockchain.
116 | In Wallet Core, signing input and output parameters are typically represented in a protobuf message
117 | (internally needed for serialization for passing through different language runtimes).
118 |
119 | A generic, coin-independent signer also exists (_AnySigner_), but its usage is recommended only in browser-based applications.
120 |
121 | ### Bitcoin Transaction Signing
122 |
123 | Bitcoin is the first `UTXO` (Unspent Transaction Output) based cryptocurrency / blockchain, if you haven't read the documentation about Bitcoin, we highly recommend you to read [developer glossary](https://bitcoin.org/en/developer-glossary) and [raw transaction format](https://bitcoin.org/en/developer-reference#raw-transaction-format), these will help you understand how to sign a Bitcoin transaction. Wallet Core supports _Bitcoin_, _Bitcoin Cash_, _Zcash_, _Decred_ and a few forks.
124 |
125 | The most important models in Swift are `BitcoinSigningInput` and `BitcoinUnspentTransaction`
126 |
127 | _BitcoinSigningInput_
128 |
129 | | Field | Sample value | Description |
130 | | ------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
131 | | hash_type | BitcoinSigHashType.all | _Bitcoin Cash_ needs to `or` with `TitcoinSigHashType.fork` (see [Sighash](https://bitcoin.org/en/glossary/signature-hash) for more details) |
132 | | amount | 10000 | Amount (in satoshi) to send (value of new UTXO will be created) |
133 | | byteFee | 1 | Transaction fee is `byte_fee x transaction_size`, Wallet Core will calculate the fee for you by default |
134 | | toAddress | bc1q03h6k5lt6pzfjaanz5mlnmuc7aha2t3nkz7gh0 | Recipient address (Wallet Core will build lock script for you) |
135 | | changeAddress | 1AC4gh14wwZPULVPCdxUkgqbtPvC92PQPN | Address to receive changes, can be empty if you sweep a wallet |
136 | | privateKey | [Data(...), Data(...)] | Private keys for all the input UTXOs in this transaction |
137 | | scripts | [`script_hash`: Data(...)] | Redeem scripts indexed by script hash, usually for `P2SH`, `P2WPKH` or `P2WSH` |
138 | | utxo | [*BitcoinUnspentTransaction*] | All the input UTXOs, see below table for more details |
139 | | useMaxAmount | false | Consume all the input UTXOs, it will affect fee estimation and number of output |
140 | | coinType | 145 | [SLIP44 Index](https://github.com/trustwallet/wallet-core/blob/master/docs/registry.md) coin type, default is 0 / Bitcoin |
141 |
142 | _BitcoinUnspentTransaction_
143 |
144 | | Field | Sample value | Description |
145 | | -------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
146 | | outPoint | _BitcoinOutPoint(hash:index:)_ | Refer to a particular transaction output, consisting of a 32-byte TXID and a 4-byte output index number (vout) |
147 | | amount | 10000 | A value field for transferring zero or more satoshis |
148 | | script | 0x76a9146cfa0e96c34fce09c0e4e671fcd43338c14812e588ac | A script (ScriptPubKey) included in outputs which sets the conditions that must be fulfilled for those satoshis to be spent |
149 |
150 | Here is the Swift sample code for signing a real world Bitcoin Cash [transaction](https://blockchair.com/bitcoin-cash/transaction/96ee20002b34e468f9d3c5ee54f6a8ddaa61c118889c4f35395c2cd93ba5bbb4)
151 |
152 | ```swift
153 | let utxoTxId = Data(hexString: "050d00e2e18ef13969606f1ceee290d3f49bd940684ce39898159352952b8ce2")! // latest utxo for sender, "txid" field from blockbook utxo api: https://github.com/trezor/blockbook/blob/master/docs/api.md#get-utxo
154 | let privateKey = PrivateKey(data: Data(hexString: "7fdafb9db5bc501f2096e7d13d331dc7a75d9594af3d251313ba8b6200f4e384")!)!
155 | let address = CoinType.bitcoinCash.deriveAddress(privateKey: privateKey)
156 |
157 | let utxo = BitcoinUnspentTransaction.with {
158 | $0.outPoint.hash = Data(utxoTxId.reversed()) // reverse of UTXO tx id, Bitcoin internal expects network byte order
159 | $0.outPoint.index = 2 // outpoint index of this this UTXO, "vout" field from blockbook utxo api
160 | $0.outPoint.sequence = UINT32_MAX
161 | $0.amount = 5151 // value of this UTXO, "value" field from blockbook utxo api
162 | $0.script = BitcoinScript.lockScriptForAddress(address: address, coin: .bitcoinCash).data // Build lock script from address or public key hash
163 | }
164 |
165 | let input = BitcoinSigningInput.with {
166 | $0.hashType = BitcoinScript.hashTypeForCoin(coinType: .bitcoinCash)
167 | $0.amount = 600
168 | $0.byteFee = 1
169 | $0.toAddress = "1Bp9U1ogV3A14FMvKbRJms7ctyso4Z4Tcx"
170 | $0.changeAddress = "1FQc5LdgGHMHEN9nwkjmz6tWkxhPpxBvBU" // can be same sender address
171 | $0.utxo = [utxo]
172 | $0.privateKey = [privateKey.data]
173 | }
174 |
175 | let output: BitcoinSigningOutput = AnySigner.sign(input: input, coin: .bitcoinCash)
176 | guard output.error.isEmpty else { return }
177 | // encoded transaction to broadcast
178 | print(output.encoded)
179 | ```
180 |
181 | It's worth to note that you can also calcuate fee and change manually (by using a `BitcoinTransactionPlan` struct)
182 | Below is another real world Zcash [transparent transaction](https://explorer.zcha.in/transactions/ec9033381c1cc53ada837ef9981c03ead1c7c41700ff3a954389cfaddc949256) demonstrate this
183 |
184 | ```swift
185 | let utxos = [
186 | BitcoinUnspentTransaction.with {
187 | $0.outPoint.hash = Data(hexString: "53685b8809efc50dd7d5cb0906b307a1b8aa5157baa5fc1bd6fe2d0344dd193a")!
188 | $0.outPoint.index = 0
189 | $0.outPoint.sequence = UINT32_MAX
190 | $0.amount = 494000
191 | $0.script = Data(hexString: "76a914f84c7f4dd3c3dc311676444fdead6e6d290d50e388ac")!
192 | }
193 | ]
194 |
195 | let input = BitcoinSigningInput.with {
196 | $0.hashType = BitcoinSigHashType.all.rawValue
197 | $0.amount = 488000
198 | $0.toAddress = "t1QahNjDdibyE4EdYkawUSKBBcVTSqv64CS"
199 | $0.coinType = CoinType.zcash.rawValue
200 | $0.privateKey = [Data(hexString: "a9684f5bebd0e1208aae2e02bc9e9163bd1965ad23d8538644e1df8b99b99559")!]
201 | $0.plan = BitcoinTransactionPlan.with {
202 | $0.amount = 488000
203 | $0.fee = 6000
204 | $0.change = 0
205 | // Sapling branch id
206 | $0.branchID = Data(hexString: "0xbb09b876")!
207 | $0.utxos = utxos
208 | }
209 | }
210 |
211 | let output: BitcoinSigningOutput = AnySigner.sign(input: input, coin: .zcash)
212 |
213 | // encoded transaction to broadcast
214 | print(output.encoded)
215 | ```
216 |
217 | Besides [orignal Bitcoin RPC](https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list), there are many other APIs / block explorer can get UTXO and broadcast raw transaction, like: insight api, trezor blockbook, blockchain com, blockchair api.
218 |
219 | ### Ethereum Transaction Signing
220 |
221 | A simple Ethereum send transaction needs the following fields:
222 |
223 | | Field | Sample value | Description |
224 | | -------- | --------------- | ----------------------------------------------------------------------------------------- |
225 | | chainID | 1 | Network selector, use 1 for mainnet (see https://chainid.network for more) |
226 | | nonce | 1 | The count of the number of outgoing transactions, starting with 0 |
227 | | gasPrice | 3600000000 | The price to determine the amount of ether the transaction will cost |
228 | | gasLimit | 21000 | The maximum gas that is allowed to be spent to process the transaction |
229 | | to | <address> | The account the transaction is sent to, if empty, the transaction will create a contract |
230 | | value | 100000000 | The amount of ether to send |
231 | | data | | Could be an arbitrary message or function call to a contract or code to create a contract |
232 |
233 | Several parameters, like the current nonce and gasPrice values can be obtained from Ethereum node RPC calls (see https://github.com/ethereum/wiki/wiki/JSON-RPC, e.g., _eth_gasPrice_).
234 |
235 | Code example to fill in the signer input parameters:
236 |
237 | ```swift
238 | let input = EthereumSigningInput.with {
239 | $0.chainID = Data(hexString: "01")!
240 | $0.gasPrice = Data(hexString: "d693a400")! // decimal 3600000000
241 | $0.gasLimit = Data(hexString: "5208")! // decimal 21000
242 | $0.toAddress = "0xC37054b3b48C3317082E7ba872d7753D13da4986"
243 | $0.transaction = EthereumTransaction.with {
244 | $0.transfer = EthereumTransaction.Transfer.with {
245 | $0.amount = Data(hexString: "0348bca5a16000")!
246 | }
247 | }
248 | $0.privateKey = wallet.getKeyForCoin(coin: .ethereum).data
249 | }
250 | ```
251 |
252 | Then Signer is invoked, and the signed and encoded output retrieved:
253 |
254 | ```swift
255 | let output: EthereumSigningOutput = AnySigner.sign(input: input, coin: .ethereum)
256 | print(" data: ", output.encoded.hexString)
257 | ```
258 |
259 | For more details on Ethereum transactions, check the Ethereum documentation. A few resources are here:
260 |
261 | - https://medium.com/@codetractio/inside-an-ethereum-transaction-fa94ffca912f
262 | - https://kauri.io/article/7e79b6932f8a41a4bcbbd194fd2fcc3a/v2/ethereum-101-part-4-accounts-transactions-and-messages
263 | - https://github.com/ethereumbook/ethereumbook/blob/develop/06transactions.asciidoc
264 |
265 | ### Binance Chain (BNB) Transaction Signing
266 |
267 | Binance Chain is built upon [cosmos-sdk](https://github.com/cosmos/cosmos-sdk), instead of `Message`, transaction in Binance Chain is called `Order`, [Binance.proto](https://github.com/trustwallet/wallet-core/blob/master/src/proto/Binance.proto#L144) shows all the orders that Wallet Core currently supports.
268 |
269 | To sign a order, you need to use `BinanceSigningInput`:
270 |
271 | | Field | Sample value | Description |
272 | | ------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273 | | chainID | Binance-Chain-Nile | Network id, use Binance-Chain-Tigris for mainnet (see [node-info](https://dex.binance.org/api/v1/node-info) api) |
274 | | accountNumber | 51 | On chain account number. (see [account](https://dex.binance.org/api/v1/account/bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m) api) |
275 | | sequence | 437412 | Order sequence starting from 0, always plus 1 for new order from [account](https://dex.binance.org/api/v1/account/bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m) api |
276 | | source | 0 | [BEP10](https://github.com/binance-chain/BEPs/blob/master/BEP10.md) source id |
277 | | sendOrder | <sendOrder> | SendOrder contains `inputs` and `outputs`, see below sample code for more details |
278 |
279 | A Swift sample code send order is shown below:
280 |
281 | ```swift
282 | let privateKey = PrivateKey(data: Data(hexString: "95949f757db1f57ca94a5dff23314accbe7abee89597bf6a3c7382c84d7eb832")!)!
283 | let publicKey = privateKey.getPublicKeySecp256k1(compressed: true)
284 |
285 | let token = BinanceSendOrder.Token.with {
286 | $0.denom = "BNB" // BNB or BEP2 token symbol
287 | $0.amount = 1 // Amount, 1 BNB
288 | }
289 |
290 | // A.k.a from / sender
291 | let orderInput = BinanceSendOrder.Input.with {
292 | $0.address = CosmosAddress(hrp: .binance, publicKey: publicKey)!.keyHash
293 | $0.coins = [token]
294 | }
295 |
296 | // A.k.a to / recipient
297 | let orderOutput = BinanceSendOrder.Output.with {
298 | $0.address = CosmosAddress(string: "bnb1hlly02l6ahjsgxw9wlcswnlwdhg4xhx38yxpd5")!.keyHash
299 | $0.coins = [token]
300 | }
301 |
302 | let input = BinanceSigningInput.with {
303 | $0.chainID = "Binance-Chain-Nile" // Testnet Chain id
304 | $0.accountNumber = 0 // On chain account number
305 | $0.sequence = 0 // Sequence number
306 | $0.source = 0 // BEP10 source id
307 | $0.privateKey = privateKey.data
308 | $0.memo = ""
309 | $0.sendOrder = BinanceSendOrder.with {
310 | $0.inputs = [orderInput]
311 | $0.outputs = [orderOutput]
312 | }
313 | }
314 |
315 | let output: BinanceSigningOutput = AnySigner.sign(input: input, coin: .binance)
316 | // encoded order to broadcast
317 | print(output.encoded)
318 | ```
319 |
320 | For more details please check the Binance Chain documentation:
321 |
322 | - https://docs.binance.org/encoding.html
323 | - https://docs.binance.org/api-reference/dex-api/paths.html#http-api
324 |
325 | Consult the complete sample applications for more details.
326 |
--------------------------------------------------------------------------------
/wallet-core/wallet-core.md:
--------------------------------------------------------------------------------
1 | # Wallet Core
2 |
3 | 
4 |
5 | ## Introduction
6 |
7 | Trust Wallet Core is a cross-platform library that implements low-level cryptographic wallet functionality for many blockchains. Most of the code is C++ with a set of strict exported C interfaces. The library provides idiomatic interfaces for all supported languages \(currently Swift for iOS and Java for Android\).
8 |
9 | ## Usage
10 |
11 | If you want to use wallet core in your project follow these instructions:
12 |
13 | - For building locally, or using Docker image, see the [Build Instructions](building.md).
14 | - For trying out, e.g. testing key management and address derivation, see the [WalletConsole utility](walletconsole.md).
15 | - If you want to include Wallet Core in your project, see the [Integration Guides](integration-guide.md).
16 | Start with the overview of the most common wallet operations ([Usage Guide](wallet-core-usage.md)),
17 | and see the platform-specifc guides for
18 | [iOS](ios-guide.md) and
19 | [Android](android-guide.md).
20 | - We have a [FAQ](faq.md) list may already answer some of your questions.
21 |
22 | ## Projects using Wallet Core -- Add yours here too!
23 |
24 | - [Trust Wallet](https://trustwallet.com)
25 | - [coinpaprika](https://coinpaprika.com/)
26 | - [IFWallet](https://www.ifwallet.com/)
27 | - [Alice](https://www.alicedapp.com/)
28 | - [Crypto.com](https://crypto.com)
29 | - [Frontier](https://frontier.xyz/)
30 | - [Belco](https://www.belcobtm.com/)
31 | - [Pumapay](https://pumapay.io/)
32 | - [Tokenary](https://tokenary.io/)
33 | - [MemesWallet](https://planetmemes.com/)
34 | - [xPortal](https://xportal.com/)
35 | - [Slingshot](https://slingshot.finance/)
36 | - [ECOIN Wallet](https://play.google.com/store/apps/details?id=org.ecoinwallet&pcampaignid=web_share)
37 |
38 | ## Contributing
39 |
40 | The best way to submit feedback and report bugs is to [open a GitHub issue](https://github.com/trustwallet/wallet-core/issues/new).
41 | If you want to contribute code please see [Contributing](contributing.md).
42 | If you want to add support for a new blockchain also see [Adding Support for a New Blockchain](newblockchain.md).
43 |
44 | Thanks to all the people who contribute.
45 |
46 |
47 | ## License
48 |
49 | Trust Wallet Core is available under the MIT license. See the [LICENSE](https://github.com/trustwallet/wallet-core/blob/master/LICENSE) file for more info.
50 |
--------------------------------------------------------------------------------
/wallet-core/walletconsole.md:
--------------------------------------------------------------------------------
1 | # WalletConsole utility
2 |
3 | The _Wallet Core_ library comes with an interactive command-line utility, for accessing key- and address management functionality of the library.
4 |
5 | ## Quick Start
6 |
7 | ```shell
8 | $ ./build/walletconsole/walletconsole
9 | Wallet-Core Console (c) TrustWallet
10 | Type 'help' for list of commands.
11 | > help
12 | Commands:
13 | . . .
14 | newKey Create new pseudo-random 32-byte key (secret!)
15 | . . .
16 | > coin btc
17 | Set active coin to: bitcoin
18 | > addrDefault
19 | Result: bc1q2kecrqfvzj7l6phet956whxkvathsvsgn7twav
20 | ```
21 |
22 | ## Starting
23 |
24 | The utility builds together with the library and can be started from: `build/walletconsole/walletconsole` .
25 | See [build instructions](building.md).
26 |
27 | Walletconsole can be also executed 'off the shelf' using the Docker image:
28 |
29 | ```shell
30 | docker run -i -t trustwallet/wallet-core /wallet-core/build/walletconsole/walletconsole
31 | ```
32 |
33 | ## Commands
34 |
35 | Here is a snapshot of the commands:
36 |
37 | ```shell
38 | Commands:
39 | exit Exit
40 | quit Exit
41 | help This help
42 | Inputs, buffer:
43 | # Take last result
44 | # Take nth previous result
45 | buffer Take buffer values
46 | Coins:
47 | coins List known coins
48 | coin Set active coin, selected by its ID or symbol or name
49 | Keys:
50 | newKey Create new pseudo-random 32-byte key (secret!)
51 | pubPri Derive public key from a secret private key (type is coin-dependent)
52 | priPub Derive private key from public key :)
53 | setMnemonic ... Set current mnemonic, several words (secret!)
54 | newMnemonic Create and store a new mnemonic, of strength (128 -- 256) (secret!)
55 | dumpSeed Dump the seed of the current mnemonic (secret!)
56 | dumpMnemonic Dump the current mnemonic (secret!)
57 | dumpDP Dump the default derivation path of the current coin (ex.: m/84'/0'/0'/0/0)
58 | priDP [] Derive a new private key for the coin, from the current mnemonic and given derivation path.
59 | If derivation path is missing, the default one is used (see dumpDP).
60 | Addresses:
61 | addrPub Create address from public key
62 | addrPri Create address from private key
63 | addr Check string address
64 | addrDefault Derive default address, for current coin, fom current mnemonic; see dumpDP
65 | addrDP Derive a new address with the given derivation path (using current coin and mnemonic)
66 | Coin-specific methods:
67 | tonInitMsg Build TON account initialization message.
68 | Transformations:
69 | hex Encode given string to hex
70 | base64Encode Encode given hex data to Base64
71 | base64Decode Decode given Base64 string to hex data
72 | File methods:
73 | fileW Write data to a (new) binary file.
74 | fileR Read data from a binary file.
75 | ```
76 |
77 | ## Examples
78 |
79 | Here are various sample usages.
80 |
81 | Create a new private key, derive a BTC address from it, write it to a file:
82 |
83 | ```shell
84 | > coin bitcoin
85 | Set active coin to: bitcoin Use 'coin' to change. (name: 'bitcoin' symbol: btc numericalid: 0)
86 | > newKey
87 | Result: 4e8c1773ce1ca447594fa23a445d9952236c7a15e96802b880aab4d918bdcfd9
88 | > addrPri #
89 | Result: bc1qvjf93nc80f3fu7j2ehqv6xw6zqa5cny32hl90y
90 | > fileW btcaddr.txt #
91 | Written to file 'btcaddr.txt', 21 bytes.
92 | ```
93 |
94 | Create a new private key, derive the public key from it, derive a BTC address from it:
95 |
96 | ```shell
97 | > newKey
98 | Result: ef8f76035c4d4dd29ed4bbe3fc7c0db45d81cd616f2ac8b038cb982bec2a63ad
99 | > pubPri #
100 | Result: 0381277ec943a6cd4033171da547bbe93585a8905fb3dad108e8e51e88a4e136ea
101 | > addrPub #
102 | Result: bc1qvf6gzfhcelpugw84ks677x5zuke46jm946dtpx
103 | ```
104 |
105 | Check an ALGO address for validity:
106 |
107 | ```shell
108 | > coin algo
109 | Set active coin to: algorand Use 'coin' to change. (name: 'algorand' symbol: algo numericalid: 283)
110 | > addr LCSUSBOLNVT6BND6DWWGM4DLVUYJN3PGBT4T7LTCMDMKS7TR7FZAOHOVPE
111 | Address is a valid algorand address: LCSUSBOLNVT6BND6DWWGM4DLVUYJN3PGBT4T7LTCMDMKS7TR7FZAOHOVPE
112 | ```
113 |
114 | Derive private keys using different BIP39 derivation paths, and create address from it:
115 |
116 | ```shell
117 | > coin btc
118 | Set active coin to: bitcoin Use 'coin' to change. (name: 'bitcoin' symbol: btc numericalid: 0)
119 | > dumpDP
120 | Result: m/84'/0'/0'/0/0
121 | > priDP
122 | Using derivation path "m/84'/0'/0'/0/0" for coin bitcoin
123 | Result: df6a78d65fe3c82f020c25be12debd46e58f5f4366381102485ce26c52416a96
124 | > priDP m/84'/0'/0'/0/1
125 | Using derivation path "m/84'/0'/0'/0/1" for coin bitcoin
126 | Result: 19c44359b4953bb3084dd73ba2854f6822de3b6f8f358055a16a1b19e533e37c
127 | > pubPri #
128 | Result: 02222d3889870d36e0c9e788c69a6509eddfb2105309e7733cfa669bb52ba996d1
129 | > addrPub #
130 | Result: bc1q7ghe6xyx38vdkzs9ryv3gz47mgvpa747z2mcvy
131 | > addr #
132 | Address is a valid bitcoin address: bc1q7ghe6xyx38vdkzs9ryv3gz47mgvpa747z2mcvy
133 | ```
134 |
135 | Derive several NANO addresses (BIP39):
136 |
137 | ```shell
138 | > coin nano
139 | Set active coin to: nano Use 'coin' to change. (name: 'nano' symbol: nano numericalid: 165)
140 | > dumpDP
141 | Result: m/44'/165'/0'
142 | > setMnemonic edge defense waste choose enrich upon flee junk siren film clown finish luggage leader kid quick brick print evidence swap drill paddle truly occur
143 | Mnemonic set (24 words).
144 | > addrDefault
145 | Result: nano_3yyipbgtnd7183k61nkh5mxnt9wpsfhto95mksdqj6s7p45mwj9osai7asad
146 | > addrDP m/44'/165'/0'
147 | Result: nano_3yyipbgtnd7183k61nkh5mxnt9wpsfhto95mksdqj6s7p45mwj9osai7asad
148 | > addrDP m/44'/165'/1'
149 | Result: nano_3zni7o8m4dq1aphffnaq5pwseh7rrzhkrz5mpr8bcm68n6u775pbk7csedam
150 | ```
151 |
152 | Hex and Base64 encoding example:
153 |
154 | ```shell
155 | > hex Hello
156 | Result: 48656c6c6f
157 | > base64Encode #
158 | Result: SGVsbG8=
159 | > base64Decode #
160 | Result: 48656c6c6f
161 | > buffer
162 | Last value: 48656c6c6f
163 | 3 previous values:
164 | #1 48656c6c6f
165 | #2 SGVsbG8=
166 | #3 48656c6c6f
167 | ```
168 |
--------------------------------------------------------------------------------