CAIP10.sol 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.24;
  3. import {SafeCast} from "./math/SafeCast.sol";
  4. import {Bytes} from "./Bytes.sol";
  5. import {CAIP2} from "./CAIP2.sol";
  6. import {Strings} from "./Strings.sol";
  7. /**
  8. * @dev Helper library to format and parse CAIP-10 identifiers
  9. *
  10. * https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md[CAIP-10] defines account identifiers as:
  11. * account_id: chain_id + ":" + account_address
  12. * chain_id: [-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32} (See {CAIP2})
  13. * account_address: [-.%a-zA-Z0-9]{1,128}
  14. */
  15. library CAIP10 {
  16. using SafeCast for uint256;
  17. using Strings for address;
  18. using Bytes for bytes;
  19. /// @dev Return the CAIP-10 identifier for an account on the current (local) chain.
  20. function local(address account) internal view returns (string memory) {
  21. return format(CAIP2.local(), account.toChecksumHexString());
  22. }
  23. /**
  24. * @dev Return the CAIP-10 identifier for a given caip2 chain and account.
  25. *
  26. * NOTE: This function does not verify that the inputs are properly formatted.
  27. */
  28. function format(string memory caip2, string memory account) internal pure returns (string memory) {
  29. return string.concat(caip2, ":", account);
  30. }
  31. /**
  32. * @dev Parse a CAIP-10 identifier into its components.
  33. *
  34. * NOTE: This function does not verify that the CAIP-10 input is properly formatted. The `caip2` return can be
  35. * parsed using the {CAIP2} library.
  36. */
  37. function parse(string memory caip10) internal pure returns (string memory caip2, string memory account) {
  38. bytes memory buffer = bytes(caip10);
  39. uint256 pos = buffer.lastIndexOf(":");
  40. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  41. }
  42. }