Skip to content

Commit 913651d

Browse files
committed
feat: ref swap, wallet connection, ref env variables
1 parent 35f7ca6 commit 913651d

File tree

6 files changed

+87
-25
lines changed

6 files changed

+87
-25
lines changed

agent/src/index.ts

+1-8
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import {
2323
validateCharacterConfig,
2424
} from "@ai16z/eliza";
2525
import { zgPlugin } from "@ai16z/plugin-0g";
26-
import { goatPlugin } from "@ai16z/plugin-goat";
2726
import { bootstrapPlugin } from "@ai16z/plugin-bootstrap";
2827
// import { buttplugPlugin } from "@ai16z/plugin-buttplug";
2928
import {
@@ -373,11 +372,7 @@ export function createAgent(
373372
!getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("0x"))
374373
? solanaPlugin
375374
: null,
376-
getSecret(character, "NEAR_PUBLIC_KEY") ||
377-
(getSecret(character, "WALLET_PUBLIC_KEY") &&
378-
!getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("ed25519"))
379-
? nearPlugin
380-
: null,
375+
nearPlugin,
381376
getSecret(character, "EVM_PUBLIC_KEY") ||
382377
(getSecret(character, "WALLET_PUBLIC_KEY") &&
383378
!getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("0x"))
@@ -397,7 +392,6 @@ export function createAgent(
397392
? [coinbaseMassPaymentsPlugin, tradePlugin]
398393
: []),
399394
getSecret(character, "WALLET_SECRET_SALT") ? teePlugin : null,
400-
getSecret(character, "ALCHEMY_API_KEY") ? goatPlugin : null,
401395
].filter(Boolean),
402396
providers: [],
403397
actions: [],
@@ -439,7 +433,6 @@ async function startAgent(character: Character, directClient) {
439433

440434
const cache = intializeDbCache(character, db);
441435
const runtime = createAgent(character, db, cache, token);
442-
443436
await runtime.initialize();
444437

445438
const clients = await initializeClients(character, runtime);

packages/plugin-near/src/actions/swap.ts

+8-9
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
} from "@ai16z/eliza";
1212
import { connect, keyStores, utils } from "near-api-js";
1313
import BigNumber from "bignumber.js";
14-
import { init_env, ftGetTokenMetadata, estimateSwap, instantSwap } from '@ref-finance/ref-sdk';
14+
import { init_env, ftGetTokenMetadata, estimateSwap, instantSwap, fetchAllPools, FT_MINIMUM_STORAGE_BALANCE_LARGE } from '@ref-finance/ref-sdk';
1515
import { walletProvider } from "../providers/wallet";
1616
import { KeyPairString } from "near-api-js/lib/utils";
1717

