Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: BitteProtocol/near-ca
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v0.7.1
Choose a base ref
...
head repository: BitteProtocol/near-ca
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: main
Choose a head ref
  • 15 commits
  • 20 files changed
  • 2 contributors

Commits on Nov 13, 2024

  1. Copy the full SHA
    6e8f6c0 View commit details

Commits on Nov 15, 2024

  1. Copy the full SHA
    23b3ce3 View commit details

Commits on Nov 18, 2024

  1. Upgrade (#149)

    bh2smith authored Nov 18, 2024
    Copy the full SHA
    5b8a89d View commit details

Commits on Jan 7, 2025

  1. Yarn Upgrade (#152)

    Updating Dependencies
    bh2smith authored Jan 7, 2025
    Copy the full SHA
    a23442a View commit details

Commits on Jan 9, 2025

  1. Manually Sign, Broadcast and Poll Signature Requests (#153)

    The MPC Sign Requests are timing out when calling
    `account.signAndSendTransaction`. This appears to be buried deeply in
    the non-configurable `provider.txStatus` polling (when waiting for an
    EXECUTED status).
    
    Add alternate/semi-manual transaction broadcast & result fetching as
    follows:
    
     - signTransaction
     - sendTransactionAsync
    - poll txStatus for INCLUDED instead of EXECUTED on a loop until
    EXECUTED (with 1 second/block sleep).
    
    
    This is entirely due to some usability issue with near-js/providers:
    near/near-api-js#1448
    bh2smith authored Jan 9, 2025
    Copy the full SHA
    007e55c View commit details

Commits on Jan 14, 2025

  1. Add Avalanche Native Asset (#154)

    Had to also fix an e2e test.
    bh2smith authored Jan 14, 2025
    Copy the full SHA
    f62ba6b View commit details
  2. Update Dependencies (#155)

    bh2smith authored Jan 14, 2025
    Copy the full SHA
    4172f9e View commit details

Commits on Jan 15, 2025

  1. RPC Overrides for Unreliable Defaults (#156)

    Introducing a few internal rpc overrides (Avalanche and Sepolia) whose
    viem defaults are not good enough for our purposes.
    
    **Bonus:** We also add the optional user overrides for `rpcUrl` and
    `scanUrl` on calls to `Network.fromChainId()`!
    bh2smith authored Jan 15, 2025
    Copy the full SHA
    477a574 View commit details
  2. Readme: Remove Disclaimer (#157)

    This is now used in production system so... and this tweet.
    
    https://x.com/microchipgnu/status/1879171098258096344
    bh2smith authored Jan 15, 2025
    Copy the full SHA
    8d1f001 View commit details
  3. Improve TypedDataDomain guard (#158)

    Uniswap WC requests had chainId as a string in the domain structure.
    This PR improves the type guard to capture this.
    bh2smith authored Jan 15, 2025
    Copy the full SHA
    18a1c44 View commit details
  4. Copy the full SHA
    89a2206 View commit details

Commits on Jan 21, 2025

  1. Copy the full SHA
    5441a65 View commit details

Commits on Jan 22, 2025

  1. Fix wrapped POL

    bh2smith committed Jan 22, 2025
    Copy the full SHA
    2495430 View commit details

Commits on Jan 27, 2025

  1. Yarn Upgrade (#161)

    Updating Dependencies with yarn upgrade, but also marking them in package.json
    bh2smith authored Jan 27, 2025
    Copy the full SHA
    7b0c78b View commit details
  2. Update Readme & Adapt Utilities (#162)

    **Readme Updates**
    
    1. Remove redundant aspects.
    2. Make front end example more prominent.
    3. Expand frontend example.
    
    **Type Utilities**
    1. `convertToAction`: Transforming WalletSelector Action to NearApiJS
    Action
    2. Expose NearAccount from Adapter.
    
    TODO: Add tests for conversion utility.
    bh2smith authored Jan 27, 2025
    Copy the full SHA
    f33616d View commit details
Showing with 1,021 additions and 1,136 deletions.
  1. +49 −58 README.md
  2. +25 −0 examples/README.md
  3. +13 −13 package.json
  4. +9 −1 src/chains/ethereum.ts
  5. +0 −5 src/chains/near.ts
  6. +3 −1 src/index.ts
  7. +57 −30 src/mpcContract.ts
  8. +8 −1 src/network/constants.ts
  9. +20 −4 src/network/index.ts
  10. +10 −2 src/types/guards.ts
  11. +2 −296 src/types/index.ts
  12. +295 −0 src/types/interfaces.ts
  13. +40 −0 src/types/util.ts
  14. +2 −2 src/utils/kdf.ts
  15. +36 −3 tests/e2e.test.ts
  16. +1 −0 tests/unit/network.test.ts
  17. +68 −0 tests/unit/types.guards.test.ts
  18. +41 −0 tests/unit/types.util.test.ts
  19. +13 −3 tsconfig.json
  20. +329 −717 yarn.lock
107 changes: 49 additions & 58 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# NEAR Chain Abstraction Layer (NEAR-CA)

**DISCLAIMER: This should only be used for educational purposes.**

NEAR-CA is a TypeScript library designed to provide an abstraction layer for interacting with the NEAR blockchain, simplifying the process of performing transactions and managing accounts on both NEAR and Ethereum chains. This library is intended for use in server-side applications only.

## Features
@@ -12,61 +10,21 @@ NEAR-CA is a TypeScript library designed to provide an abstraction layer for int
- Support for EIP-1559 transactions on Ethereum.
- Wallet Connect intergration tools.

## Contracts

### Get Started

This project requires Node.js version 20.0.0 or higher.
If you are using nvm, you can run `nvm use` to use the node version specified in `.nvmrc`.

To install dependencies and set up the project:

```sh
# Install dependencies
yarn
# Credentials
cp .env.example .env <---- paste your Near credentials
# Send Eth. You'll need to fund your account first.
# More details in the 'Fund your account' part of this document
npx tsx examples/send-eth.ts
```

### NEAR Credentials

Before using NEAR-CA, ensure you have the following environment variables set in your `.env` file:

- `NEAR_ACCOUNT_ID`: Your NEAR account identifier.
- `NEAR_ACCOUNT_PRIVATE_KEY`: Your NEAR account private key.
- `MPC_CONTRACT_ID`: The NEAR contract that handles multichain operations.
- `NETWORK`: Either `near` or `testnet`.

Copy the `.env.example` file and add these values to the `.env` file.

For setting up a wallet, use the NEAR testnet wallet.
The testnet wallet is different from the main wallet.
For example, you can use the [Mintbase Wallet](https://testnet.wallet.mintbase.xyz/).

## Fund your account

Get your address

```sh
npx tsx examples/getEthAddress.ts
```

After getting your address fund it from one of your own wallets.

# Examples
### Usage

## CLI

For Ethereum, you can derive addresses, create payloads for transactions, and send signed transactions.

For more detailed examples, see the [Examples README](./examples/README.md).
For more detailed usage examples, see the [Examples README](./examples/README.md).

## Integrations

## Frontend
[near-safe](https://github.com/BitteProtocol/near-safe) extends this tool kit by using the EOA as an owner of an ERC-4337 [Safe](https://safe.global/) account.

To install NEAR-CA in your project, run the following command:
## Frontend/UI

Install near-ca, run the following command:

```bash
yarn add near-ca
@@ -78,26 +36,59 @@ Here's an example of how to set up the `NearEthAdapter` and send ETH:

```typescript
import dotenv from "dotenv";
import { setupAdapter } from "near-ca";
import {
broadcastSignedTransaction,
convertToAction,
isRlpHex,
setupAdapter,
signatureFromOutcome,
} from "near-ca";

dotenv.config();
const { NEAR_ACCOUNT_ID, NEAR_ACCOUNT_PRIVATE_KEY } = process.env;

const adapter = await setupAdapter({
accountId: NEAR_ACCOUNT_ID!,
privateKey: NEAR_ACCOUNT_PRIVATE_KEY!,
mpcContractId: MPC_CONTRACT_ID!,
// privateKey: NEAR_ACCOUNT_PRIVATE_KEY!, // Optional depending on setup
});

await adapter.signAndSendTransaction({
receiver: "0xdeADBeeF0000000000000000000000000b00B1e5",
amount: 1n,
chainId: 11_155_111,
// Optional: Set nearGas (default is 250 TGAS, which sometimes might not be sufficient)
const {
evmMessage,
nearPayload: { receiverId, actions },
} = await evm.encodeSignRequest({
method: "eth_sendTransaction",
chainId: 11_155_111, // Sepolia
params: [
{
from: evm.address,
to: "0xdeADBeeF0000000000000000000000000b00B1e5",
value: "0x01", // 1 WEI
// data: "0x", // Optional
},
],
});
console.log(`Requesting Signature for ${evmMessage}`);
// Using your near Account, send the nearPaylod as signature request:
const nearAccount = adapter.nearAccount();
//
const outtcome = await nearAccount.signAndSendTransaction({
receiverId,
actions: actions.map((a) => convertToAction(a)),
});
const signature = signatureFromOutcome(outtcome);
console.log("Signature aquired!");
if (isRlpHex(evmMessage)) {
// This will be true for what we built above.
broadcastSignedTransaction({ transaction: evmMessage, signature });
} else {
// Use Signature for whatever else.
}
```

### Other Examples
### Other Examples (CLI)

These examples require Private Key to be supplied:

Each of the following scripts can be run with

25 changes: 25 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -6,6 +6,31 @@ You can run any of the following example scripts using the command:
npx tsx examples/*.ts
```

### NEAR Credentials

Before using NEAR-CA, ensure you have the following environment variables set in your `.env` file:

- `NEAR_ACCOUNT_ID`: Your NEAR account identifier.
- `MPC_CONTRACT_ID`: The NEAR contract that handles multichain operations.
- `NETWORK`: Either `near` or `testnet`.
- `NEAR_ACCOUNT_PRIVATE_KEY`: Your NEAR account private key.

Copy the `.env.example` file and add these values to the `.env` file.

For setting up a wallet, use the NEAR testnet wallet.
The testnet wallet is different from the main wallet.
For example, you can use the [Bitte Wallet](https://testnet.wallet.bitte.ai/).

## Fund your account

Get your address

```sh
npx tsx examples/getEthAddress.ts
```

After getting your address fund it from one of your own wallets.

Here are some of the available examples:

1. **Basic:**
26 changes: 13 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@
"chain-signatures"
],
"main": "dist/cjs/index.js",
"module": "dist/mjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"files": [
"dist/**/*"
@@ -27,34 +27,34 @@
"build:esm": "tsc -p tsconfig.esm.json",
"build:cjs": "tsc -p tsconfig.cjs.json",
"lint": "eslint . --ignore-pattern dist/ && prettier --check **/*.ts",
"test": "jest --testTimeout 30000",
"test": "jest --passWithNoTests",
"coverage": "yarn test --coverage",
"verify": "yarn coverage unit",
"fmt": "prettier --write '{src,examples,tests}/**/*.{js,jsx,ts,tsx}' && eslint src/ --fix"
},
"engines": {
"node": ">=20.0.0"
},
"dependencies": {
"@walletconnect/web3wallet": "^1.13.0",
"elliptic": "^6.5.6",
"near-api-js": "^5.0.1",
"viem": "^2.22.15"
},
"devDependencies": {
"@types/elliptic": "^6.4.18",
"@types/jest": "^29.5.12",
"@types/node": "^22.1.0",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"@types/node": "^22.10.10",
"@typescript-eslint/eslint-plugin": "^8.21.0",
"@typescript-eslint/parser": "^8.21.0",
"dotenv": "^16.4.5",
"eslint": "^9.7.0",
"eslint": "^9.19.0",
"ethers": "^6.13.3",
"jest": "^v30.0.0-alpha.6",
"opensea-js": "^7.1.12",
"prettier": "^3.3.3",
"ts-jest": "^29.2.3",
"tsx": "^4.16.2",
"typescript": "^5.5.3"
},
"dependencies": {
"@walletconnect/web3wallet": "^1.13.0",
"elliptic": "^6.5.6",
"near-api-js": "^5.0.0",
"viem": "^2.21.37"
"typescript": "^5.7.3"
}
}
10 changes: 9 additions & 1 deletion src/chains/ethereum.ts
Original file line number Diff line number Diff line change
@@ -27,6 +27,7 @@ import {
} from "..";
import { Beta } from "../beta";
import { requestRouter } from "../utils/request";
import { Account } from "near-api-js";

export class NearEthAdapter {
readonly mpcContract: IMpcContract;
@@ -46,7 +47,14 @@ export class NearEthAdapter {
}

/**
* @returns Near accountId linked to derived ETH.
* @returns Near Account linked to derived EVM account.
*/
nearAccount(): Account {
return this.mpcContract.connectedAccount;
}

/**
* @returns Near accountId linked to derived EVM account.
*/
nearAccountId(): string {
return this.mpcContract.connectedAccount.accountId;
5 changes: 0 additions & 5 deletions src/chains/near.ts
Original file line number Diff line number Diff line change
@@ -16,11 +16,6 @@ type NetworkId = "mainnet" | "testnet";
*/
export function getNetworkId(accountId: string): NetworkId {
const accountExt = accountId.split(".").pop() || "";
if (!["near", "testnet"].includes(accountExt)) {
console.warn(
`Unusual or invalid network extracted from accountId ${accountId}`
);
}
// Consider anything that isn't testnet as mainnet.
return accountExt !== "testnet" ? "mainnet" : accountExt;
}
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -27,13 +27,15 @@ type KeyPairString = `ed25519:${string}` | `secp256k1:${string}`;
* @property {NearConfig} [network] - (Optional) The NEAR network configuration.
* @property {string} [privateKey] - (Optional) The private key for the account.
* @property {string} [derivationPath] - (Optional) The derivation path for the Ethereum account. Defaults to "ethereum,1".
* @property {string} [rootPublicKey] - (Optional) The root public key for the account. If not available it will be fetched from the MPC contract.
*/
export interface SetupConfig {
accountId: string;
mpcContractId: string;
network?: NearConfig;
privateKey?: string;
derivationPath?: string;
rootPublicKey?: string;
}

/**
@@ -79,7 +81,7 @@ export async function setupAdapter(args: SetupConfig): Promise<NearEthAdapter> {
throw error;
}
return NearEthAdapter.fromConfig({
mpcContract: new MpcContract(account, mpcContractId),
mpcContract: new MpcContract(account, mpcContractId, args.rootPublicKey),
derivationPath: derivationPath,
});
}
Loading