├── .gitbook.yaml ├── .gitignore ├── LICENSE ├── README.md ├── SUMMARY.md ├── assets ├── add_new_asset.md ├── faq.md ├── pr-fee.md └── repository_details.md ├── blockatlas ├── blockatlas-code-guide.md ├── blockatlas.md ├── newblockchain.md ├── transaction-format.md └── universal_asset_id.md ├── dapps ├── debugging.md ├── listing-guide.md └── mobile-optimize.md ├── deeplinking └── deeplinking.md ├── index.md ├── media ├── android-dapp-emulator.png ├── android-install-apk-emulator.png ├── edge-inspect.png ├── edge-inspect2.png ├── js-eth-sign-console.png ├── js-eth-sign.png ├── sourcetrail-screenshot.png ├── staking-steps.png ├── wallet-core-banner.png └── wallet-core.png ├── wallet-connect ├── dapp.md └── wallet-connect.md └── wallet-core ├── android-guide.md ├── building.md ├── contributing.md ├── coverage.md ├── integration-guide.md ├── ios-guide.md ├── newblockchain.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 -------------------------------------------------------------------------------- /.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-2019 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 | * [Wallet Core](wallet-core/wallet-core.md) 6 | * [Blockatlas](blockatlas/blockatlas.md) 7 | * [WalletConnect](wallet-connect/wallet-connect.md) 8 | * [Assets](assets/add_new_asset.md) 9 | * [Deep Linking](deeplinking/deeplinking.md) 10 | * [DApps](dapps/listing-guide.md) 11 | 12 | Want to discuss more? join our [Trust Developers chat](https://t.me/trust_developers) on Telegram. 13 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Table of contents 2 | 3 | * [Get Started](README.md) 4 | * [Wallet Core](wallet-core/wallet-core.md) 5 | * [New Blockchain Support](wallet-core/newblockchain.md) 6 | * [RPC / API Requirements](wallet-core/rpc-requirements.md) 7 | * Developing the Library 8 | * [Contributing](wallet-core/contributing.md) 9 | * [Building](wallet-core/building.md) 10 | * [WalletConsole utility](wallet-core/walletconsole.md) 11 | * [Coverage](wallet-core/coverage.md) 12 | * [Releasing](wallet-core/releasing.md) 13 | * [Integration Guide](wallet-core/integration-guide.md) 14 | * [Usage Guide](wallet-core/wallet-core-usage.md) 15 | * [iOS Integration Guide](wallet-core/ios-guide.md) 16 | * [Android Integration Guide](wallet-core/android-guide.md) 17 | * [Server-Side](wallet-core/server-side.md) 18 | * [Blockatlas](blockatlas/blockatlas.md) 19 | * [Adding Support for a New Blockchain](blockatlas/newblockchain.md) 20 | * [Transaction Format](blockatlas/transaction-format.md) 21 | * [URL Specifications](trust-sdk/trust-sdk-specs.md) 22 | * [Universal Asset ID](blockatlas/universal_asset_id.md) 23 | * [WalletConnect](wallet-connect/wallet-connect.md) 24 | * [DApp](wallet-connect/dapp.md) 25 | * [Assets](assets/add_new_asset.md) 26 | * [Pull Request Fee](assets/pr-fee.md) 27 | * [FAQ](assets/faq.md) 28 | * [Repository Details](assets/repository_details.md) 29 | * [Deep Linking](deeplinking/deeplinking.md) 30 | * [DApps](dapps/listing-guide.md) 31 | * [Optimizing your DApp for Trust Wallet DApp Browser](dapps/mobile-optimize.md) 32 | * [Debugging](dapps/debugging.md) 33 | -------------------------------------------------------------------------------- /assets/add_new_asset.md: -------------------------------------------------------------------------------- 1 | # Trust Wallet Assets Info 2 | 3 |
4 | 5 | ## Overview 6 | The Trust Wallet Token Repository 7 | [https://github.com/trustwallet/assets](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 [other projects](#used-in-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 | Please note that __new tokens are not accepted__, 18 | the projects have to be sound, with information available, and __non-minimal circulation__ 19 | (for limit details see https://community.trustwallet.com/t/how-to-submit-a-token-logo/3863). 20 | 21 | 22 | 23 | 24 | 27 | 28 | 29 | 30 | 31 | 32 | 38 | 39 | 40 |
25 | ⚠️ NOTE 26 |
33 |
    34 |
  • 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
  • 35 |
  • Payment of the Pull Request Fee does not guarantee your asset will be approved. Fee is non-refundable
  • 36 |
37 |
41 | 42 | 43 | ## Contribution Quick Start 44 | 45 | Details of the [repository structure](#repository-details) and 46 | [contribution guidelines](repository_details.md#contribution-guidelines) are listed below. 47 | Here is a quick starter summary for the most common use case. 48 | 49 | For **adding an ERC20 token**: 50 | - Ensure your asset meets the our [general guidelines](#disclaimer) 51 | - Visit the [Assets web app](https://assets.trustwallet.com) (GitHub account required), and fill out the requested information 52 | - Pay the processing fee 53 | 54 | Adding a DApp logo or other type of asset? Check our [contribution guidelines](repository_details.md#contribution-guidelines). 55 | 56 | ## Used in Projects 57 | 58 | - [Trust Wallet](https://trustwallet.com) - [iOS](https://itunes.apple.com/us/app/trust-ethereum-wallet/id1288339409) and [Android](https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp) 59 | - [0x Tracker](https://0xtracker.com) - The 0x Protocol Trade Explorer and news aggregator. 60 | - [Uniswap](https://uniswap.exchange) - Uniswap is a protocol for automated token exchange on Ethereum. 61 | - [LinkDrop](https://linkdrop.io/) - A customer acquisition platform for DApps. The easiest crypto onboarding. 62 | - [Aragon](https://aragon.org/) − Aragon is platform and network for decentralized organizations. 63 | - [SpiderDEX](https://www.spiderdex.com) - Decentralized exchange for crypto collectibles. 64 | - [Zerion](https://zerion.io) — A simple interface to decentralized finance. 65 | 66 | ### Fee 67 | Due to an increasing number of pull request (and proportional checking & merging effort), 68 | a modest fee is required for processing a pull request, payable in cryptocurrency. 69 | Follow the instructions in the pull request for completing the fee payment. 70 | 71 | See the [fee FAQ](pr-fee.md) 72 | 73 | ## Disclaimer 74 | 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. 75 | 76 | Trust Wallet team will reject projects that are deemed as scam or fraudulent after careful review. 77 | 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. 78 | 79 | 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. 80 | -------------------------------------------------------------------------------- /assets/faq.md: -------------------------------------------------------------------------------- 1 | ## FAQ 2 | ### Why is the build on my pull request red? 3 | Contributions in a pull request are verified by an automated build. 4 | The checks fail if something is wrong, like to logo is too large or an Ethereum contract is not in 5 | [checksum format](#checksum-format). 6 | Checks the exact error message in the build to find out the problem. 7 | 8 | ### Why is there a merge conflict in my pull request? 9 | 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. 10 | 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. 11 | A pull request can also happen when overriding an existing logo. 12 | 13 | ### Why I don't see my token in search after PR was merged? 14 | After PR was merged, it may take some time, but not longer than one hour, until search will show the new logo. 15 | 16 | ### Why do I still see old logo in Trust Wallet after uploaded new one? 17 | 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. 18 | 19 | ### What is smart contract deprecation? 20 | A process of removing smart contract information such as (token logo and info) from this repository. 21 | 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. 22 | Why would you want to do this ?. 23 | 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. 24 | -------------------------------------------------------------------------------- /assets/pr-fee.md: -------------------------------------------------------------------------------- 1 | # Pull Request Fee -- FAQ 2 | 3 | **Someone is asking for cypto payment for processing my Pull Request. Is this a scam?** 4 | 5 | Always be cautious when someone asks you for payment. 6 | Check that there is a description about it under Trust Wallet Developers' doucmentation (this page). 7 | Check that the app is under the *trustwallet* github account, or that its owner belong to the trustwallet group. 8 | So no, this is not a scam. 9 | 10 | **Why?** 11 | 12 | Trust Wallet supports an insane number of tokens and coins. 13 | We are committed to supporting the tokens used by our users. 14 | But supporting so many assets has a high cost, in terms of running the infrastructure, ensuring continuous integrations, 15 | handling a massive number of requests to the assets info, etc. A lot of spam/scam coins also find us. 16 | 17 | We have introduced this crypto contribution in order to filter requests, so we have more time to handle genuine ones. 18 | 19 | We were partly insipred by [Token Curated Registry](https://medium.com/@tokencuratedregistry/a-simple-overview-of-token-curated-registries-84e2b7b19a06). 20 | 21 | **What do I have to pay attention to?** 22 | 23 | * Double check the [contribution guidelines](assets/add_new_asset.md), to minimize the risk of your PR being rejected. 24 | * Make sure to set the correct memo on your transfer. 25 | 26 | **How does a Fee fit with Open Source?** 27 | 28 | We believe in the power of open-source software, and essential parts of Trust Wallet are open source to contribute to the community 29 | ([Wallet-Core](https://developer.trustwallet.com/wallet-core), [Blockatlas](https://developer.trustwallet.com/blockatlas)). 30 | But Trust Wallet is a branded product and running its backend infrastructure, support, marketing, etc. 31 | Has costs (done by a non-volunteer based team). 32 | 33 | The `assets` repository is open source. You are free to use it and free to create your version (fork). But we choose to ask for a contribution for requests to include/change the information in the Trust Wallet product. See also *Why* question. 34 | 35 | **What is Trust Wallet Token TWT?** 36 | 37 | TWT is a token used in the 38 | [Referral Program](https://community.trustwallet.com/t/invite-a-friend-earn-trust-wallet-token-twt/4125). 39 | Currently, it is only possible to obtain it through referrals. But if you are a token with a serious user base, getting a referral for ten new users should not be a problem. 40 | 41 | **When is my payment evaluated?** 42 | 43 | Payment is handled by [`merge-fee-bot`](https://github.com/settings/apps/merge-fee-bot), a GitHub app by us. 44 | Currently, payment is checked only when there is some action on the PR, such as a comment. 45 | So after your transfer, create a comment about it. The payment should be detected within seconds. 46 | (Technical background: being notified when the payment happens is not a problem, but interacting with a PR 47 | when there is no action on it is difficult for the GitHub app.) 48 | 49 | **What happens after I pay? Is merging automatic?** 50 | 51 | When the `merge-fee-bot` detects payment, it automatically places an Accept review on the PR. 52 | This is a precondition for merge. 53 | But merging is currently not automatic, it is done by the maintainers. 54 | 55 | **I have forgot to set a memo in my transfer, do I have to send another payment?** 56 | 57 | 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. 58 | 59 | **If you decide not to merge my PR, do I get my payment back?** 60 | 61 | 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 prior to paying the fee. 62 | -------------------------------------------------------------------------------- /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 | 6. 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 | 7. Crypto price providers map: [CoinMarketCap](https://github.com/trustwallet/assets/blob/master/pricing/coinmarketcap/mapping.json) 27 | 8. Token and coin information 28 | 9. 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 | 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`. 49 | Non-checksum addresses (e.g. all lowercase) are considered invalid. 50 | 51 | You can find the checksum address by searching on [etherscan.io](https://etherscan.io), 52 | for example stablecoin [DAI](https://etherscan.io/address/0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359) 53 | the checksum address is located at the top left corner of the page and has both uppercase and lowercase characters. 54 | 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). 55 | 56 | #### Layout 57 | 58 | ``` 59 | . 60 | ├── blockchains 61 | │ └──ethereum 62 | │ │ └──assets 63 | │ │ │ └──0x0a2D9370cF74Da3FD3dF5d764e394Ca8205C50B6 // address folder 64 | │ │ │ └──logo.png // token logo 65 | | | | └──info.json // optional token info 66 | │ │ └──info 67 | │ │ │ └──logo.png // chain coin logo 68 | | | │ └──info.json // chain coin info 69 | │ │ └──allowlist.json // list of accepted tokens 70 | │ │ └──denylist.json // list of blocked tokens 71 | | | 72 | | └──binance 73 | │ │ └──assets 74 | │ │ │ └──ONE-5F9 75 | │ │ │ └──logo.png 76 | | | | └──info.json 77 | │ │ └──info 78 | │ │ └──logo.png 79 | | └──tron 80 | │ | └──assets 81 | │ | │ └──1002000 82 | │ | │ | └──logo.png 83 | | | | | └──info.json 84 | | | | └──TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t 85 | | | | └──logo.png 86 | | | | └──info.json 87 | | | | 88 | │ | └──info 89 | │ | └──logo.png 90 | | | └──info.json 91 | | | 92 | | └──cosmos 93 | │ │ └──info 94 | | | | └──logo.png 95 | | | | └──info.json 96 | | | | 97 | │ │ └──validators 98 | │ │ | └──assets 99 | | | | └──cosmosvaloper1clpqr4nrk4khgkxj78fcwwh6dl3uw4epsluffn 100 | | | | └──logo.png 101 | | | | 102 | | | └──list.json 103 | ├── ... 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 | 2. Commit changes and make a PR (pull request) 140 | 141 | ### Image Requirements 142 | - File location: must be placed in the correct folder and subfolder within the [folder structure](#repository-structure). 143 | - File extension: `png`. Uppercase `PNG` is considered invalid. 144 | - File name:`logo.png`, all lowercase. 145 | - Dimension: `256 x 256 pixels` or `512 x 512 pixels`. 146 | - Background: Avoid transparency, set background as your brand color or white by default otherwise your token image wont look good on white/dark theme design. 147 | - File size: maximum 100kB. Tip: optimize image size, e.g. using simple drag-and-drop online service [tinypng](https://tinypng.com/). 148 | 149 | ### Info.json Contents 150 | 151 | The `info.json` file contains basic information about the token/project. 152 | 153 | It has following required fields: 154 | - `name`: name of the token 155 | - `type`: such as ERC20, BEP2, BEP20, TRC20, TRC10, ... 156 | - `symbol`: the token symbol 157 | - `decimals`: number of decimal digits used in the amounts (e.g. 18 for ETH) 158 | - `description`: a few sentence summary of the token/project 159 | - `website`: project web site 160 | - `explorer`: URL of the token explorer page 161 | - `id`: the id/contract/address of the token, same as the subfolder name 162 | 163 | And optionally: 164 | - `links`: Optional array with `name`/`url` pairs, for social media links, documentation, etc. 165 | List of currently supported types: 166 | `github`, `whitepaper`, `twitter`, `telegram`, `telegram_news`, `medium`, `discord`, `reddit`, `facebook`, `youtube`, `coinmarketcap`, `coingecko`, `blog`, `forum`, `docs`, `source_code`. 167 | Note: the `socials` section is no longer used. 168 | 169 | If in doubt about fields, look around / search in existing info.json files. 170 | 171 | Sample `info.json`: 172 | 173 | ``` 174 | { 175 | "name": "Trust Wallet Token", 176 | "website": "https://trustwallet.com", 177 | "description": "Utility token to increase adoption of cryptocurrency.", 178 | "explorer": "https://explorer.binance.org/asset/TWT-8C2", 179 | "type": "BEP2", 180 | "symbol": "TWT", 181 | "decimals": 8, 182 | "status": "active", 183 | "id": "TWT-8C2" 184 | "links": [ 185 | { 186 | "name": "github", 187 | "url": "https://github.com/trustwallet/" 188 | }, 189 | { 190 | "name": "twitter", 191 | "url": "https://twitter.com/TrustWalletApp" 192 | }, 193 | { 194 | "name": "reddit", 195 | "url": "https://reddit.com/r/trustapp" 196 | } 197 | ] 198 | } 199 | ``` 200 | 201 | ### dApp image naming requirements 202 | - [Folder for upload](https://github.com/trustwallet/assets/tree/master/dapps) 203 | - `..png` e.g: 204 | https://app.compound.finance/ => `app.compound.finance.png` 205 | https://kyberswap.com/ => `kyberswap.com.png` 206 | 207 | ### dApp submission and listing requirements 208 | - Upload [logo](https://github.com/trustwallet/assets/tree/master/dapps) 209 | – Make sure you follow rules for image requirements. 210 | - Integrate [deep linking](https://developer.trustwallet.com/deeplinking) 211 | - Add [logo](https://trustwallet.com/press) as dApp supported wallet 212 | - Test dApp inside Trust Wallet on iOS and Android devices 213 | - [Submit form for review](https://docs.google.com/forms/d/e/1FAIpQLSd5p9L78zKXIiu9E5yFRPf5UkvsLZ7TbUDLFBRIi1qMd8Td4A/viewform) 214 | 215 | ### Staking validators requirements 216 | 217 | 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) 218 | 2. Add validator logo image to `blockchains//validators/assets//logo.png` [see images requirements](#image-requirements) 219 | 3. Check chain [specific](#validators-specific-requirements) requirements. 220 | 221 | ### Common Uploads 222 | 223 | 1. Ethereum ERC20 [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/ethereum/assets) 224 | 2. Binance DEX BEP2, BEP8 token [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/binance/assets) 225 | 3. TRON TRC10, TRC20 token [token folder](https://github.com/trustwallet/assets/tree/master/blockchains/tron/assets) 226 | 4. Add Cosmos validator image [](https://github.com/trustwallet/assets/tree/master/blockchains/cosmos/validators) 227 | 5. Add Tezos validator info [](https://github.com/trustwallet/assets/tree/master/blockchains/tezos/validators/list.json) 228 | 6. Add Ethereum contract address to denylist [](https://github.com/trustwallet/assets/tree/master/blockchains/ethereum/denylist.json) 229 | 7. Add TRON TRC10 ID or TRC20 owner contract address to allowlist [](https://github.com/trustwallet/assets/tree/master/blockchains/tron/allowlist.json) 230 | 231 | 232 | ### How To Add Files 233 | 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. 234 | 235 | #### Basics, Prerequisites 236 | 237 | The assets repository is maintained in [GitHub](https://github.com), the largest hosting for open source projects. 238 | You need a GitHub account to interact with it. 239 | 240 | To do changes in the assets repository, you need to create a personal copy called a _fork_. 241 | 242 | Once the changes are prepared inside the fork, you need to create a _pull request_ to the main repository. 243 | Upon review the maintainers will accept your pull request, and the changes will be incorporated. 244 | 245 | ## Token Status 246 | 247 | `active` - Token meets the standard requirements in circulation (number of holders and transactions). 248 | 249 | `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. 250 | 251 | `abandoned` - Token with very low activity (below 100 token transfers a year), migrated to mainnet or to a new contract. 252 | 253 | No longer active 254 | -------------------------------------------------------------------------------- /blockatlas/blockatlas-code-guide.md: -------------------------------------------------------------------------------- 1 | # Block Atlas Code Guide 2 | 3 | ## Code Style 4 | 5 | This repository use the [Uber Go Style Guide](https://github.com/uber-go/guide/blob/master/style.md), which documents 6 | patterns and conventions used in Go code at Uber. 7 | 8 | ## Tests 9 | 10 | All new implementations need to be cover from unit and integration tests. 11 | 12 | ### Unit 13 | 14 | To run the unit tests: `make test` 15 | 16 | ### Integration 17 | 18 | To run the unit tests: `make integration` 19 | 20 | You can find the integration tests inside the folder `pkg/tests/integration`. The tests use a different build constraint, named `integration`. 21 | 22 | ### Functional 23 | 24 | The functional tests are generated automatically and make a health check test in all API's provided from Blockatlas. You only need to set the environment for your coin in the config file. 25 | The tests use a different build constraint, named `functional`. 26 | 27 | You can find the functional tests inside the folder `pkg/tests/functional`. 28 | 29 | To run the integration tests: `make functional` 30 | 31 | ##### Fixtures 32 | 33 | - If you need to change the parameters used in our tests, you can update the fixtures files inside the folder `pkg/tests/functional/testdata` 34 | 35 | - `body_fixtures.json` - Body fixtures for POST requests. 36 | - `coin_fixtures.json` - Coin fixtures for path parameters. 37 | - `query_fixtures.json` - Query string for GET requests. 38 | 39 | - To exclude an API from integration tests, you need to add the route inside the file `pkg/tests/functional/testdata/exclude.json` 40 | 41 | e.g.: 42 | 43 | ```json 44 | [ 45 | "/v2/ethereum/collections/:owner", 46 | "/v2/ethereum/collections/:owner/collection/:collection_id" 47 | ] 48 | ``` 49 | 50 | 51 | ## Error 52 | Use the package `pkg/errors` for create a new error. 53 | An error in Go is any implementing interface with an Error() string method. We overwrite the error object by our error struct: 54 | 55 | ``` 56 | type Error struct { 57 | Err error 58 | Type Type 59 | meta map[string]interface{} 60 | stack []string 61 | } 62 | ``` 63 | 64 | To be easier the error construction, the package provides a function named E, which is short and easy to type: 65 | 66 | `func E(args ...interface{}) *Error` 67 | 68 | E.g.: 69 | - just error: 70 | `errors.E(err)` 71 | 72 | - error with message: 73 | `errors.E(err, "new message to append")` 74 | 75 | - error with type: 76 | `errors.E(err, errors.TypePlatformReques)` 77 | 78 | - error with type and message: 79 | `errors.E(err, errors.TypePlatformReques, "new message to append")` 80 | 81 | - error with type and meta: 82 | ``` 83 | errors.E(err, errors.TypePlatformRequest, errors.Params{ 84 | "coin": "Ethereum", 85 | "method": "CurrentBlockNumber", 86 | }) 87 | ``` 88 | 89 | - error with meta: 90 | ``` 91 | errors.E(err, errors.Params{ 92 | "coin": "Ethereum", 93 | "method": "CurrentBlockNumber", 94 | }) 95 | ``` 96 | 97 | - error with type and meta: 98 | ``` 99 | errors.E(err, errors.TypePlatformRequest, errors.Params{ 100 | "coin": "Ethereum", 101 | "method": "CurrentBlockNumber", 102 | }) 103 | ``` 104 | 105 | - error with type, message and meta: 106 | ``` 107 | errors.E(err, errors.TypePlatformRequest, "new message to append", errors.Params{ 108 | "coin": "Ethereum", 109 | "method": "CurrentBlockNumber", 110 | }) 111 | ``` 112 | 113 | 114 | - You can send the errors to sentry using `.PushToSentry()` 115 | `errors.E(err, errors.TypePlatformReques).PushToSentry()` 116 | 117 | 118 | *All fatal errors emitted by logger package already send the error to Sentry* 119 | 120 | ### Types 121 | 122 | ``` 123 | const ( 124 | TypeNone Type = iota 125 | TypePlatformUnmarshal 126 | TypePlatformNormalize 127 | TypePlatformUnknown 128 | TypePlatformRequest 129 | TypePlatformClient 130 | TypePlatformError 131 | TypePlatformApi 132 | TypeLoadConfig 133 | TypeLoadCoins 134 | TypeObserver 135 | TypeStorage 136 | TypeAssets 137 | TypeUtil 138 | TypeCmd 139 | TypeUnknown 140 | ) 141 | ``` 142 | 143 | 144 | ## Logs 145 | Use the package `pkg/logger` for logs. 146 | 147 | E.g.: 148 | 149 | - Log message: 150 | `logger.Info("Loading Observer API")` 151 | 152 | - Log message with params: 153 | `logger.Info("Running application", logger.Params{"bind": bind})` 154 | 155 | - Fatal with error: 156 | `logger.Fatal("Application failed", err)` 157 | 158 | - The method parameters don't have a sort. You just need to pass them to the method: 159 | `logger.Fatal(err, "Application failed")` 160 | 161 | - Create a simple error log: 162 | `logger.Error(err)` 163 | 164 | - Create an error log with a message: 165 | `logger.Error("Failed to initialize API", err)` 166 | 167 | - Create an error log, with error, message, and params: 168 | ``` 169 | p := logger.Params{ 170 | "platform": handle, 171 | "coin": platform.Coin(), 172 | } 173 | err := platform.Init() 174 | if err != nil { 175 | logger.Error("Failed to initialize API", err, p) 176 | } 177 | ``` 178 | 179 | - Debug log: 180 | `logger.Debug("Loading Observer API")` 181 | or 182 | `logger.Debug("Loading Observer API", logger.Params{"bind": bind})` 183 | 184 | - Warning log: 185 | `logger.Warn("Warning", err)` 186 | or 187 | `logger.Warn(err, "Warning")` 188 | or 189 | `logger.Warn("Warning", err, logger.Params{"bind": bind})` 190 | -------------------------------------------------------------------------------- /blockatlas/blockatlas.md: -------------------------------------------------------------------------------- 1 | # Block Atlas by Trust Wallet 2 | 3 | ![Go Version](https://img.shields.io/github/go-mod/go-version/TrustWallet/blockatlas) 4 | [![GoDoc](https://godoc.org/github.com/TrustWallet/blockatlas?status.svg)](https://godoc.org/github.com/TrustWallet/blockatlas) 5 | [![Build Status](https://dev.azure.com/TrustWallet/Trust%20BlockAtlas/_apis/build/status/TrustWallet.blockatlas?branchName=master)](https://dev.azure.com/TrustWallet/Trust%20BlockAtlas/_build/latest?definitionId=27&branchName=master) 6 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/43834b0c94ad4f6088629aa3e3bb5e94)](https://www.codacy.com/app/TrustWallet/blockatlas?utm_source=github.com&utm_medium=referral&utm_content=TrustWallet/blockatlas&utm_campaign=Badge_Grade) 7 | [![Go Report Card](https://goreportcard.com/badge/trustwallet/blockatlas)](https://goreportcard.com/report/TrustWallet/blockatlas) 8 | [![Docker](https://img.shields.io/docker/cloud/build/trustwallet/blockatlas.svg)](https://hub.docker.com/r/trustwallet/blockatlas) 9 | 10 | > BlockAtlas is a clean explorer API and transaction observer for cryptocurrencies. 11 | 12 | BlockAtlas connects to nodes or explorer APIs of the supported coins and maps transaction data, 13 | account transaction history and market data into a generic, easy to work with JSON format. 14 | It is in production use at the [Trust Wallet app](https://trustwallet.com/), 15 | the official cryptocurrency wallet of Binance. Also is in production at the [BUTTON Wallet](https://buttonwallet.com), Telegram based non-custodial wallet. 16 | The observer API watches the chain for new transactions and generates notifications by webhooks. 17 | 18 | #### Supported Coins 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ## Setup 43 | 44 | ### Requirements 45 | 46 | * [Go Toolchain](https://golang.org/doc/install) versions 1.13+ 47 | * [Redis](https://redis.io/topics/quickstart) instance (observer and syncmarkets) 48 | 49 | ### From Source 50 | 51 | ```shell 52 | # Download source to $GOPATH 53 | go get -u github.com/trustwallet/blockatlas 54 | cd $(go env GOPATH)/src/github.com/trustwallet/blockatlas 55 | 56 | # Start Observer with the path to the config.yml ./ 57 | go build -o observer-bin cmd/observer/main.go && ./observer-bin -c config.yml 58 | 59 | # Start API server at port 8422 with the path to the config.yml ./ 60 | go build -o api-bin cmd/api/main.go && ./api-bin -p 8422 -c config.yml 61 | 62 | # Start sync worker for market prices and rates with the path to the config.yml ./ 63 | go build -o syncmarkets-bin cmd/syncmarkets/main.go && ./syncmarkets-bin -c config.yml 64 | ``` 65 | 66 | ### Docker 67 | 68 | [![Docker](https://img.shields.io/docker/cloud/build/trustwallet/blockatlas.svg?style=for-the-badge)](https://hub.docker.com/r/trustwallet/blockatlas) 69 | 70 | Build and run from local Dockerfile: 71 | 72 | You should change `config.yml`: 73 | ```yaml 74 | redis: redis://redis:6379 75 | ``` 76 | Then build: 77 | ```shell 78 | docker-compose build 79 | ``` 80 | 81 | For run api, observer and syncmarkets: 82 | ```shell 83 | docker-compose up 84 | ``` 85 | 86 | If you need to start one service: 87 | ```shell 88 | docker-compose start api redis 89 | docker-compose start observer redis 90 | docker-compose start syncmarkets redis 91 | ``` 92 | 93 | ### Heroku 94 | 95 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://www.heroku.com/deploy/?template=https://github.com/trustwallet/blockatlas) 96 | 97 | ## Configuration 98 | 99 | Block Atlas can run just fine without configuration. 100 | By default, all coins offering public RPC/explorer APIs are enabled. 101 | 102 | If you want to use custom RPC endpoints, or enable coins without public RPC (like Nimiq), 103 | you can configure Block Atlas over `config.yml` or environment variables. 104 | 105 | #### Config File 106 | 107 | Config is loaded from `config.yml` if it exists in the working directory. 108 | The repository includes a [default config](./config.yml) for reference with all available config options. 109 | 110 | Example (`config.yml`): 111 | 112 | ```yaml 113 | nimiq: 114 | api: http://localhost:8648 115 | #... 116 | ``` 117 | 118 | #### Environment 119 | 120 | The rest gets loaded from environment variables. 121 | Every config option is available under the `ATLAS_` prefix. 122 | Nested keys are joined via `_` (Example `nimiq.api` => `NIMIQ_API`) 123 | 124 | Example: 125 | 126 | ```shell 127 | ATLAS_NIMIQ_API=http://localhost:8648 128 | ``` 129 | 130 | ## Docs 131 | 132 | Swagger API docs provided at path `/swagger/index.html` 133 | 134 | #### Updating Docs 135 | 136 | - After creating a new route, add comments to your API source code, [See Declarative Comments Format](https://swaggo.github.io/swaggo.io/declarative_comments_format/). 137 | - Download Swag for Go by using: 138 | 139 | `$ go get -u github.com/swaggo/swag/cmd/swag` 140 | 141 | - Run the Swag in your Go project root folder. 142 | 143 | `$ swag init -g ./cmd/api/main.go -o ./docs` 144 | 145 | ## Metrics 146 | 147 | The Blockatlas can collect and expose by `expvar's`, metrics about the application healthy and clients and server requests. 148 | Prometheus or another service can collect metrics provided from the `/metrics` endpoint. 149 | 150 | To protect the route, you can set the environment variables `METRICS_API_TOKEN`, and this route starts to require the auth bearer token. 151 | 152 | ## Contributing 153 | 154 | If you'd like to add support for a new blockchain, feel free to file a pull request. 155 | Note that most tokens that run on top of other chains are already supported and 156 | don't require code changes (e.g. ERC-20). 157 | 158 | The best way to submit feedback and report bugs is to open a GitHub issue. 159 | Please be sure to include your operating system, version number, and 160 | [steps](https://gist.github.com/nrollr/eb24336b8fb8e7ba5630) to reproduce reported bugs. 161 | 162 | More resources for developers are in [CONTRIBUTING.md](CONTRIBUTING.md). -------------------------------------------------------------------------------- /blockatlas/newblockchain.md: -------------------------------------------------------------------------------- 1 | # Block Atlas Developer Guide 2 | 3 | ## Overview 4 | 5 | Block Atlas provides access to blockchain data. 6 | It is used by Trust Wallet to query transaction information and stream new transactions. 7 | 8 | A list of supported coins can be found in the config file. 9 | 10 | ## Integration 11 | 12 | While we are happy about any new coin integrations we cannot immediately accept every request. To keep our high security and reliability standards, every integration must be approved by the Trust Wallet team first. 13 | 14 | Pull requests other than coin integrations are always welcome. You can contact the Trust Wallet team through our [community site](http://community.trustwallet.com/). 15 | 16 | To integrate an approved coin with Block Atlas, please follow this guide: 17 | 18 | ### Requirements 19 | 20 | Before starting development on Block Atlas integration, make sure that _all_ of the following requirements are met: 21 | 22 | - Your coin is based on the accounts-model and transactions have a single input & output (excluding fees). 23 | Integrate UTXO-based coins with BlockBook instead. 24 | - You are _NOT_ integrating a _token_ that runs on top of another blockchain (ERC-20, TRX10, ...) 25 | - Your coin is either 26 | - supported by [_wallet-core_](https://github.com/trustwallet/wallet-core) 27 | - OR a ready-for-review PR for wallet-core has been submitted 28 | - Your coin has a public JSON-RPC or HTTP API. 29 | - Said API supports querying a list of transactions by address 30 | - Your coin is registered with [SLIP-0044](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) 31 | - Your coin is not already supported 32 | 33 | ### Structure 34 | 35 | This project is powered by Go, Gin Gonic and Viper. 36 | 37 | Try to use existing code of other coins as an example. 38 | 39 | Avoid adding additional dependencies for security and performance reasons. 40 | `go.mod` contains a list of available third-party packages. 41 | If you think adding a dependency is necessary, please provide an explanation in the respective pull request. 42 | A library specific to your chain is not a necessary dependency. 43 | 44 | ### Setup 45 | 46 | #### Metadata 47 | 48 | Add your coin to the end of `/coin/coins.yml`. 49 | 50 | - `id` - Coin ID. 51 | - `symbol` - Coin symbol. 52 | - `handle` - Coin handle, this is going to be your coin path, eg: `ethereum`: `v1/ethereum/...`. 53 | - `name` - The coin name. 54 | - `decimals` - How many decimals your coin has. 55 | - `blockTime` - Time between two blocks. 56 | - `sampleAddress` - Arbitrary address holding coins. 57 | It is used to test the API. 58 | 59 | Then, run `make gen-coins` to re-generate the coin file. 60 | 61 | (Optional) Add your coin icon to the end at `/README.md`. 62 | 63 | #### Config 64 | 65 | The config specifies how to reach your blockchain. 66 | All coins have a `.api` key pointing to the URL that provides your blockchain API. 67 | 68 | Add your default config, like hosts and api keys, at `/config.yml`. 69 | 70 | ### API client 71 | 72 | For each Blockchain implementation, we have one platform, some platforms can be useful for other blockchains, like BTC, LTC, BHC, DASH, DOGE. You can find these implementations inside the `platform` package. 73 | 74 | Create a `platform//client.go` file with a `Client` struct. 75 | The only exported properties are "constructor"-like parameters. 76 | 77 | For example, a client using JSON-RPC might look like this: 78 | 79 | ``` 80 | type Client struct { 81 | blockatlas.Request 82 | } 83 | 84 | func (c *Client) Init() { 85 | p.client = Client{blockatlas.InitClient(viper.GetString("ethereum.api"))} 86 | } 87 | ``` 88 | 89 | Depending on your required feature set you'll need to expose these methods: 90 | 91 | - `client.GetTxsOfAddress(address string)` 92 | - `client.CurrentBlockNumber(num int64)` & `client.GetBlockByNumber()` 93 | 94 | They will be used in other files later. 95 | 96 | #### Coin-specific models 97 | 98 | `/platform//model.go` contains the data models returned by `client.go` above. 99 | 100 | Take care when unmarshalling (Go's term for deserializing) currency amounts. We never do floating point operations on currencies but operate on base 10 string representations instead. Use any of these data types in your model. 101 | 102 | To make conversions from decimals numbers to satoshi/wei you can use the numbers package inside `pkg/numbers`. 103 | 104 | The Blockatlas use `blockatlas.Amount` object to return value, this object is a type string. Internally, it carries an integer string of smallest units. 105 | 106 | 107 | #### Normalizing chain data 108 | 109 | The models above are not ready to be used yet and 110 | need to be converted to the BlockAtlas generic model. 111 | 112 | Define `Normalize*` functions in `api.go` that convert from `model.go` types to `blockatlas` transactions (lists). 113 | 114 | ##### Transaction metadata types 115 | 116 | `Tx` can express different transaction types, for my details see the [Transaction Format guide](transaction-format.md) 117 | 118 | ### Base integration 119 | 120 | #### `Platform` implementation 121 | 122 | Every coin implements the `blockatlas.Platform` and some `blockatlas.*API` interfaces. 123 | 124 | Create a `/platform//base.go` file and implement the `blockatlas.Platform` methods, `Init() & Coin()` like this: 125 | 126 | ``` 127 | type Platform struct { 128 | client Client 129 | } 130 | 131 | func (p *Platform) Init() error { 132 | p.client = Client{blockatlas.InitClient(viper.GetString("ethereum.api"))} 133 | p.client.Headers["X-APIKEY"] = viper.GetString("ethereum.key") 134 | } 135 | 136 | 137 | func (p *Platform) Coin() coin.Coin { 138 | return coin.Coins[coin.ETH] 139 | } 140 | ``` 141 | 142 | Then, link your platform at `/platform/registry.go`. 143 | 144 | #### `TxAPI` 145 | 146 | `TxAPI` can query transactions of an address. Needs to be implemented inside `/platform//transaction.go`. 147 | 148 | _Method signatures_: 149 | 150 | - `func (p *Platform) GetTxsByAddress(address string) (blockatlas.TxPage, error)` 151 | 152 | After implementation, a `GET /v1//
` route gets created. 153 | 154 | #### `BlockAPI` 155 | 156 | `BlockAPI` can tell the chain height and get blocks by their number. Needs to be implemented inside `/platform//block.go`. 157 | 158 | _Method signatures_: 159 | 160 | - `func (p *Platform) CurrentBlockNumber() (int64, error)` 161 | - `func (p *Platform) GetBlockByNumber(num int64) (*blockatlas.Block, error)` 162 | 163 | After implementation the observer API gets enabled (required for tx push notifications). 164 | 165 | #### `TokenTxAPI` 166 | `TokenTxAPI` provides token transaction lookups. Needs to be implemented inside `/platform//transaction.go`. 167 | 168 | _Method signatures_: 169 | 170 | - `GetTokenTxsByAddress(address, token string) (TxPage, error)` 171 | 172 | #### `TokenAPI` 173 | `TokenAPI` provides token lookups. Needs to be implemented inside `/platform//token`. 174 | 175 | _Method signatures_: 176 | 177 | - `GetTokenListByAddress(address string) (TokenPage, error)` 178 | 179 | #### `AddressAPI ` 180 | `AddressAPI ` provides an AddressAPI to fetch addresses for an account. Needs to be implemented inside `/platform//base.go`. 181 | 182 | _Method signatures_: 183 | 184 | - ` GetAddressesFromXpub(xpub string) ([]string, error)` 185 | 186 | #### `CollectionAPI ` 187 | `AddressAPI ` provides custom HTTP routes. Needs to be implemented inside `/platform//collection.go`. 188 | 189 | _Method signatures_: 190 | 191 | - `GetCollections(owner string) (CollectionPage, error)` 192 | - `GetCollectibles(owner, collectibleID string) (CollectiblePage, error)` 193 | 194 | #### `NamingServiceAPI ` 195 | `NamingServiceAPI ` provides public name service domains HTTP routes. Needs to be implemented inside `/platform//domain.go`. 196 | 197 | _Method signatures_: 198 | 199 | - ` Lookup(coins []uint64, name string) ([]Resolved, error)` 200 | 201 | #### `CustomAPI ` 202 | `CustomAPI ` provides a custom public name service domains HTTP. Needs to be implemented inside `/platform//custom.go`. 203 | 204 | _Method signatures_: 205 | 206 | - ` RegisterRoutes(router gin.IRouter)` 207 | 208 | ### Submitting the code 209 | 210 | #### Unit Test 211 | 212 | Write a test at `/platform//_test.go` to ensure correct normalization. 213 | Try reading and normalizing a sample API response (copy paste output of REST client). 214 | 215 | 216 | ### Pull Request 217 | 218 | As soon as you are done, file a pull request from your fork to `trustwallet:master`. 219 | Our devs will get a notification and review your code soon. 220 | In case of design problems or bugs, we will request changes via GitHub code review. 221 | 222 | You can speed up integration and merge approval by making sure that: 223 | 224 | - the Git history is relatively clean (`git rebase -i` to squash your commits) 225 | - only one pull request is filed (`git push -f` to overwrite the commit history of your PR). 226 | Please don't close and open PRs too often, our mail inboxes will be thankful. 227 | - no merge conflicts with `trustwallet:master` exist 228 | - all tests pass, your build gets a green tick 229 | - `go lint` has no complaints about your code 230 | 231 | After your code is merged, our Continous Delivery will deploy it to our servers and your part is done. 232 | 233 | Thanks for contributing to Trust Wallet! 234 | -------------------------------------------------------------------------------- /blockatlas/transaction-format.md: -------------------------------------------------------------------------------- 1 | # Formats 2 | 3 | ## Transactions 4 | 5 | All types of the transaction have the same [base](#base) format, and we can differ the actions using the [meta](#meta) object. 6 | 7 | ### Base 8 | 9 | - `id` - Transaction hash. 10 | - `from` - Transaction original sender. 11 | - `to` - Transaction original recipient. 12 | - `fee` - Transaction fee. 13 | - `coin` - Coin index from [SLIP-44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md). 14 | - `date` - Time in Unix format at which a transaction is mined. 15 | - `block` - Block number at which transaction is included. 16 | - `memo` - Message included with a transaction. 17 | - `inputs ` - Input addresses for UTXO platforms. 18 | - `outputs ` - Output addresses for UTXO platforms. 19 | - `sequence` - Transaction nonce or sequence. 20 | - `status` - [Transaction status](#transaction-status). 21 | - `direction` - [Transaction direction](#transaction-direction). 22 | 23 | 24 | ##### Transaction Status: 25 | - `completed` - Completed and settled in the ledger. 26 | - `pending` - Pending in the mempool. 27 | - `error` - Smart contract failed to execute transaction or failed for any reason in the ledger. 28 | 29 | ##### Transaction Direction: 30 | - `outgoing` - The address owner is the sender of the transaction. 31 | - `incoming` - The address owner is the receiver of the transaction. 32 | - `yourself` - The address owner sends a transaction to yourself. 33 | 34 | 35 | e.g: 36 | 37 | ``` 38 | { 39 | "id": "12345678" 40 | "from": "123", 41 | "to": "123", 42 | "fee": "1234" 43 | "coin": 60, 44 | "date": 1562256431, 45 | "block": 123, 46 | "memo": "", 47 | "status": "completed" 48 | } 49 | ``` 50 | 51 | 52 | ## Meta 53 | 54 | ### Types 55 | Meta actions to specify a type of transfer. 56 | 57 | - [`transfer`](#transfer) - Basic transaction transfer from native currency platform. 58 | - [`token_transfer`](#token_transfer) - Transfer of native tokens (Stellar Tokens/TRC10). 59 | - [`native_token_transfer`](#native_token_transfer) - Transfer of non-native tokens (ERC20/TRC20). 60 | - [`collectible_transfer`](#collectible_transfer) - NFT tokens transfer (ERC721/ERC1155). 61 | - [`token_swap`](#token_swap) - Exchange of two different tokens. 62 | - [`contract_call`](#contract_call) - Transaction from a contract execution/call. 63 | - [`any_action`](#any_action) - Generic action, can be used for stake like delegate, undeelegate and claim rewards action. 64 | 65 | 66 | ### Examples: 67 | #### Transfer 68 | 69 | Type: `transfer` 70 | 71 | ``` 72 | { 73 | "type": "transfer", 74 | "metadata: { 75 | "name": "Viktor Coin", 76 | "symbol": "VIK", 77 | "decimals": 18, 78 | "value": "12312312" 79 | } 80 | } 81 | ``` 82 | 83 | #### Token Transfer 84 | 85 | Type: `token_transfer` 86 | 87 | ``` 88 | { 89 | "type": "token_transfer", 90 | "metadata: { 91 | "name": "Viktor Coin", 92 | "symbol": "VIK", 93 | "token_id" : "0x123", 94 | "decimals": 18, 95 | "value": "12312312", 96 | "from": "123", 97 | "to": "123", 98 | } 99 | } 100 | ``` 101 | 102 | #### Native Token Transfer 103 | 104 | Type: `native_token_transfer` 105 | 106 | ``` 107 | { 108 | "type": "native_token_transfer", 109 | "metadata: { 110 | "name": "Bittorent", 111 | "symbol": "BTT", 112 | "token_id" : "1002000", 113 | "decimals": 8, 114 | "value": "12312312" 115 | } 116 | } 117 | ``` 118 | 119 | #### Collectible Transfer 120 | 121 | Type: `collectible_transfer` 122 | 123 | ``` 124 | { 125 | "type": "collectible_transfer", 126 | "metadata: { 127 | "name": "Viktor Kittie", 128 | "contract" : "0x123", 129 | "image_url": "https://google.com/img.png", 130 | "from": "0x123", 131 | "to": "0x123", 132 | } 133 | } 134 | ``` 135 | 136 | #### Token Swap 137 | 138 | Type: `token_swap` 139 | 140 | ``` 141 | { 142 | "type": "token_swap" 143 | "metadata: { 144 | "input" : { 145 | "coin": 60, 146 | "token_id": "0x123" - optional 147 | "symbol": "BNB", 148 | "value": "123", 149 | "decimals": 8, 150 | }, 151 | "output": { 152 | "coin": 60, 153 | "token_id": "0x123" - optional 154 | "symbol": "BTT", 155 | "value": "123", 156 | "decimals": 8, 157 | } 158 | } 159 | } 160 | ``` 161 | 162 | #### Contract Call 163 | 164 | Type: `contract_call` 165 | 166 | ``` 167 | { 168 | "type": "contract_call", 169 | "metadata": { 170 | "input": "0xfffdefefed", 171 | "value": "1800000000000000000" 172 | } 173 | } 174 | ``` 175 | 176 | 177 | #### Any Action 178 | 179 | Type: `any_action` 180 | 181 | ``` 182 | { 183 | "type": "any_action", 184 | "metadata": { 185 | "coin": 60, 186 | "title": "Place Order", 187 | "key": "place_order", 188 | "token_id": "0x123" - optional 189 | "name": "Viktor Coin", 190 | "symbol": "VIK", 191 | "decimals": 18, 192 | "value": "12312312" 193 | } 194 | } 195 | ``` 196 | 197 | ##### Keys and Titles 198 | Keys mostly used to provide localized version on the clients by key. 199 | 200 | - `place_order`: Placer Order. 201 | - `cancel_order`: Cancel Order. 202 | - `issue_token`: Issue Token. 203 | - `burn_token`: Burn Token. 204 | - `mint_token`: Mint Token. 205 | - `approve_token`: Approve Token. 206 | - `stake_delegate`: Stake Delegate. 207 | - `stake_claim_rewards`: Stake Claim Rewards. 208 | 209 | 210 | ## Staking 211 | 212 | ### Validators 213 | 214 | - `id` - Validator address. 215 | - `status` - [Validator status](#validator-status). 216 | - `info` - Details about the validator. 217 | - `name` - Validator name. 218 | - `description` - Validator description. 219 | - `image` - Validator image to show on the client. 220 | - `website` - Validator website. 221 | - `details` - Stake details. 222 | - `reward` - Estimate percent reward. 223 | - `annual` - Estimate percent reward per year. 224 | - `locktime` - Estimate percent reward. 225 | - `minimum_amount ` - Estimate percent reward. 226 | - `type ` - [Validator status](#validator-status). 227 | 228 | ##### Validator Status: 229 | - `active` - Validator is active for stake. 230 | - `pending` - Validator is pending for stake. 231 | 232 | ##### Validator Type: 233 | - `auto` - The address owner is staking only holding the coin. 234 | - `delegate` - The owner needs to delegate your balance. 235 | 236 | e.g: 237 | 238 | ```json 239 | { 240 | "id": "cosmosvaloper1fhr7e04ct0zslmkzqt9smakg3sxrdve6ulclj2", 241 | "status": true, 242 | "info": { 243 | "name": "Stakin", 244 | "description": "Your Trusted Crypto Rewards", 245 | "image": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/cosmos/validators/assets/cosmosvaloper1fhr7e04ct0zslmkzqt9smakg3sxrdve6ulclj2/logo.png", 246 | "website": "https://stakin.com" 247 | }, 248 | "details": { 249 | "reward": { 250 | "annual": 7.318467221273478 251 | }, 252 | "locktime": 1814400, 253 | "minimum_amount": "0", 254 | "type": "delegate" 255 | } 256 | } 257 | ``` 258 | 259 | ## Token 260 | 261 | 262 | - `name` - Token name 263 | - `symbol` - Token symbol 264 | - `decimals` - Number of decimal places 265 | - `tokenID` - Token unique id on the chain. e.g. (Dai token id on Ethereum - 0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359) 266 | - `coin` - Coin index from [SLIP-44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) 267 | - `type` - [Token type](#token-type). 268 | 269 | ##### Token Type: 270 | - `ERC20` - ERC20 token. 271 | - `BEP2` - BEP2 token. 272 | - `TRC10` - TRC10 token. 273 | - `ETC20` - ETC20 token. 274 | - `POA20` - POA20 token. 275 | - `TRC20` - TRC20 token. 276 | - `CLO20` - CLO20 token. 277 | - `G020` - G020 token. 278 | - `WAN20` - WAN20 token. 279 | - `TT20` - TT20 token. 280 | 281 | 282 | e.g: 283 | 284 | ```json 285 | { 286 | "name": "Givly Coin", 287 | "symbol": "GIV", 288 | "decimals": 8, 289 | "tokenID": "GIV-94E", 290 | "coin": 714, 291 | "type": "BEP2" 292 | } 293 | ``` 294 | 295 | -------------------------------------------------------------------------------- /blockatlas/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](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) conventions, There is some exceptions that it's using [coinId](https://github.com/trustwallet/wallet-core/blob/master/coins.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 | -------------------------------------------------------------------------------- /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 | ![Edge inspect](../media/edge-inspect.png) 22 | ![Edge inspect](../media/edge-inspect2.png) 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 | 5. what's the url of your dapp? 36 | -------------------------------------------------------------------------------- /dapps/listing-guide.md: -------------------------------------------------------------------------------- 1 | # A Complete Guide to Listing your DApp with Trust Wallet 2 | 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. 3 | 4 | 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. 5 | 6 | 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. 7 | 8 | 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: 9 | 10 | 1. [Optimization](dapps/mobile-optimize.md) 11 | 2. [Upload Assets (involves nominal fee)](https://developer.trustwallet.com/add_new_asset#dapp-image-naming-requirements) 12 | 3. [Application Form](https://trustwallet.com/submit-dapp) 13 | 14 | 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. 15 | 16 | - [ ] Optimization of your DApp for the Trust Wallet browser 17 | - [ ] Optimization of your DApp for desktop users 18 | - [ ] Uploading of required logo assets 19 | - [ ] Application to join the Trust Wallet DApp listing 20 | - [ ] Hosting a Trust Wallet AMA session 21 | - [ ] Creating a Barn of Trust staking vault 22 | 23 | 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. 24 | 25 | ### Technical Requirements & Preperation 26 | 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. 27 | 28 | Therefore, it is required that you have a GitHub account to interact with the repo and submit your DApp for listing. Before uploading any image files, you must make sure they meet the following requirements: 29 | 30 | - File Extension: `png` 31 | - Uppercase `PNG` is considered invalid 32 | - File Name:logo.pngSize: 256px by 256px 33 | - Background: Avoid transparency. White is preferred to fit in with app white/dark theme designs. 34 | - 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 35 | - For example: https://app.compound.finance/ => app.compound.finance.png 36 | https://kyberswap.com/ => kyberswap.com.png 37 | 38 | Some basic information is also required on your DApp project as part of the submission process. This includes: 39 | 40 | - A short and clear explanation of your DApp functionality 41 | - Your Telegram channel 42 | - A description of your DApp for listing 43 | - Your DApp name for the listing 44 | - The URL of your DApp for listing 45 | 46 | ### Pull Request Fee 47 | 48 | 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. 49 | 50 | Contributing a fee filters spam requests and ensures that there is more time to handle genuine submissions. 51 | 52 | More details are available on the [pull request fee](https://developer.trustwallet.com/add_new_asset/pr-fee) that explain how this fits in with Trust Wallet’s open-source ethos. 53 | 54 | **NOTE:** Paying the fee does not guarantee that your asset will be listed in the repository. 55 | 56 | ### Applying for the Trust Wallet Dapp Listing 57 | 58 | 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*. 59 | 60 | 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. 61 | 62 | The aim of the Trust Wallet DApp Directory is twofold: 63 | 64 | 1. It empowers users to discover high-quality DApps within Trust Wallet. 65 | 2. It allows developers to showcase their work to millions of users as part of a developed and supported ecosystem. 66 | 67 | #### Curation Guidelines 68 | 69 | 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: 70 | 71 | - 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. 72 | - Attempts to misrepresent or otherwise deceive the listing and review process will result in your DApp being rejected or delisted from the directory. 73 | - Stronger consideration will be given to Dapps that demonstrate a unique value proposition relative to other existing/popular apps 74 | - 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 75 | 76 | Before submitting your DApp and filling out the submission form, you should ensure that your DApp is fully compliant with our submission criteria. 77 | 78 | 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. 79 | 80 | #### Safety and Security 81 | 82 | Trust Wallet users require confidence that using Dapps won’t jeopardize their funds, personal information, or device security. 83 | 84 | 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. 85 | 86 | #### Objectionable and misleading content 87 | 88 | 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. 89 | 90 | #### Legal & Business 91 | 92 | 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. 93 | 94 | 95 | ### Support and Questions 96 | 97 | 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/). 98 | 99 | 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. 100 | -------------------------------------------------------------------------------- /dapps/mobile-optimize.md: -------------------------------------------------------------------------------- 1 | # Optimizing Your Dapp for the Trust Wallet DApp Browser 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. 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 browser 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 Binance Smart Chain, Ethereum network, ETC, CLO, Thunder, Tomo, and POA 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 is a good place to start 18 | 19 | Familiarity with MetaMask puts you off to a good start in terms of optimizing or developing Ethereum DApps for Trust Wallet. The web3 development process is the same when using MetaMask 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, 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 (in [TestFlight](https://community.trustwallet.com/t/how-to-use-the-dapp-browser-on-ios/69390)). 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 of any DApp to be uploaded to TestFlight before they can access it. 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 | Web3 is incredibly powerful for developing DApps and outlining their interactions with Ethereum nodes. The most up-to-date Web3 open-source [JavaScript library](https://github.com/ethers-io/ethers.js/) needs to be implemented for your DApp to be well optimized for the Trust Wallet browser. 30 | 31 | All 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. 32 | 33 | If you have decided upon using MetaMask as your dev tool, do not forget their [decision](https://medium.com/metamask/no-longer-injecting-web3-js-4a899ad6e59e) to stop injecting the web.js API. This will seriously affect the degree of compatibility between your DApp and the Trust Wallet browser without proper planning. 34 | 35 | ## Test your DApp on both iOS and Android 36 | 37 | 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. 38 | 39 | 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. 40 | 41 | ## Flag issues in the trust-web3-provider repo 42 | 43 | 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. The Trust Wallet team will then provide support for any queries you have in due time. 44 | 45 | ## Implement deep links 46 | 47 | 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. 48 | -------------------------------------------------------------------------------- /deeplinking/deeplinking.md: -------------------------------------------------------------------------------- 1 | # Deeplinking 2 | 3 | ## DApp Browser 4 | 5 | Open dapp browser with a specific url and network (Android only). 6 | 7 | - `coin` slip44 index 8 | - `url` website url 9 | 10 | Due to Apple restrictions, [browser was removed from the iOS app](https://community.trustwallet.com/t/dapp-browser-removal-on-ios-version-of-trust-wallet/212293) 11 | 12 | https://link.trustwallet.com/open_url?coin_id=60&url=https://compound.finance 13 | 14 | 15 | ## Assets 16 | 17 | ### Open coin 18 | 19 | - `asset` asset in [UAI format](/assets/universal_asset_id.md) 20 | 21 | https://link.trustwallet.com/open_coin?asset=c60 22 | 23 | 24 | ### Add asset 25 | 26 | Asset will be added to local storage and will show up on the wallet screen. 27 | 28 | - `asset` asset in [UAI format](/assets/universal_asset_id.md) 29 | 30 | https://link.trustwallet.com/add_asset?asset=c60_t0x514910771af9ca656af840dff83e8264ecf986ca 31 | 32 | ## Payment 33 | 34 | ### Redeem Code: 35 | 36 | - `code` unique code 37 | - `provider` provider url 38 | 39 | https://link.trustwallet.com/redeem?code=abc123 40 | 41 | ### Send Payment: 42 | 43 | - `asset` asset in [UAI format](/assets/universal_asset_id.md) 44 | - `address` Recipient address 45 | - `amount` Optional. Payment amount 46 | - `memo` Optional. Memo 47 | - `data` Optional. Data 48 | 49 | https://link.trustwallet.com/send?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F&address=0x650b5e446edabad7eba7fa7bb2f6119b2630bfbb&amount=1&memo=test 50 | 51 | ### Referral: 52 | 53 | https://link.trustwallet.com/referral 54 | 55 | ## Staking 56 | 57 | ### Stake details: 58 | 59 | - `coin` slip44 index 60 | 61 | https://link.trustwallet.com/stake?coin=118 62 | 63 | ### Stake / Delegate: 64 | 65 | - `coin` slip44 index 66 | - `id` validator / delegator to be selected. Optional 67 | 68 | https://link.trustwallet.com/stake_delegate?coin=118&id=cosmosvaloper156gqf9837u7d4c4678yt3rl4ls9c5vuursrrzf 69 | 70 | ### Unstake / Undelegate: 71 | 72 | - `coin` slip44 index 73 | 74 | https://link.trustwallet.com/stake_undelegate?coin=118 75 | 76 | ### Claim Rewards: 77 | 78 | - `coin` slip44 index 79 | 80 | https://link.trustwallet.com/stake_claim_rewards?coin=118 81 | 82 | ## Exchange 83 | 84 | ### Open Swap: 85 | 86 | - `from` asset in [UAI format](/assets/universal_asset_id.md) 87 | - `to` asset in [UAI format](/assets/universal_asset_id.md) 88 | 89 | https://link.trustwallet.com/swap?from=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F&to=c60 90 | 91 | ### Open Exchange: 92 | 93 | - `from` asset in [UAI format](/assets/universal_asset_id.md) 94 | - `to` asset in [UAI format](/assets/universal_asset_id.md) 95 | 96 | https://link.trustwallet.com/exchange?from=c714_tRUNE-B1A&to=c714 97 | 98 | ### Open Buy Crypto 99 | 100 | - `asset` asset in [UAI format](/assets/universal_asset_id.md) 101 | 102 | https://link.trustwallet.com/buy?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F 103 | 104 | ### Open Market Info 105 | 106 | - `asset` asset in [UAI format](/assets/universal_asset_id.md) 107 | 108 | https://link.trustwallet.com/market?asset=c60_t0x6B175474E89094C44Da98b954EedeAC495271d0F 109 | 110 | ### Open Notifications 111 | 112 | https://link.trustwallet.com/notifications 113 | 114 | ### Open Price alerts 115 | 116 | https://link.trustwallet.com/alerts 117 | 118 | #### Available domains links: 119 | 120 | - `https://link.trustwallet.com` 121 | - `trust://` 122 | 123 | #### Definition 124 | 125 | slip44 index - https://github.com/satoshilabs/slips/blob/master/slip-0044.md 126 | 127 | 128 | ## WalletConnect 129 | 130 | ### Connect to a WalletConnect session 131 | 132 | https://link.trustwallet.com/wc?uri=wc%3Aca1fccc0-f4d1-46c2-90b7-c07fce1c0cae%401%3Fbridge%3Dhttps%253A%252F%252Fbridge.walletconnect.org%26key%3Da413d90751839c7628873557c718fd73fcedc5e8e8c07cfecaefc0d3a178b1d8 133 | 134 | #### Available domains links: 135 | 136 | - `https://link.trustwallet.com` 137 | - `trust://` 138 | -------------------------------------------------------------------------------- /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. 5 | -------------------------------------------------------------------------------- /media/android-dapp-emulator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/android-dapp-emulator.png -------------------------------------------------------------------------------- /media/android-install-apk-emulator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/android-install-apk-emulator.png -------------------------------------------------------------------------------- /media/edge-inspect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/edge-inspect.png -------------------------------------------------------------------------------- /media/edge-inspect2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/edge-inspect2.png -------------------------------------------------------------------------------- /media/js-eth-sign-console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/js-eth-sign-console.png -------------------------------------------------------------------------------- /media/js-eth-sign.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/js-eth-sign.png -------------------------------------------------------------------------------- /media/sourcetrail-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/sourcetrail-screenshot.png -------------------------------------------------------------------------------- /media/staking-steps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/staking-steps.png -------------------------------------------------------------------------------- /media/wallet-core-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/wallet-core-banner.png -------------------------------------------------------------------------------- /media/wallet-core.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cryptocool1/developer/46485da130d3371c9ceb95c100a220ca64058cdb/media/wallet-core.png -------------------------------------------------------------------------------- /wallet-connect/dapp.md: -------------------------------------------------------------------------------- 1 | # DApp Integration 2 | 3 | Trust extends WalletConnect with aditional 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/coins.md) implements `signJSON` method in wallet core 4 | 5 | __Supported Coins__ 6 | 7 | - Binance Chain 8 | - Ethereum and forks 9 | - Cosmos, Kava and other sdk based chains 10 | - Tezos 11 | - Nano 12 | - Filecoin (until mainnet) 13 | 14 | ## Getting started 15 | 16 | To use Trust additional methods, you just need to install: 17 | 18 | ```bash 19 | npm install --save @walletconnect/client @walletconnect/qrcode-modal 20 | ``` 21 | 22 | ### Initiate Connection 23 | 24 | Before you can sign transactions, you have to initiate a connection to a WalletConnect bridge server, and handle all possible states: 25 | (code snippet below is copied from https://docs.walletconnect.org/quick-start/dapps/client#initiate-connection) 26 | 27 | ```javascript 28 | import WalletConnect from "@walletconnect/client"; 29 | import QRCodeModal from "@walletconnect/qrcode-modal"; 30 | 31 | // Create a connector 32 | const connector = new WalletConnect({ 33 | bridge: "https://bridge.walletconnect.org", // Required 34 | qrcodeModal: QRCodeModal, 35 | }); 36 | 37 | // Check if connection is already established 38 | if (!connector.connected) { 39 | // create new session 40 | connector.createSession(); 41 | } 42 | 43 | // Subscribe to connection events 44 | connector.on("connect", (error, payload) => { 45 | if (error) { 46 | throw error; 47 | } 48 | 49 | // Get provided accounts and chainId 50 | const { accounts, chainId } = payload.params[0]; 51 | }); 52 | 53 | connector.on("session_update", (error, payload) => { 54 | if (error) { 55 | throw error; 56 | } 57 | 58 | // Get updated accounts and chainId 59 | const { accounts, chainId } = payload.params[0]; 60 | }); 61 | 62 | connector.on("disconnect", (error, payload) => { 63 | if (error) { 64 | throw error; 65 | } 66 | 67 | // Delete connector 68 | }); 69 | ``` 70 | 71 | ### Get Accounts 72 | 73 | Once you have `walletconnect client` set up, you will be able to get user's accounts: 74 | 75 | ```javascript 76 | 77 | const request = connector._formatRequest({ 78 | method: 'get_accounts', 79 | }); 80 | 81 | connector 82 | ._sendCallRequest(request) 83 | .then(result => { 84 | // Returns the accounts 85 | console.log(result); 86 | }) 87 | .catch(error => { 88 | // Error returned when rejected 89 | console.error(error); 90 | }); 91 | ``` 92 | 93 | The result is an array with following structure: 94 | ```javascript 95 | [ 96 | { 97 | network: number, 98 | address: string 99 | } 100 | ] 101 | ``` 102 | 103 | ### Sign Transaction 104 | 105 | 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. 106 | 107 | ```javascript 108 | const network = 118; // Atom (SLIP-44) 109 | const account = accounts.find((account) => account.network === network); 110 | // Transaction structure based on Trust's protobuf messages. 111 | const tx = { 112 | accountNumber: "1035", 113 | chainId: "cosmoshub-2", 114 | fee: { 115 | amounts: [ 116 | { 117 | denom: "uatom", 118 | amount: "5000" 119 | } 120 | ], 121 | gas: "200000" 122 | }, 123 | sequence: "40", 124 | sendCoinsMessage: { 125 | fromAddress: account.address, 126 | toAddress: "cosmos1zcax8gmr0ayhw2lvg6wadfytgdhen25wrxunxa", 127 | amounts: [ 128 | { 129 | denom: "uatom", 130 | amount: "100000" 131 | } 132 | ] 133 | } 134 | }; 135 | 136 | const request = connector._formatRequest({ 137 | method: 'trust_signTransaction', 138 | params: [ 139 | { 140 | network, 141 | transaction: JSON.stringify(tx), 142 | }, 143 | ], 144 | }); 145 | 146 | connector 147 | ._sendCallRequest(request) 148 | .then(result => { 149 | // Returns transaction signed in json or encoded format 150 | console.log(result); 151 | }) 152 | .catch(error => { 153 | // Error returned when rejected 154 | console.error(error); 155 | }); 156 | ``` 157 | 158 | The result can be either a string JSON or an HEX encoded string. For Atom, the result is JSON: 159 | 160 | ```json 161 | { 162 | "tx": { 163 | "fee": { 164 | "amount": [{ 165 | "amount": "5000", 166 | "denom": "uatom" 167 | }], 168 | "gas": "200000" 169 | }, 170 | "memo": "", 171 | "msg": [{ 172 | "type": "cosmos-sdk/MsgSend", 173 | "value": { 174 | "amount": [{ 175 | "amount": "100000", 176 | "denom": "uatom" 177 | }], 178 | "from_address": "cosmos135qla4294zxarqhhgxsx0sw56yssa3z0f78pm0", 179 | "to_address": "cosmos1zcax8gmr0ayhw2lvg6wadfytgdhen25wrxunxa" 180 | } 181 | }], 182 | "signatures": [{ 183 | "pub_key": { 184 | "type": "tendermint/PubKeySecp256k1", 185 | "value": "A+mYPFOMSp6IYyXsW5uKTGWbXrBgeOOFXHNhLGDsGFP7" 186 | }, 187 | "signature": "m10iqKAHQ5Ku5f6NcZdP29fPOYRRR+p44FbGHqpIna45AvYWrJFbsM45xbD+0ueX+9U3KYxG/jSs2I8JO55U9A==" 188 | }], 189 | "type": "cosmos-sdk/MsgSend" 190 | } 191 | } 192 | ``` 193 | -------------------------------------------------------------------------------- /wallet-connect/wallet-connect.md: -------------------------------------------------------------------------------- 1 | # WalletConnect 2 | 3 | [WalletConnect](https://walletconnect.org/) Swift SDK, implements 1.0.0 websocket based protocol. 4 | 5 | Demo video: 6 | 7 | [![How to Use WalletConnect to Trade on Binance DEX](https://img.youtube.com/vi/kI6UiqudBng/0.jpg)](https://www.youtube.com/watch?v=kI6UiqudBng) 8 | 9 | Features: 10 | 11 | - [x] Connect and disconnect 12 | - [x] Approve / Reject / Kill session 13 | - [x] Approve and reject ethereum transactions `eth_sign` / `personal_sign` / `eth_sendTransaction` 14 | - [x] Approve and reject binance dex orders `bnb_sign` 15 | - [x] Sign Transactions `trust_sign` (full documentation [here](/wallet-connect/dapp.md)) 16 | 17 | ## Example 18 | 19 | To run the example project, clone the repo, and run `pod install` from the Example directory first. 20 | 21 | ## Installation 22 | 23 | WalletConnect is available through [CocoaPods](https://cocoapods.org). To install 24 | it, simply add the following line to your Podfile: 25 | 26 | ```ruby 27 | pod 'WalletConnect', git: 'git@github.com:trustwallet/wallet-connect-swift.git', branch: 'master' 28 | ``` 29 | 30 | ## Usage 31 | 32 | parse session from scanned QR code: 33 | 34 | ```swift 35 | let string = "wc:..." 36 | guard let session = WCSession.from(string: string) else { 37 | // invalid session 38 | return 39 | } 40 | // handle session 41 | ``` 42 | 43 | configure and handle incoming message: 44 | 45 | ```swift 46 | let interactor = WCInteractor(session: session, meta: clientMeta) 47 | interactor.onSessionRequest = { [weak self] (id, peer) in 48 | // ask for user consent 49 | } 50 | 51 | interactor.onDisconnect = { [weak self] (error) in 52 | // handle disconnect 53 | } 54 | 55 | interactor.onEthSign = { [weak self] (id, params) in 56 | // handle eth_sign and personal_sign 57 | } 58 | 59 | interactor.onEthSendTransaction = { [weak self] (id, transaction) in 60 | // handle eth_sendTransaction 61 | } 62 | 63 | interactor.onBnbSign = { [weak self] (id, order) in 64 | // handle bnb_sign 65 | } 66 | 67 | interactor.onTrustSignTransaction = { [weak self] (id, transaction) in 68 | // handle trust_signTransaction 69 | } 70 | ``` 71 | 72 | approve session 73 | 74 | ```swift 75 | interactor.approveSession(accounts: accounts, chainId: chainId).done { 76 | print("<== approveSession done") 77 | }.cauterize() 78 | ``` 79 | 80 | approve request 81 | 82 | ```swift 83 | interactor.approveRequest(id: id, result: result.hexString).done { 84 | print("<== approveRequest done") 85 | }.cauterize() 86 | ``` 87 | 88 | approve binance dex orders 89 | 90 | ```swift 91 | interactor?.approveBnbOrder(id: id, signed: signed).done({ confirm in 92 | print("<== approveBnbOrder", confirm) 93 | }).cauterize() 94 | ``` 95 | 96 | ## Author 97 | 98 | hewigovens 99 | 100 | ## License 101 | 102 | WalletConnect is available under the MIT license. See the LICENSE file for more info. 103 | -------------------------------------------------------------------------------- /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 | Add this dependency to build.gradle: 16 | ``` 17 | dependencies { 18 | implementation "com.trustwallet:wallet-core:0.12.31" 19 | } 20 | ``` 21 | 22 | ## Code Examples 23 | 24 | In the following sections we show code examples for some common funcions. 25 | Please refer to the [Wallet Usage Guide](wallet-core-usage.md) for detailed explanations. 26 | 27 | ### Wallet Management 28 | 29 | First thing we need is to load JNI library 30 | 31 | ```kotlin 32 | init { 33 | System.loadLibrary("TrustWalletCore") 34 | } 35 | ``` 36 | 37 | Creating or Importing a Multi-Coin HD Wallet 38 | 39 | ```kotlin 40 | val wallet = HDWallet(128, "") 41 | ``` 42 | 43 | ```kotlin 44 | val wallet = HDWallet("ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", "") 45 | ``` 46 | 47 | 48 | ### Account Address Derivation 49 | 50 | Generating the Default Address for a Coin 51 | 52 | ```kotlin 53 | val addressBTC = wallet.getAddressForCoin(CoinType.BITCOIN) 54 | val addressETH = wallet.getAddressForCoin(CoinType.ETHEREUM) 55 | val addressBNB = wallet.getAddressForCoin(CoinType.BINANCE) 56 | ``` 57 | 58 | Generating an Address Using a Custom Derivation Path (Expert) 59 | 60 | ```kotlin 61 | val key = wallet.getKey("m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0 62 | val address = CoinType.ETHEREUM.deriveAddress(key) 63 | ``` 64 | 65 | 66 | ### Transaction Signing 67 | 68 | In general, when creating a new blockchain transaction, a wallet has to: 69 | 70 | 1. Put together a transaction with relevant fields (source, target, amount, etc.) 71 | 2. Sign the transaction, using the account private key. This is done by Wallet Core. 72 | 3. Send to a node for broadcasting to the blockchain network. 73 | 74 | Ethereum Transaction Signing 75 | 76 | Code example to fill in signer input parameters, perform signing, and retrieve encoded result: 77 | 78 | ```kotlin 79 | val signerInput = Ethereum.SigningInput.newBuilder().apply { 80 | this.chainId = ByteString.copyFrom(BigInteger("01").toByteArray()) 81 | this.gasPrice = BigInteger("d693a400", 16).toByteString() // decimal 3600000000 82 | this.gasLimit = BigInteger("5208", 16).toByteString() // decimal 21000 83 | this.toAddress = dummyReceiverAddress 84 | this.transaction = Ethereum.Transaction.newBuilder().apply { 85 | this.transfer = Ethereum.Transaction.Transfer.newBuilder().apply { 86 | this.amount = BigInteger("0348bca5a16000", 16).toByteString() 87 | }.build() 88 | }.build() 89 | this.privateKey = ByteString.copyFrom(secretPrivateKey.data()) 90 | }.build() 91 | val output = AnySigner.sign(signerInput, CoinType.ETHEREUM, Ethereum.SigningOutput.parser()) 92 | println("Signed transaction: \n${signerOutput.encoded.toByteArray().toHexString()}") 93 | ``` 94 | -------------------------------------------------------------------------------- /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 | 12 | The following *development platforms* are supported: 13 | 14 | * **macOS**: is the *primary* development platform, as it supports compiling for both target platforms. 15 | * **Linux**: is partially supported as a development platform. 16 | 17 | ## Build Methods 18 | 19 | Wallet Core can be build inside a Docker image, or natively. 20 | 21 | * 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. 22 | * Natively, in your dev OS (macOS, Linux). 23 | 24 | ## Prerequisites 25 | 26 | Here is the list of required prerequisites. 27 | 28 | ### Prerequisites on macOS 29 | 30 | * CMake `brew install cmake` 31 | * Boost `brew install boost` 32 | * Xcode 33 | * Xcode command line tools: `xcode-select --install` 34 | * Other tools: `brew install git ninja autoconf automake libtool xcodegen clang-format` 35 | * Cocoapods for iOS: `sudo gem install cocoapods` 36 | * [Android Studio](https://developer.android.com/studio/index.html) 37 | * [Android NDK](https://developer.android.com/ndk/guides/) 38 | 39 | ### Prerequisites on Linux 40 | 41 | * Various packages `sudo apt-get install autoconf git libcurl4-openssl-dev libicu-dev libssl-dev libtool ninja-build nodejs pkg-config unzip` 42 | * CLang 43 | * Ruby 2.6 (`rbenv` from https://github.com/rbenv/ruby-build, then `rbenv install 2.6.3`) 44 | * Boost (from https://dl.bintray.com/boostorg/release/1.66.0/source/boost_1_66_0.tar.gz) 45 | * CMake (from https://github.com/Kitware/CMake/releases) 46 | * [Android Studio](https://developer.android.com/studio/index.html) 47 | 48 | ### Managed Prerequisites 49 | 50 | 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). 51 | 52 | * Google test 53 | * Check 54 | * Json 55 | * Protobuf 56 | 57 | ## Full Build 58 | 59 | The full build can be triggered with one top-level script: 60 | 61 | ```shell 62 | ./bootstrap.sh 63 | ``` 64 | 65 | Or, broken up in smaller steps: 66 | 67 | ```shell 68 | ./tools/install-dependencies 69 | ``` 70 | 71 | This script downloads and compiles some prerequisites. 72 | 73 | ```shell 74 | ./tools/generate-files 75 | ``` 76 | 77 | This script generates source files, coin- and protobuf files. Needs to be re-run whenever `coins.json` or protobuf files are changes. 78 | 79 | ```shell 80 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug 81 | make -Cbuild 82 | ``` 83 | 84 | Standard CMake and make commands for building the library. The `cmake` command needs to be re-run whenever a new source file is added. 85 | 86 | After build, *unit tests* can be executed: 87 | 88 | ```shell 89 | ./build/tests/tests tests --gtest_filter=* 90 | ``` 91 | 92 | 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. 93 | 94 | ## Building inside Docker image 95 | 96 | Here are the instructions to build Wallet Core with the provided `Dockerfile`. 97 | 98 | Prerequisite is a working Docker installation. 99 | 100 | The command for building the Docker image: 101 | 102 | ```shell 103 | docker build docker/wallet-core --tag wallet-core-dev 104 | ``` 105 | 106 | Then launch the container: 107 | 108 | ```shell 109 | docker run -i -t wallet-core-dev /bin/bash 110 | ``` 111 | 112 | Inside the container the build commands can be executed (as described above; note that install-dependencies is not necessary): 113 | 114 | ```shell 115 | cd wallet-core 116 | ./tools/generate-files 117 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug 118 | make -Cbuild 119 | ``` 120 | 121 | ## Executing inside Docker image 122 | 123 | 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. 124 | *Note:* this may not be the most recent version! 125 | 126 | Unit tests and [wallet console utility](walletconsole.md) can be executed straight from this Docker image: 127 | 128 | ```shell 129 | docker run -i -t trustwallet/wallet-core 130 | cd wallet-core 131 | ./build/tests/tests tests 132 | ./build/walletconsole/walletconsole 133 | exit 134 | ``` 135 | 136 | ## Linux 137 | 138 | Building on Linux is possible, but not fully supported, 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. 139 | Otherwise, the prerequisites have to be installed manually. 140 | 141 | ## Unit tests with Coverage 142 | 143 | Coverage info can be seen in the GitHub [CI builds](https://codecov.io/gh/trustwallet/wallet-core), 144 | but can be generated locally as well. 145 | 146 | Steps for running unit tests with coverage measurement, and creating report locally: 147 | 148 | ```bash 149 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug -DCODE_COVERAGE=ON 150 | make -Cbuild -j12 tests 151 | find . -name "*.gcda" -exec rm {} \; 152 | ./build/tests/tests tests --gtest_filter=* 153 | rm -rf coverage.info coverage/ 154 | tools/coverage html 155 | ``` 156 | 157 | See also 158 | [tools/coverage](https://github.com/trustwallet/wallet-core/blob/master/tools/coverage) and 159 | [linux-ci.yml](https://github.com/trustwallet/wallet-core/blob/master/.github/workflows/linux-ci.yml). 160 | -------------------------------------------------------------------------------- /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 | ![](/media/wallet-core.png) 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 | ![](/media/sourcetrail-screenshot.png) 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 `coins.json`, the generated code will locate at `src/Generated/Coins.cpp`. 123 | 124 | ```json 125 | { 126 | "id": "bitcoin", // coin id 127 | "name": "Bitcoin", // coin name 128 | "symbol": "BTC", // coin symbol 129 | "decimals": 8, // minimum currency unit, e.g. a satoshi is 0.00000001 ฿ 130 | "blockchain": "Bitcoin", // blockchain type 131 | "derivationPath": "m/84'/0'/0'/0/0", // default path for derivating private key from a mnemonic 132 | "curve": "secp256k1", // elliptic curve used in Bitcoin's public key cryptography 133 | "publicKeyType": "secp256k1", // public key type 134 | "p2pkhPrefix": 0, // [optional] pay-to-pubkey hash address prefix 135 | "p2shPrefix": 5, // [optional] pay-to-script hash address prefix 136 | "hrp": "bc", // [optional] human readable part for bech32 address 137 | "publicKeyHasher": "sha256ripemd", // [optional] xpub / xprv fingerprint hasher 138 | "base58Hasher": "sha256d", // [optional] xpub / xprv base58 hasher, base58(hasher(hd node data)) 139 | "xpub": "zpub", // [optional] hd version bytes defined in slip-0132 140 | "xprv": "zprv", // [optional] hd version bytes defined in slip-0132 141 | "explorer": { 142 | "url": "https://blockchair.com", // block explorer 143 | "txPath": "/bitcoin/transaction/", // path to view transaction detail 144 | "accountPath": "/bitcoin/address/", // path to view account / address detail 145 | "sampleTx": "0607f62530b68cfcc91c57a1702841dd399a899d0eecda8e31ecca3f52f01df2", // [optional] sample transaction id 146 | "sampleAccount": "17A16QmavnUfCW11DAApiJxp7ARnxN5pGX" // [optional] sample account / address 147 | }, 148 | "info": { 149 | "url": "https://ethereum.org", // project homepage 150 | "client": "https://github.com/ethereum/go-ethereum", // rpc node to query balance, utxo, send transactions 151 | "clientPublic": "https://mainnet.infura.io", // public rpc/api node to query balance, utxo, send transactions 152 | "clientPuclicDocs": "https://github.com/ethereum/wiki/wiki/JSON-RPC" // API Reference 153 | } 154 | } 155 | ``` 156 | 157 | ## Protocol Buffers 158 | 159 | 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`. 160 | 161 | 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. 162 | 163 | ## Code Style 164 | 165 | 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. 166 | 167 | ## More 168 | 169 | * [Build instructions](building.md) 170 | * [Adding Support for a New Blockchain](newblockchain.md) 171 | * [Releasing](releasing.md) 172 | -------------------------------------------------------------------------------- /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` CI build (executed on PRs and commits) contains 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`, to enable coverage measurement 26 | 27 | ```shell 28 | cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug -DCODE_COVERAGE=ON 29 | ``` 30 | 31 | - Build tests 32 | 33 | ```shell 34 | make -Cbuild -j12 tests TrezorCryptoTests 35 | ``` 36 | 37 | 38 | - Cleanup any old coverage files, and run unit tests 39 | 40 | ```shell 41 | find . -name "*.gcda" -exec rm {} \; 42 | ./build/trezor-crypto/crypto/tests/TrezorCryptoTests 43 | ./build/tests/tests tests --gtest_output=xml 44 | ``` 45 | 46 | - Generate coverage info (slow). With the `html` argument the script will generate HTML report as well: 47 | 48 | ```shell 49 | ./tools/coverage html 50 | ``` 51 | 52 | if you see genhtml (from lcov) error on macOS like below: 53 | 54 | ```shell 55 | c++filt: Unknown command line argument '--no-strip-underscores'. Try: '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++filt --help' 56 | c++filt: Did you mean '--no-strip-underscore'? 57 | genhtml: ERROR: c++filt output not as expected (0 vs 11) lines 58 | ``` 59 | please 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 | -------------------------------------------------------------------------------- /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 | 20 | -------------------------------------------------------------------------------- /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 | ## Code Examples 30 | 31 | In the following sections we show code examples for some common funcions. 32 | Please refer to the [Wallet Usage Guide](wallet-core-usage.md) for detailed explanations. 33 | 34 | Accessing Wallet Core functionality requires one import statement: 35 | 36 | ```swift 37 | import WalletCore 38 | ``` 39 | 40 | ### Wallet Management 41 | 42 | Creating or Importing a Multi-Coin HD Wallet 43 | 44 | ```swift 45 | let wallet = HDWallet(strength: 128, passphrase: "") 46 | ``` 47 | 48 | ```swift 49 | let wallet = HDWallet(mnemonic: "ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", passphrase: "")! 50 | ``` 51 | 52 | 53 | ### Account Address Derivation 54 | 55 | Generating the Default Address for a Coin 56 | 57 | ```swift 58 | let addressBTC = wallet.getAddressForCoin(coin: .bitcoin) 59 | let addressETH = wallet.getAddressForCoin(coin: .ethereum) 60 | let addressBNB = wallet.getAddressForCoin(coin: .binance) 61 | ``` 62 | 63 | Generating an Address Using a Custom Derivation Path (Expert) 64 | 65 | ```swift 66 | let key = wallet.getKey(derivationPath: "m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0 67 | let address = CoinType.ethereum.deriveAddress(privateKey: key) 68 | ``` 69 | 70 | 71 | ### Transaction Signing 72 | 73 | In general, when creating a new blockchain transaction, a wallet has to: 74 | 75 | 1. Put together a transaction with relevant fields (source, target, amount, etc.) 76 | 2. Sign the transaction, using the account private key. This is done by Wallet Core. 77 | 3. Send to a node for broadcasting to the blockchain network. 78 | 79 | Ethereum Transaction Signing 80 | 81 | Code example to fill in signer input parameters, perform signing, and retrieve encoded result: 82 | 83 | ```swift 84 | let signerInput = EthereumSigningInput.with { 85 | $0.chainID = Data(hexString: "01")! 86 | $0.gasPrice = Data(hexString: "d693a400")! // decimal 3600000000 87 | $0.gasLimit = Data(hexString: "5208")! // decimal 21000 88 | $0.toAddress = "0xC37054b3b48C3317082E7ba872d7753D13da4986" 89 | $0.transaction = EthereumTransaction.with { 90 | $0.transfer = EthereumTransaction.Transfer.with { 91 | $0.amount = Data(hexString: "0348bca5a16000")! 92 | } 93 | } 94 | $0.privateKey = wallet.getKeyForCoin(coin: .ethereum).data 95 | } 96 | let output: EthereumSigningOutput = AnySigner.sign(input: signerInput, coin: .ethereum) 97 | print(" data: ", output.encoded.hexString) 98 | ``` 99 | -------------------------------------------------------------------------------- /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/add_new_asset.md) section for more details. 8 | * 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. 9 | 10 | ## Integration Criteria 11 | 12 | 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. 13 | 14 | The general integration criteria is as follows: 15 | 16 | - The blockchain has launched mainnet and has stably run for at least 3 ~ 6 months without major security incidents. 17 | - The blockchain has extensive public documentation and tools available for developers to use. 18 | - The native coin is listed in the top 30 coins on CoinMarketCap and proposal gets approved on [https://governance.trustwallet.com]. 19 | - 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). 20 | - The native coin is tradable on major exchanges. 21 | 22 | After integrating into Trust Wallet projects are expected to provide timely support for any urgent matters. 23 | 24 | ## Overview 25 | 26 | Adding support for a new coin consists of these steps: 27 | 28 | * Add **coin definition** -- contains basic parameters of the new coin, several definition source files are gneerated from the definitions 29 | * Extend a few **central files**. There are a few central source files that need to be extended (some definitions, dispatching logic to coin implementations). 30 | * **C++ implementation** of **address** handling and **signing** functionality. Optionally protobuf definitions might be needed for more complex parameters. 31 | * **Unit tests** for coin definitions, and address and signing functionality 32 | * **C interface** (basis for mobile integration) 33 | * **Java/JNI** and **Swift** bindings -- these are generated 34 | * **Integration tests** for testing through C interface, and through JN and Swift interfaces. 35 | 36 | 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. 37 | 38 | 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. 39 | Coverage must not decrease! This is enforced automatically in the valiation of the pull requests. 40 | 41 | ## Blockchain definition 42 | 43 | The first step to add a blockchain is to define its coin configuration. Add the definition to the `coins.json` file. 44 | 45 | ## Skeleton generation 46 | 47 | Execute the command `codegen/bin/newcoin `, where `newcoin ` is the ID of the new coin from `coins.json`. This will generate skeleton `Address`, `Signer`, `Entry` classes, proto file, C interface for Signer and corresponding tests. 48 | 49 | Run `tools/generate-files` to generate message proto files. 50 | 51 | Run `cmake` to include the new files in the build (`cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug`), and build the project. 52 | 53 | ## Definition tests, first commit 54 | 55 | Review tests in `tests/X/TWCoinTypeTests.cpp` (where `X` is the name of the blockchain), exactly as in other blockchains. 56 | Run the tests and make sure everything is passing before moving on to the next step. 57 | You should reate a commit with this change, \(but don't create a pull request yet\). 58 | 59 | *Note:* don't forget to add new files to git. 60 | *Note:* don't forget to re-run `cmake` before building, to include new files in the build. 61 | 62 | ## C++ Implementation 63 | 64 | Implement the required functionality in C++. The code should be placed in the `src/X` folder where `X` is the name of the blockchain. 65 | 66 | 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. 67 | Adding new dependencies is something we want to avoid at all costs. We want to keep the codebase and the binary library as small as possible. 68 | 69 | 70 | 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. 71 | 72 | ### Entry point for coin functionality 73 | 74 | The `Entry` class should be kept minimal, it should have no logic, just call into relevant Address, Signer, etc. classes. 75 | 76 | Include the new coin Entry class in the list of coin dispatchers, in `src/Coin.cpp` (an include, a new instance in the list of dispatcher instances). 77 | 78 | ### Address encoding/decoding 79 | 80 | The first step is to support the address format specific to the blockchain. Start with the generated source files `src/X/Address.h` and `src/X/Address.cpp` (where `X` is the blockchain name). 81 | 82 | 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. 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. 83 | 84 | For an example of this have a look at Cosmos [Address.h](https://github.com/trustwallet/wallet-core/blob/master/src/Cosmos/Address.h) and [Address.cpp](https://github.com/trustwallet/wallet-core/blob/master/src/Cosmos/Address.cpp). 85 | 86 | Make sure the dispatcher of address validation and derivation in `src/Coin.cpp` is also extended. 87 | 88 | ### Transaction signing 89 | 90 | The second step is supporting signing of transactions. Work on the `src/X/Signer.h` and `src/X/Signer.cpp` source files. 91 | Make sure you can generate a valid signature and a valid signed and encoded transaction. Write a unit tests for this. 92 | 93 | For an example of this have a look at Binance's [Signer.h](https://github.com/trustwallet/wallet-core/blob/master/src/Binance/Signer.h) and [Signer.cpp](https://github.com/trustwallet/wallet-core/blob/master/src/Binance/Signer.cpp). 94 | 95 | ### Tests 96 | 97 | The tests should be put in `tests/X` where `X` is the name of the blockchain. All C++ code needs to be unit tested. 98 | 99 | The C++ implementation with tests should be a separate commit. 100 | 101 | ## C Interface 102 | 103 | Once you are satisfied with your C++ implementation, time to write some tests for C interface, usually you don't need to change the generated C interfaces, those C interfaces are made as small as possible so that clients don't need to worry about implementation details. If you are implementing blockchain `Xxx`, handle and implement it first in `TWAnyAddress.h` and `TWAnySigner.h` before writing tests. 104 | 105 | Please make sure you catch all C++ exceptions in C implementation. 106 | 107 | If possible test the interface on Android, iOS. Optionally add integration test to each platform. This is required only if the interface is significantly different than the interface used for other blockchains. 108 | 109 | The C interface, any Protobuf models, and integration tests should be a separate commit. 110 | 111 | ## Blockchain checklist 112 | 113 | The above steps are summarized below as a checklist: 114 | 115 | * [ ] Coin Definition: 116 | * [ ] Add the coin definition to `coins.json`. 117 | * [ ] Execute `codegen/bin/newcoin `. 118 | * [ ] Execute `tools/generate-files`. 119 | * [ ] Add coin dispatcher to `src/Coin.cpp`. 120 | * [ ] Create tests in `tests/Xxx/TWCoinTypeTests.cpp`. 121 | * [ ] Implement functionality in C++. Put it in a subfolder of `src/`. 122 | * [ ] Entry. 123 | * [ ] Address. 124 | * [ ] Transaction \(if necessary\). 125 | * [ ] Signer. 126 | * [ ] Write unit tests. Put them in a subfolder of `tests/`. 127 | * [ ] `Mnemonic phrase - > Address` derivation test. Put this test in the `CoinTests.cpp` file. 128 | * [ ] Transaction signing tests, at least one mainnet transaction test. 129 | * [ ] Add stake, unstake, get rewards tests if the blockchain is PoS like. 130 | * [ ] Add relevant constants in `TWEthereumChainID`, `TWCurve`, etc., as necessary. 131 | * [ ] Implement C interface in `src/interface`. 132 | * [ ] Add tests for `TWAnyAddress` and `TWAnySigner` 133 | * [ ] Validate generated code in Android an iOS projects. Write integration tests for each. 134 | * [ ] Extend central derivation and validation tests: make sure the following tests are extended with the new coin: `CoinAddressDerivationTests.cpp` and 135 | `CoinAddressValidationTests.cpp`, 136 | `TWHRPTests.cpp`, 137 | `CoinAddressDerivationTests.kt`, 138 | `CoinAddressDerivationTests.swift`. 139 | 140 | * [ ] Upload coin icon to [trustwallet/assets](https://github.com/trustwallet/assets/#how-to-add-asset) if necessary. 141 | 142 | ### Bitcoin forks checklist 143 | 144 | 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: 145 | 146 | - [ ] Derive address according to definition in `coins.json`, `p2pkh` address for `bip44` or native `bech32` segwit address for `bip84`. 147 | - [ ] Check [SLIP-0132 :Registered HD version bytes](https://github.com/satoshilabs/slips/blob/master/slip-0132.md). 148 | - [ ] Check fee preference, use static fee or not, Trust will use fee that can be confirmed with in 2 blocks. 149 | - [ ] Add tests to validate all possible addresses, `p2pkh`, `p2sh` and `bech32`. 150 | - [ ] Add tests to derive `xpub` / `xprv` and cross check the values with other wallets, like ledger or trezor. 151 | - [ ] Add tests to derive address from `xpub` at random index. 152 | - [ ] Add tests to cover lock scripts for all addresses. 153 | - [ ] Add tests to make sure transaction detail url in block explorer is correct. 154 | - [ ] Add a mainnet transaction test, you can construct it by using wallet core and validate it by broadcasting it. 155 | -------------------------------------------------------------------------------- /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 | ```text 21 | BINTRAY_USER=user 22 | BINTRAY_KEY=key 23 | ``` 24 | 25 | ## Docker Hub 26 | 27 | We need to release a new prebuilt Docker image every time our dependencies or sources change. 28 | To build the docker image(s), see `tools/docker-build`. Use `docker push` to upload to Docker Hub. 29 | -------------------------------------------------------------------------------- /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, alternatively [Rosetta](https://www.rosetta-api.org/) Data API is also welcomed. 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 Block Atlas: 16 | 17 | At first, please read [Block Atlas Developer Guide](https://developer.trustwallet.com/blockatlas/newblockchain), We need API or RPC to: 18 | 19 | - [ ] query sent / received list of transactions for an account / address 20 | - [ ] query transactions in a block 21 | 22 | ## Example 23 | 24 | We will take XRP as an example here, it supports WebSocket, JSON-RPC (including over HTTP) 25 | 26 | - [x] query account / address balance 27 | - - JSON RPC method: `account_info` (https://xrpl.org/account_info.html) 28 | - [x] query transaction details 29 | - - JSON RPC method: `tx` (https://xrpl.org/tx.html) 30 | - [x] query fee / nonce for sending transaction 31 | - - fee: JSON RPC method: `fee` (https://xrpl.org/fee.html) 32 | - - nonce: same as `account_info`, you can find `Sequence` in response. 33 | - [x] query blockchain status (block height etc) 34 | - - JSON RPC method: `server_state` (https://xrpl.org/server_state.html) 35 | - [x] send raw transaction 36 | - - JSON RPC method: `submit` (https://xrpl.org/submit.html) 37 | - [x] query sent / received transactions for an account / address 38 | - - REST API: https://xrpl.org/data-api.html#get-account-transaction-history 39 | - [x] query transactions in a block 40 | - - REST API: https://xrpl.org/data-api.html#get-ledger 41 | -------------------------------------------------------------------------------- /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 | import "C" 27 | 28 | import "fmt" 29 | import "unsafe" 30 | import "encoding/hex" 31 | 32 | // C.TWString -> Go string 33 | func TWStringGoString(s unsafe.Pointer) string { 34 | return C.GoString(C.TWStringUTF8Bytes(s)) 35 | } 36 | 37 | // Go string -> C.TWString 38 | func TWStringCreateWithGoString(s string) unsafe.Pointer { 39 | cStr := C.CString(s) 40 | defer C.free(unsafe.Pointer(cStr)) 41 | str := C.TWStringCreateWithUTF8Bytes(cStr) 42 | return str 43 | } 44 | 45 | // C.TWData -> Go byte[] 46 | func TWDataGoBytes(d unsafe.Pointer) []byte { 47 | cBytes := C.TWDataBytes(d) 48 | cSize := C.TWDataSize(d) 49 | return C.GoBytes(unsafe.Pointer(cBytes), C.int(cSize)) 50 | } 51 | 52 | // Go byte[] -> C.TWData 53 | func TWDataCreateWithGoBytes(d []byte) unsafe.Pointer { 54 | cBytes := C.CBytes(d) 55 | defer C.free(unsafe.Pointer(cBytes)) 56 | data := C.TWDataCreateWithBytes((*C.uchar)(cBytes), C.ulong(len(d))) 57 | return data 58 | } 59 | 60 | func main() { 61 | fmt.Println("==> calling wallet core from go") 62 | str := TWStringCreateWithGoString("confirm bleak useless tail chalk destroy horn step bulb genuine attract split") 63 | emtpy := TWStringCreateWithGoString("") 64 | defer C.TWStringDelete(str) 65 | defer C.TWStringDelete(emtpy) 66 | 67 | fmt.Println("<== mnemonic is valid: ", C.TWHDWalletIsValid(str)) 68 | 69 | wallet := C.TWHDWalletCreateWithMnemonic(str, emtpy) 70 | defer C.TWHDWalletDelete(wallet) 71 | 72 | key := C.TWHDWalletGetKeyForCoin(wallet, C.TWCoinTypeBitcoin) 73 | keyData := C.TWPrivateKeyData(key) 74 | keyHex := hex.EncodeToString(TWDataGoBytes(keyData)) 75 | fmt.Println("<== bitcoin private key: ", keyHex) 76 | 77 | pubKey, _ := hex.DecodeString("0288be7586c41a0498c1f931a0aaf08c15811ee2651a5fe0fa213167dcaba59ae8") 78 | pubKeyData := TWDataCreateWithGoBytes(pubKey) 79 | defer C.TWDataDelete(pubKeyData) 80 | 81 | fmt.Println("<== bitcoin public key is valid: ", C.TWPublicKeyIsValid(pubKeyData, C.TWPublicKeyTypeSECP256k1)) 82 | 83 | address := C.TWHDWalletGetAddressForCoin(wallet, C.TWCoinTypeBitcoin) 84 | fmt.Println("<== bitcoin address: ", TWStringGoString(address)) 85 | } 86 | ``` 87 | 88 | 4. Compile it by `go build -o main` 89 | 5. Run `./main` and you will see the output below: 90 | 91 | ```shell 92 | ==> calling wallet core from go 93 | <== mnemonic is valid: true 94 | <== bitcoin private key: 945f423798858e24aa1ab490648013db63ad1f539ebbb8cb1399edd1d0b59716 95 | <== bitcoin public key is valid: true 96 | <== bitcoin address: bc1qw29x4hrt6tahz4jvuhzrq6y5el3spqt499zuay 97 | ``` 98 | 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. 99 | -------------------------------------------------------------------------------- /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 | 24 | ## Wallet Management 25 | 26 | ### Multi-Coin Wallet 27 | 28 | The Multi-Coin Wallet is a structure allowing accounts for many coins, all controlled by a single recovery phrase. 29 | It is a standard HD Wallet (Hierarchically Derived), employing the standard derivation schemes, interoperable with many other wallets: 30 | **BIP39** for recovery phrase, **BIP44**/**BIP84** for account derivation. 31 | 32 | ### Creating a New Multi-Coin Wallet 33 | 34 | When a new wallet is created, a new seed (and thus recovery phrase) is chosen at random. 35 | *After creation, the user has to be informed and guided to backup the recovery phrase.* 36 | 37 | The random generation employs secure random generation, as available on the device. 38 | 39 | ```swift 40 | let wallet = HDWallet(strength: 128, passphrase: "") 41 | ``` 42 | 43 | Input parameter | Description 44 | ---|--- 45 | *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. 46 | *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). 47 | 48 | ### Importing a Multi-Coin Wallet 49 | 50 | A previously created wallet can be imported using the recovery phrase. Typical usecases for import are: 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 | 67 | ## Account Address Derivation 68 | 69 | Each coin needs a different account, with matching address. Addresses are derived from the multi-coin wallet. 70 | Derivation is based on a *derivation path*, which is unique for each coin, but can have other parameters as well. 71 | 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. 72 | 73 | ### Generating the Default Address for a Coin 74 | 75 | The simplest is to get the default address for a coin -- this requires no further inputs. 76 | The address is generated using the default derivation path of the coin. 77 | 78 | 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: 79 | `bc1qpsp72plnsqe6e2dvtsetxtww2cz36ztmfxghpd`. 80 | For Ethereum, this is `0xA3Dcd899C0f3832DFDFed9479a9d828c6A4EB2A7`. 81 | 82 | Here is the sample code fort obtaining the default address for different coins: 83 | 84 | ```swift 85 | let addressBTC = wallet.getAddressForCoin(coin: .bitcoin) 86 | let addressETH = wallet.getAddressForCoin(coin: .ethereum) 87 | let addressBNB = wallet.getAddressForCoin(coin: .binance) 88 | ``` 89 | 90 | ### Generating an Address Using a Custom Derivation Path (Expert) 91 | 92 | It is also possible to derive addresses using custom derivation paths. 93 | This can be done in two steps: first a derived private key is obtained, then an address from it. 94 | 95 | > **Warning**: use this only if you are well aware of the semantics of the derivation path used! 96 | 97 | > **Security Warning**: if secrets such as private keys are handled by the wallet, even if for a short time, handle with care! 98 | > Avoid any risk of leakage of secrets! 99 | 100 | ```swift 101 | let key = wallet.getKey(derivationPath: "m/44\'/60\'/1\'/0/0") // m/44'/60'/1'/0/0 102 | let address = CoinType.ethereum.deriveAddress(privateKey: key) 103 | ``` 104 | 105 | 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), 106 | yielding address `0x68eF4e5660620976a5968c7d7925753D3Cc40809`. 107 | 108 | 109 | ## Transaction Signing 110 | 111 | In general, when creating a new blockchain transaction, a wallet has to: 112 | 113 | 1. Put together a transaction with relevant fields (source, target, amount, etc.) 114 | 2. Sign the transaction, using the account private key. This is done by Wallet Core. 115 | 3. Send to a node for broadcasting to the blockchain network. 116 | 117 | The exact fields needed for a transaction are different for each blockchain. 118 | In Wallet Core, signing input and output parameters are typically represented in a protobuf message 119 | (internally needed for serialization for passing through different language runtimes). 120 | 121 | A generic, coin-independent signer also exists (*AnySigner*), but its usage is recommended only in browser-based applications. 122 | 123 | ### Bitcoin Transaction Signing 124 | 125 | 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. 126 | 127 | The most important models in Swift are `BitcoinSigningInput` and `BitcoinUnspentTransaction` 128 | 129 | *BitcoinSigningInput* 130 | 131 | Field | Sample value | Description 132 | ---|---|--- 133 | hash_type | BitcoinSigHashType.all | *Bitcoin Cash* needs to `or` with `TitcoinSigHashType.fork` (see [Sighash](https://bitcoin.org/en/glossary/signature-hash) for more details) 134 | amount | 10000 | Amount (in satoshi) to send (value of new UTXO will be created) 135 | byteFee | 1 | Transaction fee is `byte_fee x transaction_size`, Wallet Core will calculate the fee for you by default 136 | toAddress | bc1q03h6k5lt6pzfjaanz5mlnmuc7aha2t3nkz7gh0 | Recipient address (Wallet Core will build lock script for you) 137 | changeAddress | 1AC4gh14wwZPULVPCdxUkgqbtPvC92PQPN | Address to receive changes, can be empty if you sweep a wallet 138 | privateKey | [Data(...), Data(...)] | Private keys for all the input UTXOs in this transaction 139 | scripts | [`script_hash`: Data(...)] | Redeem scripts indexed by script hash, usually for `P2SH`, `P2WPKH` or `P2WSH` 140 | utxo | [*BitcoinUnspentTransaction*] | All the input UTXOs, see below table for more details 141 | useMaxAmount | false | Consume all the input UTXOs, it will affect fee estimation and number of output 142 | coinType | 145 | [SLIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) coin type, default is 0 / Bitcoin 143 | 144 | *BitcoinUnspentTransaction* 145 | 146 | Field | Sample value | Description 147 | ---|---|--- 148 | outPoint | *BitcoinOutPoint(hash:index:)* | Refer to a particular transaction output, consisting of a 32-byte TXID and a 4-byte output index number (vout) 149 | amount | 10000 | A value field for transferring zero or more satoshis 150 | script | 0x76a9146cfa0e96c34fce09c0e4e671fcd43338c14812e588ac | A script (ScriptPubKey) included in outputs which sets the conditions that must be fulfilled for those satoshis to be spent 151 | 152 | Here is the Swift sample code for signing a real world Bitcoin Cash [transaction](https://blockchair.com/bitcoin-cash/transaction/96ee20002b34e468f9d3c5ee54f6a8ddaa61c118889c4f35395c2cd93ba5bbb4) 153 | 154 | ```swift 155 | 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 156 | let privateKey = PrivateKey(data: Data(hexString: "7fdafb9db5bc501f2096e7d13d331dc7a75d9594af3d251313ba8b6200f4e384")!)! 157 | let address = CoinType.bitcoinCash.deriveAddress(privateKey: privateKey) 158 | 159 | let utxo = BitcoinUnspentTransaction.with { 160 | $0.outPoint.hash = Data(utxoTxId.reversed()) // reverse of UTXO tx id, Bitcoin internal expects network byte order 161 | $0.outPoint.index = 2 // outpoint index of this this UTXO, "vout" field from blockbook utxo api 162 | $0.outPoint.sequence = UINT32_MAX 163 | $0.amount = 5151 // value of this UTXO, "value" field from blockbook utxo api 164 | $0.script = BitcoinScript.buildForAddress(address: address, coin: .bitcoinCash).data // Build lock script from address or public key hash 165 | } 166 | 167 | let input = BitcoinSigningInput.with { 168 | $0.hashType = BitcoinSigHashType.all.rawValue | BitcoinSigHashType.fork.rawValue 169 | $0.amount = 600 170 | $0.byteFee = 1 171 | $0.toAddress = "1Bp9U1ogV3A14FMvKbRJms7ctyso4Z4Tcx" 172 | $0.changeAddress = "1FQc5LdgGHMHEN9nwkjmz6tWkxhPpxBvBU" // can be same sender address 173 | $0.utxo = [utxo] 174 | $0.privateKey = [privateKey.data] 175 | } 176 | 177 | let output: BitcoinSigningOutput = AnySigner.sign(input: input, coin: .bitcoinCash) 178 | guard output.error.isEmpty else { return } 179 | // encoded transaction to broadcast 180 | print(output.encoded) 181 | ``` 182 | It's worth to note that you can also calcuate fee and change manually (by using a `BitcoinTransactionPlan` struct) 183 | Below is another real world Zcash [transparent transaction](https://explorer.zcha.in/transactions/ec9033381c1cc53ada837ef9981c03ead1c7c41700ff3a954389cfaddc949256) demonstrate this 184 | 185 | ```swift 186 | let utxos = [ 187 | BitcoinUnspentTransaction.with { 188 | $0.outPoint.hash = Data(hexString: "53685b8809efc50dd7d5cb0906b307a1b8aa5157baa5fc1bd6fe2d0344dd193a")! 189 | $0.outPoint.index = 0 190 | $0.outPoint.sequence = UINT32_MAX 191 | $0.amount = 494000 192 | $0.script = Data(hexString: "76a914f84c7f4dd3c3dc311676444fdead6e6d290d50e388ac")! 193 | } 194 | ] 195 | 196 | let input = BitcoinSigningInput.with { 197 | $0.hashType = BitcoinSigHashType.all.rawValue 198 | $0.amount = 488000 199 | $0.toAddress = "t1QahNjDdibyE4EdYkawUSKBBcVTSqv64CS" 200 | $0.coinType = CoinType.zcash.rawValue 201 | $0.privateKey = [Data(hexString: "a9684f5bebd0e1208aae2e02bc9e9163bd1965ad23d8538644e1df8b99b99559")!] 202 | $0.plan = BitcoinTransactionPlan.with { 203 | $0.amount = 488000 204 | $0.fee = 6000 205 | $0.change = 0 206 | // Sapling branch id 207 | $0.branchID = Data(hexString: "0xbb09b876")! 208 | $0.utxos = utxos 209 | } 210 | } 211 | 212 | let output: BitcoinSigningOutput = AnySigner.sign(input: input, coin: .zcash) 213 | 214 | // encoded transaction to broadcast 215 | print(output.encoded) 216 | ``` 217 | 218 | 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. 219 | 220 | ### Ethereum Transaction Signing 221 | 222 | A simple Ethereum send transaction needs the following fields: 223 | 224 | Field | Sample value | Description 225 | ---|---|--- 226 | chainID | 1 | Network selector, use 1 for mainnet (see https://chainid.network for more) 227 | nonce | 1 | The count of the number of outgoing transactions, starting with 0 228 | gasPrice | 3600000000 | The price to determine the amount of ether the transaction will cost 229 | gasLimit | 21000 | The maximum gas that is allowed to be spent to process the transaction 230 | to | <address> | The account the transaction is sent to, if empty, the transaction will create a contract 231 | value | 100000000 | The amount of ether to send 232 | data | | Could be an arbitrary message or function call to a contract or code to create a contract 233 | 234 | 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*). 235 | 236 | Code example to fill in the signer input parameters: 237 | 238 | ```swift 239 | let input = EthereumSigningInput.with { 240 | $0.chainID = Data(hexString: "01")! 241 | $0.gasPrice = Data(hexString: "d693a400")! // decimal 3600000000 242 | $0.gasLimit = Data(hexString: "5208")! // decimal 21000 243 | $0.toAddress = "0xC37054b3b48C3317082E7ba872d7753D13da4986" 244 | $0.amount = Data(hexString: "0348bca5a16000")! 245 | $0.privateKey = wallet.getKeyForCoin(coin: .ethereum).data 246 | } 247 | ``` 248 | 249 | Then Signer is invoked, and the signed and encoded output retrieved: 250 | 251 | ```swift 252 | let output: EthereumSigningOutput = AnySigner.sign(input: input, coin: .ethereum) 253 | print(" data: ", output.encoded.hexString) 254 | ``` 255 | 256 | For more details on Ethereum transactions, check the Ethereum documentation. A few resources are here: 257 | 258 | * https://medium.com/@codetractio/inside-an-ethereum-transaction-fa94ffca912f 259 | * https://kauri.io/article/7e79b6932f8a41a4bcbbd194fd2fcc3a/v2/ethereum-101-part-4-accounts-transactions-and-messages 260 | * https://github.com/ethereumbook/ethereumbook/blob/develop/06transactions.asciidoc 261 | 262 | ### Binance Chain (BNB) Transaction Signing 263 | 264 | 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. 265 | 266 | To sign a order, you need to use `BinanceSigningInput`: 267 | 268 | Field | Sample value | Description 269 | ---|---|--- 270 | chainID | Binance-Chain-Nile | Network id, use Binance-Chain-Tigris for mainnet (see [node-info](https://dex.binance.org/api/v1/node-info) api) 271 | accountNumber | 51 | On chain account number. (see [account](https://dex.binance.org/api/v1/account/bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m) api) 272 | sequence | 437412 | Order sequence starting from 0, always plus 1 for new order from [account](https://dex.binance.org/api/v1/account/bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m) api 273 | source | 0 | [BEP10](https://github.com/binance-chain/BEPs/blob/master/BEP10.md) source id 274 | sendOrder | <sendOrder> | SendOrder contains `inputs` and `outputs`, see below sample code for more details 275 | 276 | A Swift sample code send order is shown below: 277 | 278 | ```swift 279 | let privateKey = PrivateKey(data: Data(hexString: "95949f757db1f57ca94a5dff23314accbe7abee89597bf6a3c7382c84d7eb832")!)! 280 | let publicKey = privateKey.getPublicKeySecp256k1(compressed: true) 281 | 282 | let token = BinanceSendOrder.Token.with { 283 | $0.denom = "BNB" // BNB or BEP2 token symbol 284 | $0.amount = 1 // Amount, 1 BNB 285 | } 286 | 287 | // A.k.a from / sender 288 | let orderInput = BinanceSendOrder.Input.with { 289 | $0.address = CosmosAddress(hrp: .binance, publicKey: publicKey)!.keyHash 290 | $0.coins = [token] 291 | } 292 | 293 | // A.k.a to / recipient 294 | let orderOutput = BinanceSendOrder.Output.with { 295 | $0.address = CosmosAddress(string: "bnb1hlly02l6ahjsgxw9wlcswnlwdhg4xhx38yxpd5")!.keyHash 296 | $0.coins = [token] 297 | } 298 | 299 | let input = BinanceSigningInput.with { 300 | $0.chainID = "Binance-Chain-Nile" // Testnet Chain id 301 | $0.accountNumber = 0 // On chain account number 302 | $0.sequence = 0 // Sequence number 303 | $0.source = 0 // BEP10 source id 304 | $0.privateKey = privateKey.data 305 | $0.memo = "" 306 | $0.sendOrder = BinanceSendOrder.with { 307 | $0.inputs = [orderInput] 308 | $0.outputs = [orderOutput] 309 | } 310 | } 311 | 312 | let output: BinanceSigningOutput = AnySigner.sign(input: input, coin: .binance) 313 | // encoded order to broadcast 314 | print(output.encoded) 315 | ``` 316 | 317 | For more details please check the Binance Chain documentation: 318 | 319 | * https://docs.binance.org/encoding.html 320 | * https://docs.binance.org/api-reference/dex-api/paths.html#http-api 321 | 322 | Consult the complete sample applications for more details. 323 | -------------------------------------------------------------------------------- /wallet-core/wallet-core.md: -------------------------------------------------------------------------------- 1 | # Wallet Core 2 | 3 | ![](/media/wallet-core-banner.png) 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 | 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 | 33 | ## Contributing 34 | 35 | The best way to submit feedback and report bugs is to [open a GitHub issue](https://github.com/trustwallet/wallet-core/issues/new). 36 | If you want to contribute code please see [Contributing](contributing.md). 37 | If you want to add support for a new blockchain also see [Adding Support for a New Blockchain](newblockchain.md). 38 | 39 | Thanks to all the people who contribute. 40 | 41 | 42 | ## License 43 | 44 | 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. 45 | -------------------------------------------------------------------------------- /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 | ## Examples 77 | 78 | Here are various sample usages. 79 | 80 | Create a new private key, derive a BTC address from it, write it to a file: 81 | 82 | ```shell 83 | > coin bitcoin 84 | Set active coin to: bitcoin Use 'coin' to change. (name: 'bitcoin' symbol: btc numericalid: 0) 85 | > newKey 86 | Result: 4e8c1773ce1ca447594fa23a445d9952236c7a15e96802b880aab4d918bdcfd9 87 | > addrPri # 88 | Result: bc1qvjf93nc80f3fu7j2ehqv6xw6zqa5cny32hl90y 89 | > fileW btcaddr.txt # 90 | Written to file 'btcaddr.txt', 21 bytes. 91 | ``` 92 | 93 | Create a new private key, derive the public key from it, derive a BTC address from it: 94 | 95 | ```shell 96 | > newKey 97 | Result: ef8f76035c4d4dd29ed4bbe3fc7c0db45d81cd616f2ac8b038cb982bec2a63ad 98 | > pubPri # 99 | Result: 0381277ec943a6cd4033171da547bbe93585a8905fb3dad108e8e51e88a4e136ea 100 | > addrPub # 101 | Result: bc1qvf6gzfhcelpugw84ks677x5zuke46jm946dtpx 102 | ``` 103 | 104 | Check an ALGO address for validity: 105 | 106 | ```shell 107 | > coin algo 108 | Set active coin to: algorand Use 'coin' to change. (name: 'algorand' symbol: algo numericalid: 283) 109 | > addr LCSUSBOLNVT6BND6DWWGM4DLVUYJN3PGBT4T7LTCMDMKS7TR7FZAOHOVPE 110 | Address is a valid algorand address: LCSUSBOLNVT6BND6DWWGM4DLVUYJN3PGBT4T7LTCMDMKS7TR7FZAOHOVPE 111 | ``` 112 | 113 | Derive private keys using different BIP39 derivation paths, and create address from it: 114 | 115 | ```shell 116 | > coin btc 117 | Set active coin to: bitcoin Use 'coin' to change. (name: 'bitcoin' symbol: btc numericalid: 0) 118 | > dumpDP 119 | Result: m/84'/0'/0'/0/0 120 | > priDP 121 | Using derivation path "m/84'/0'/0'/0/0" for coin bitcoin 122 | Result: df6a78d65fe3c82f020c25be12debd46e58f5f4366381102485ce26c52416a96 123 | > priDP m/84'/0'/0'/0/1 124 | Using derivation path "m/84'/0'/0'/0/1" for coin bitcoin 125 | Result: 19c44359b4953bb3084dd73ba2854f6822de3b6f8f358055a16a1b19e533e37c 126 | > pubPri # 127 | Result: 02222d3889870d36e0c9e788c69a6509eddfb2105309e7733cfa669bb52ba996d1 128 | > addrPub # 129 | Result: bc1q7ghe6xyx38vdkzs9ryv3gz47mgvpa747z2mcvy 130 | > addr # 131 | Address is a valid bitcoin address: bc1q7ghe6xyx38vdkzs9ryv3gz47mgvpa747z2mcvy 132 | ``` 133 | 134 | Derive several NANO addresses (BIP39): 135 | 136 | ```shell 137 | > coin nano 138 | Set active coin to: nano Use 'coin' to change. (name: 'nano' symbol: nano numericalid: 165) 139 | > dumpDP 140 | Result: m/44'/165'/0' 141 | > 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 142 | Mnemonic set (24 words). 143 | > addrDefault 144 | Result: nano_3yyipbgtnd7183k61nkh5mxnt9wpsfhto95mksdqj6s7p45mwj9osai7asad 145 | > addrDP m/44'/165'/0' 146 | Result: nano_3yyipbgtnd7183k61nkh5mxnt9wpsfhto95mksdqj6s7p45mwj9osai7asad 147 | > addrDP m/44'/165'/1' 148 | Result: nano_3zni7o8m4dq1aphffnaq5pwseh7rrzhkrz5mpr8bcm68n6u775pbk7csedam 149 | ``` 150 | 151 | Hex and Base64 encoding example: 152 | 153 | ```shell 154 | > hex Hello 155 | Result: 48656c6c6f 156 | > base64Encode # 157 | Result: SGVsbG8= 158 | > base64Decode # 159 | Result: 48656c6c6f 160 | > buffer 161 | Last value: 48656c6c6f 162 | 3 previous values: 163 | #1 48656c6c6f 164 | #2 SGVsbG8= 165 | #3 48656c6c6f 166 | ``` 167 | --------------------------------------------------------------------------------