@@ -23,25 +23,24 @@ async function swapToken(
2323
inputTokenId: string,
2424
outputTokenId: string,
2525
amount: string,
26-
slippageTolerance: number = 0.01
26+
slippageTolerance: number = 0.1
2727
): Promise<any> {
2828
try {
2929
// Get token metadata
3030
const tokenIn = await ftGetTokenMetadata(inputTokenId);
3131
const tokenOut = await ftGetTokenMetadata(outputTokenId);
3232

3333
// Get all pools for estimation
34-
const response = await fetch('https://testnet-indexer.ref-finance.com/list-pools');
35-
const { simplePools } = await response.json();
34+
const { ratedPools, unRatedPools, simplePools} = await fetchAllPools(200);
3635

37-
// Estimate swap
36+
console.log("Pools:", simplePools);
3837
const swapTodos = await estimateSwap({
3938
tokenIn,
4039
tokenOut,
4140
amountIn: amount,
4241
simplePools,
4342
options: {
44-
enableSmartRouting: true
43+
enableSmartRouting: true,
4544
}
4645
});
4746

@@ -176,7 +175,7 @@ export const executeSwap: Action = {
176175
response.inputTokenId,
177176
response.outputTokenId,
178177
response.amount,
179-
0.01 // 1% slippage tolerance
178+
0.1 // 1% slippage tolerance
180179
);
181180

182181
// Sign and send transactions
@@ -190,7 +189,7 @@ export const executeSwap: Action = {
190189
methodName: functionCall.methodName,
191190
args: functionCall.args,
192191
gas: functionCall.gas,
193-
attachedDeposit: functionCall.amount ? BigInt(functionCall.amount) : BigInt(0),
192+
attachedDeposit: BigInt(1),
194193
});
195194
results.push(result);
196195
}
@@ -208,7 +207,7 @@ export const executeSwap: Action = {
208207
} catch (error) {
209208
console.error("Error during token swap:", error);
210209
const responseMsg = {
211-
text: `Error during swap: ${error.message}`,
210+
text: `Error during swap: ${error instanceof Error ? error.message : String(error)}`,
212211
};
213212
callback?.(responseMsg);
214213
return false;

packages/plugin-near/src/environment.ts

+60
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,79 @@
11
import { IAgentRuntime } from "@ai16z/eliza";
22
import { z } from "zod";
33

4+
// Add ENV variable at the top
5+
let ENV: string = "testnet";
6+
47
export const nearEnvSchema = z.object({
58
NEAR_WALLET_SECRET_KEY: z.string().min(1, "Wallet secret key is required"),
69
NEAR_WALLET_PUBLIC_KEY: z.string().min(1, "Wallet public key is required"),
710
NEAR_ADDRESS: z.string().min(1, "Near address is required"),
811
SLIPPAGE: z.string().min(1, "Slippage is required"),
912
RPC_URL: z.string().min(1, "RPC URL is required"),
13+
networkId: z.string(),
14+
nodeUrl: z.string(),
15+
walletUrl: z.string(),
16+
WRAP_NEAR_CONTRACT_ID: z.string(),
17+
REF_FI_CONTRACT_ID: z.string(),
18+
REF_TOKEN_ID: z.string(),
19+
indexerUrl: z.string(),
20+
explorerUrl: z.string(),
21+
REF_DCL_SWAP_CONTRACT_ID: z.string(),
1022
});
1123

1224
export type NearConfig = z.infer<typeof nearEnvSchema>;
1325

26+
export function getConfig(
27+
env: string | undefined | null = ENV ||
28+
process.env.NEAR_ENV ||
29+
process.env.REACT_APP_REF_SDK_ENV
30+
) {
31+
ENV = env || "testnet";
32+
switch (env) {
33+
case 'mainnet':
34+
return {
35+
networkId: 'mainnet',
36+
nodeUrl: 'https://rpc.mainnet.near.org',
37+
walletUrl: 'https://wallet.near.org',
38+
WRAP_NEAR_CONTRACT_ID: 'wrap.near',
39+
REF_FI_CONTRACT_ID: 'v2.ref-finance.near',
40+
REF_TOKEN_ID: 'token.v2.ref-finance.near',
41+
indexerUrl: 'https://indexer.ref.finance',
42+
explorerUrl: 'https://testnet.nearblocks.io',
43+
REF_DCL_SWAP_CONTRACT_ID: 'dclv2.ref-labs.near',
44+
};
45+
case 'testnet':
46+
return {
47+
networkId: 'testnet',
48+
nodeUrl: 'https://rpc.testnet.near.org',
49+
walletUrl: 'https://wallet.testnet.near.org',
50+
indexerUrl: 'https://testnet-indexer.ref-finance.com',
51+
WRAP_NEAR_CONTRACT_ID: 'wrap.testnet',
52+
REF_FI_CONTRACT_ID: 'ref-finance-101.testnet',
53+
REF_TOKEN_ID: 'ref.fakes.testnet',
54+
explorerUrl: 'https://testnet.nearblocks.io',
55+
REF_DCL_SWAP_CONTRACT_ID: 'dclv2.ref-dev.testnet',
56+
};
57+
default:
58+
return {
59+
networkId: 'mainnet',
60+
nodeUrl: 'https://rpc.mainnet.near.org',
61+
walletUrl: 'https://wallet.near.org',
62+
REF_FI_CONTRACT_ID: 'v2.ref-finance.near',
63+
WRAP_NEAR_CONTRACT_ID: 'wrap.near',
64+
REF_TOKEN_ID: 'token.v2.ref-finance.near',
65+
indexerUrl: 'https://indexer.ref.finance',
66+
explorerUrl: 'https://nearblocks.io',
67+
REF_DCL_SWAP_CONTRACT_ID: 'dclv2.ref-labs.near',
68+
};
69+
}
70+
}
71+
1472
export async function validateNearConfig(
1573
runtime: IAgentRuntime
1674
): Promise<NearConfig> {
1775
try {
76+
const envConfig = getConfig(runtime.getSetting("NEAR_ENV") ?? undefined);
1877
const config = {
1978
NEAR_WALLET_SECRET_KEY:
2079
runtime.getSetting("NEAR_WALLET_SECRET_KEY") ||
@@ -27,6 +86,7 @@ export async function validateNearConfig(
2786
runtime.getSetting("NEAR_ADDRESS") || process.env.NEAR_ADDRESS,
2887
SLIPPAGE: runtime.getSetting("SLIPPAGE") || process.env.SLIPPAGE,
2988
RPC_URL: runtime.getSetting("RPC_URL") || process.env.RPC_URL,
89+
...envConfig // Spread the environment-specific config
3090
};
3191

3292
return nearEnvSchema.parse(config);

packages/plugin-near/src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { walletProvider } from "./providers/wallet";
44
import { executeSwap } from "./actions/swap";
55

66
export const nearPlugin: Plugin = {
7-
name: "near",
7+
name: "NEAR",
88
description: "Near Protocol Plugin for Eliza",
99
providers: [walletProvider],
1010
actions: [executeSwap],

packages/plugin-near/src/providers/wallet.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import { IAgentRuntime, Memory, Provider, State } from "@ai16z/eliza";
22
import { KeyPair, keyStores, connect, Account, utils } from "near-api-js";
33
import BigNumber from "bignumber.js";
4-
import NodeCache from "node-cache";
5-
import fs from "fs";
6-
import os from "os";
74
import { KeyPairString } from "near-api-js/lib/utils";
5+
import NodeCache from "node-cache";
86

97
const PROVIDER_CONFIG = {
108
networkId: process.env.NEAR_NETWORK || "testnet",
@@ -40,6 +38,7 @@ export class WalletProvider implements Provider {
4038
private keyStore: keyStores.InMemoryKeyStore;
4139
constructor(private accountId: string) {
4240
this.cache = new NodeCache({ stdTTL: 300 }); // Cache TTL set to 5 minutes
41+
this.keyStore = new keyStores.InMemoryKeyStore();
4342
}
4443

4544
async get(

packages/plugin-near/tsconfig.json

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
{
2-
"extends": "../../tsconfig.json",
32
"compilerOptions": {
3+
"target": "ES2020",
4+
"module": "ESNext",
5+
"moduleResolution": "node",
46
"outDir": "dist",
57
"rootDir": "./src",
6-
"typeRoots": ["./node_modules/@types", "./src/types"],
8+
"strict": true,
9+
"esModuleInterop": true,
10+
"skipLibCheck": true,
11+
"forceConsistentCasingInFileNames": true,
12+
"typeRoots": [
13+
"./node_modules/@types",
14+
"./src/types"
15+
],
716
"declaration": true
817
},
9-
"include": ["src"]
10-
}
18+
"include": [
19+
"src"
20+
]
21+
}

0 commit comments

Comments
 (0)