CAIP10.sol 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.24;
  3. import {Bytes} from "./Bytes.sol";
  4. import {Strings} from "./Strings.sol";
  5. import {CAIP2} from "./CAIP2.sol";
  6. /**
  7. * @dev Helper library to format and parse CAIP-10 identifiers
  8. *
  9. * https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md[CAIP-10] defines account identifiers as:
  10. * account_id: chain_id + ":" + account_address
  11. * chain_id: [-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32} (See {CAIP2})
  12. * account_address: [-.%a-zA-Z0-9]{1,128}
  13. *
  14. * WARNING: According to [CAIP-10's canonicalization section](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md#canonicalization),
  15. * the implementation remains at the developer's discretion. Please note that case variations may introduce ambiguity.
  16. * For example, when building hashes to identify accounts or data associated to them, multiple representations of the
  17. * same account would derive to different hashes. For EVM chains, we recommend using checksummed addresses for the
  18. * "account_address" part. They can be generated onchain using {Strings-toChecksumHexString}.
  19. */
  20. library CAIP10 {
  21. using Strings for address;
  22. using Bytes for bytes;
  23. /// @dev Return the CAIP-10 identifier for an account on the current (local) chain.
  24. function local(address account) internal view returns (string memory) {
  25. return format(CAIP2.local(), account.toChecksumHexString());
  26. }
  27. /**
  28. * @dev Return the CAIP-10 identifier for a given caip2 chain and account.
  29. *
  30. * NOTE: This function does not verify that the inputs are properly formatted.
  31. */
  32. function format(string memory caip2, string memory account) internal pure returns (string memory) {
  33. return string.concat(caip2, ":", account);
  34. }
  35. /**
  36. * @dev Parse a CAIP-10 identifier into its components.
  37. *
  38. * NOTE: This function does not verify that the CAIP-10 input is properly formatted. The `caip2` return can be
  39. * parsed using the {CAIP2} library.
  40. */
  41. function parse(string memory caip10) internal pure returns (string memory caip2, string memory account) {
  42. bytes memory buffer = bytes(caip10);
  43. uint256 pos = buffer.lastIndexOf(":");
  44. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  45. }
  46. }