first integration tests (#64)
resolves #60 Co-authored-by: johba <johba@harb.eth> Reviewed-on: https://codeberg.org/johba/harb/pulls/64
This commit is contained in:
parent
d6f0bf4f02
commit
1645865c5a
14 changed files with 913 additions and 2226 deletions
154
tests/e2e/01-acquire-and-stake.spec.ts
Normal file
154
tests/e2e/01-acquire-and-stake.spec.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { expect, test, type APIRequestContext } from '@playwright/test';
|
||||
import { Wallet } from 'ethers';
|
||||
import { createWalletContext } from '../setup/wallet-provider';
|
||||
import { startStack, waitForStackReady, stopStack } from '../setup/stack';
|
||||
|
||||
const ACCOUNT_PRIVATE_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
|
||||
const ACCOUNT_ADDRESS = new Wallet(ACCOUNT_PRIVATE_KEY).address.toLowerCase();
|
||||
const STACK_RPC_URL = process.env.STACK_RPC_URL ?? 'http://127.0.0.1:8545';
|
||||
const STACK_WEBAPP_URL = process.env.STACK_WEBAPP_URL ?? 'http://localhost:5173';
|
||||
const STACK_GRAPHQL_URL = process.env.STACK_GRAPHQL_URL ?? 'http://localhost:42069/graphql';
|
||||
|
||||
async function fetchPositions(request: APIRequestContext, owner: string) {
|
||||
const response = await request.post(STACK_GRAPHQL_URL, {
|
||||
data: {
|
||||
query: `
|
||||
query PositionsByOwner($owner: String!) {
|
||||
positionss(where: { owner: $owner }, limit: 5) {
|
||||
items {
|
||||
id
|
||||
owner
|
||||
taxRate
|
||||
stakeDeposit
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: { owner },
|
||||
},
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(response.ok()).toBeTruthy();
|
||||
const payload = await response.json();
|
||||
return (payload?.data?.positionss?.items ?? []) as Array<{
|
||||
id: string;
|
||||
owner: string;
|
||||
taxRate: number;
|
||||
stakeDeposit: string;
|
||||
status: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
test.describe('Acquire & Stake', () => {
|
||||
test.beforeAll(async () => {
|
||||
await startStack();
|
||||
await waitForStackReady({
|
||||
rpcUrl: STACK_RPC_URL,
|
||||
webAppUrl: STACK_WEBAPP_URL,
|
||||
graphqlUrl: STACK_GRAPHQL_URL,
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await stopStack();
|
||||
});
|
||||
|
||||
test('users can swap KRK via UI', async ({ browser, request }) => {
|
||||
console.log('[TEST] Creating wallet context...');
|
||||
const context = await createWalletContext(browser, {
|
||||
privateKey: ACCOUNT_PRIVATE_KEY,
|
||||
rpcUrl: STACK_RPC_URL,
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
// Log browser console messages
|
||||
page.on('console', msg => console.log(`[BROWSER] ${msg.type()}: ${msg.text()}`));
|
||||
page.on('pageerror', error => console.log(`[BROWSER ERROR] ${error.message}`));
|
||||
|
||||
try {
|
||||
console.log('[TEST] Loading app...');
|
||||
await page.goto(`${STACK_WEBAPP_URL}/app/`, { waitUntil: 'domcontentloaded' });
|
||||
console.log('[TEST] App loaded, waiting for wallet to initialize...');
|
||||
|
||||
// Wait for wallet to be fully recognized
|
||||
await page.waitForTimeout(3_000);
|
||||
|
||||
// Check if wallet shows as connected in UI
|
||||
console.log('[TEST] Checking for wallet display...');
|
||||
const walletDisplay = page.getByText(/0xf39F/i).first();
|
||||
await expect(walletDisplay).toBeVisible({ timeout: 15_000 });
|
||||
console.log('[TEST] Wallet connected successfully!');
|
||||
|
||||
console.log('[TEST] Navigating to cheats page...');
|
||||
await page.goto(`${STACK_WEBAPP_URL}/app/#/cheats`);
|
||||
await expect(page.getByRole('heading', { name: 'Cheat Console' })).toBeVisible();
|
||||
|
||||
console.log('[TEST] Minting test ETH...');
|
||||
await page.getByLabel('RPC URL').fill(STACK_RPC_URL);
|
||||
await page.getByLabel('Recipient').fill(ACCOUNT_ADDRESS);
|
||||
const mintButton = page.getByRole('button', { name: 'Mint' });
|
||||
await expect(mintButton).toBeEnabled();
|
||||
await mintButton.click();
|
||||
await page.waitForTimeout(3_000);
|
||||
|
||||
console.log('[TEST] Buying KRK tokens via swap...');
|
||||
await page.screenshot({ path: 'test-results/before-swap.png' });
|
||||
|
||||
// Check if swap is available
|
||||
const buyWarning = await page.getByText('Connect to the Base Sepolia fork').isVisible().catch(() => false);
|
||||
if (buyWarning) {
|
||||
throw new Error('Swap not available - chain config issue persists');
|
||||
}
|
||||
|
||||
const ethToSpendInput = page.getByLabel('ETH to spend');
|
||||
await ethToSpendInput.fill('0.05');
|
||||
|
||||
const buyButton = page.getByRole('button', { name: 'Buy' }).last();
|
||||
await expect(buyButton).toBeVisible();
|
||||
console.log('[TEST] Clicking Buy button...');
|
||||
await buyButton.click();
|
||||
|
||||
// Wait for button to show "Submitting..." then return to "Buy"
|
||||
console.log('[TEST] Waiting for swap to process...');
|
||||
try {
|
||||
await page.getByRole('button', { name: /Submitting/i }).waitFor({ state: 'visible', timeout: 5_000 });
|
||||
console.log('[TEST] Swap initiated, waiting for completion...');
|
||||
await page.getByRole('button', { name: 'Buy' }).last().waitFor({ state: 'visible', timeout: 60_000 });
|
||||
console.log('[TEST] Swap completed!');
|
||||
} catch (e) {
|
||||
console.log('[TEST] No "Submitting" state detected, swap may have completed instantly');
|
||||
}
|
||||
await page.waitForTimeout(2_000);
|
||||
|
||||
console.log('[TEST] Verifying swap via RPC...');
|
||||
// Query the blockchain directly to verify KRK balance increased
|
||||
const balanceResponse = await fetch(STACK_RPC_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'eth_call',
|
||||
params: [{
|
||||
to: '0xe527ddac2592faa45884a0b78e4d377a5d3df8cc', // KRK token
|
||||
data: `0x70a08231000000000000000000000000${ACCOUNT_ADDRESS.slice(2)}` // balanceOf(address)
|
||||
}, 'latest']
|
||||
})
|
||||
});
|
||||
|
||||
const balanceData = await balanceResponse.json();
|
||||
const balance = BigInt(balanceData.result || '0');
|
||||
console.log(`[TEST] KRK balance: ${balance.toString()} wei`);
|
||||
|
||||
expect(balance).toBeGreaterThan(0n);
|
||||
console.log('[TEST] ✅ Swap successful! KRK balance > 0');
|
||||
console.log('[TEST] ✅ E2E test complete: Swap verified through UI');
|
||||
console.log('[TEST] Note: Staking is verified separately via verify-swap.sh script');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
141
tests/setup/stack.ts
Normal file
141
tests/setup/stack.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { exec as execCallback } from 'node:child_process';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const exec = promisify(execCallback);
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const repoRoot = resolve(__dirname, '..', '..');
|
||||
|
||||
const DEFAULT_RPC_URL = process.env.STACK_RPC_URL ?? 'http://127.0.0.1:8545';
|
||||
const DEFAULT_WEBAPP_URL = process.env.STACK_WEBAPP_URL ?? 'http://localhost:5173';
|
||||
const DEFAULT_GRAPHQL_URL = process.env.STACK_GRAPHQL_URL ?? 'http://localhost:42069/graphql';
|
||||
|
||||
let stackStarted = false;
|
||||
|
||||
async function cleanupContainers(): Promise<void> {
|
||||
try {
|
||||
await run("podman pod ps -q --filter name=harb | xargs -r podman pod rm -f || true");
|
||||
await run("podman ps -aq --filter name=harb | xargs -r podman rm -f || true");
|
||||
} catch (error) {
|
||||
console.warn('[stack] Failed to cleanup containers', error);
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolveDelay => setTimeout(resolveDelay, ms));
|
||||
}
|
||||
|
||||
async function run(command: string): Promise<void> {
|
||||
await exec(command, { cwd: repoRoot, shell: true });
|
||||
}
|
||||
|
||||
async function checkRpcReady(rpcUrl: string): Promise<void> {
|
||||
const response = await fetch(rpcUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_chainId', params: [] }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`RPC health check failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
if (!payload?.result) {
|
||||
throw new Error('RPC health check returned no result');
|
||||
}
|
||||
}
|
||||
|
||||
async function checkWebAppReady(webAppUrl: string): Promise<void> {
|
||||
const url = webAppUrl.endsWith('/') ? `${webAppUrl}app/` : `${webAppUrl}/app/`;
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
redirect: 'manual',
|
||||
});
|
||||
|
||||
if (!response.ok && response.status !== 308) {
|
||||
throw new Error(`Web app health check failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function checkGraphqlReady(graphqlUrl: string): Promise<void> {
|
||||
const response = await fetch(graphqlUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ query: '{ __typename }' }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`GraphQL health check failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function startStack(): Promise<void> {
|
||||
if (stackStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
await cleanupContainers();
|
||||
|
||||
await run('nohup ./scripts/dev.sh start > ./tests/.stack.log 2>&1 &');
|
||||
stackStarted = true;
|
||||
}
|
||||
|
||||
export async function waitForStackReady(options: {
|
||||
rpcUrl?: string;
|
||||
webAppUrl?: string;
|
||||
graphqlUrl?: string;
|
||||
timeoutMs?: number;
|
||||
pollIntervalMs?: number;
|
||||
} = {}): Promise<void> {
|
||||
const rpcUrl = options.rpcUrl ?? DEFAULT_RPC_URL;
|
||||
const webAppUrl = options.webAppUrl ?? DEFAULT_WEBAPP_URL;
|
||||
const graphqlUrl = options.graphqlUrl ?? DEFAULT_GRAPHQL_URL;
|
||||
const timeoutMs = options.timeoutMs ?? 180_000;
|
||||
const pollIntervalMs = options.pollIntervalMs ?? 2_000;
|
||||
|
||||
const start = Date.now();
|
||||
const errors = new Map<string, string>();
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
await Promise.all([
|
||||
checkRpcReady(rpcUrl),
|
||||
checkWebAppReady(webAppUrl),
|
||||
checkGraphqlReady(graphqlUrl),
|
||||
]);
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
errors.set('lastError', message);
|
||||
await delay(pollIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
const logPath = resolve(repoRoot, 'tests', '.stack.log');
|
||||
let logTail = '';
|
||||
try {
|
||||
const contents = await readFile(logPath, 'utf-8');
|
||||
logTail = contents.split('\n').slice(-40).join('\n');
|
||||
} catch (readError) {
|
||||
logTail = `Unable to read stack log: ${readError}`;
|
||||
}
|
||||
|
||||
throw new Error(`Stack failed to become ready within ${timeoutMs}ms\nLast error: ${errors.get('lastError')}\nLog tail:\n${logTail}`);
|
||||
}
|
||||
|
||||
export async function stopStack(): Promise<void> {
|
||||
if (!stackStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await run('./scripts/dev.sh stop');
|
||||
} finally {
|
||||
stackStarted = false;
|
||||
}
|
||||
}
|
||||
207
tests/setup/wallet-provider.ts
Normal file
207
tests/setup/wallet-provider.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import type { Browser, BrowserContext } from '@playwright/test';
|
||||
import { Wallet } from 'ethers';
|
||||
|
||||
export interface WalletProviderOptions {
|
||||
privateKey: string;
|
||||
rpcUrl?: string;
|
||||
chainId?: number;
|
||||
chainName?: string;
|
||||
walletName?: string;
|
||||
walletUuid?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_CHAIN_ID = 31337;
|
||||
const DEFAULT_RPC_URL = 'http://127.0.0.1:8545';
|
||||
const DEFAULT_WALLET_NAME = 'Playwright Wallet';
|
||||
const DEFAULT_WALLET_UUID = '11111111-2222-3333-4444-555555555555';
|
||||
|
||||
export async function createWalletContext(
|
||||
browser: Browser,
|
||||
options: WalletProviderOptions,
|
||||
): Promise<BrowserContext> {
|
||||
const chainId = options.chainId ?? DEFAULT_CHAIN_ID;
|
||||
const rpcUrl = options.rpcUrl ?? DEFAULT_RPC_URL;
|
||||
const chainName = options.chainName ?? 'Kraiken Local Fork';
|
||||
const walletName = options.walletName ?? DEFAULT_WALLET_NAME;
|
||||
const walletUuid = options.walletUuid ?? DEFAULT_WALLET_UUID;
|
||||
|
||||
const wallet = new Wallet(options.privateKey);
|
||||
const address = wallet.address;
|
||||
const chainIdHex = `0x${chainId.toString(16)}`;
|
||||
|
||||
const context = await browser.newContext();
|
||||
|
||||
await context.addInitScript(() => {
|
||||
window.localStorage.setItem('authentificated', 'true');
|
||||
});
|
||||
|
||||
await context.addInitScript(
|
||||
({
|
||||
account,
|
||||
chainIdHex: cidHex,
|
||||
chainId: cid,
|
||||
rpcEndpoint,
|
||||
chainLabel,
|
||||
walletLabel,
|
||||
walletId,
|
||||
}) => {
|
||||
const listeners = new Map<string, Set<(...args: any[]) => void>>();
|
||||
let rpcRequestId = 0;
|
||||
let connected = false;
|
||||
|
||||
const emit = (event: string, payload: any): void => {
|
||||
const handlers = listeners.get(event);
|
||||
if (!handlers) {
|
||||
return;
|
||||
}
|
||||
for (const handler of Array.from(handlers)) {
|
||||
try {
|
||||
handler(payload);
|
||||
} catch (error) {
|
||||
console.error(`[wallet-provider] listener for ${event} failed`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const sendRpc = async (method: string, params: unknown[]): Promise<unknown> => {
|
||||
rpcRequestId += 1;
|
||||
const response = await fetch(rpcEndpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: rpcRequestId, method, params }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`RPC call to ${method} failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
if (payload?.error) {
|
||||
const message = payload.error?.message ?? 'RPC error';
|
||||
throw new Error(message);
|
||||
}
|
||||
return payload.result;
|
||||
};
|
||||
|
||||
const provider: any = {
|
||||
isMetaMask: true,
|
||||
isPlaywrightWallet: true,
|
||||
isConnected: () => connected,
|
||||
selectedAddress: account,
|
||||
chainId: cidHex,
|
||||
networkVersion: String(cid),
|
||||
request: async ({ method, params = [] }: { method: string; params?: unknown[] }) => {
|
||||
const args = Array.isArray(params) ? params.slice() : [];
|
||||
|
||||
switch (method) {
|
||||
case 'eth_requestAccounts':
|
||||
connected = true;
|
||||
provider.selectedAddress = account;
|
||||
provider.chainId = cidHex;
|
||||
provider.networkVersion = String(cid);
|
||||
emit('connect', { chainId: cidHex });
|
||||
emit('chainChanged', cidHex);
|
||||
emit('accountsChanged', [account]);
|
||||
return [account];
|
||||
case 'eth_accounts':
|
||||
return [account];
|
||||
case 'eth_chainId':
|
||||
return cidHex;
|
||||
case 'net_version':
|
||||
return String(cid);
|
||||
case 'wallet_switchEthereumChain': {
|
||||
const requested = (args[0] as { chainId?: string } | undefined)?.chainId;
|
||||
if (requested && requested.toLowerCase() !== cidHex.toLowerCase()) {
|
||||
throw new Error(`Unsupported chain ${requested}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 'wallet_addEthereumChain':
|
||||
return null;
|
||||
case 'eth_sendTransaction': {
|
||||
const [tx = {}] = args as Record<string, unknown>[];
|
||||
const enrichedTx = { ...tx, from: account };
|
||||
return sendRpc(method, [enrichedTx]);
|
||||
}
|
||||
case 'eth_sign':
|
||||
case 'personal_sign':
|
||||
case 'eth_signTypedData':
|
||||
case 'eth_signTypedData_v3':
|
||||
case 'eth_signTypedData_v4': {
|
||||
if (args.length > 0) {
|
||||
args[0] = account;
|
||||
}
|
||||
return sendRpc(method, args);
|
||||
}
|
||||
default:
|
||||
return sendRpc(method, args);
|
||||
}
|
||||
},
|
||||
on: (event: string, listener: (...args: any[]) => void) => {
|
||||
const handlers = listeners.get(event) ?? new Set();
|
||||
handlers.add(listener);
|
||||
listeners.set(event, handlers);
|
||||
if (event === 'connect' && connected) {
|
||||
listener({ chainId: cidHex });
|
||||
}
|
||||
return provider;
|
||||
},
|
||||
removeListener: (event: string, listener: (...args: any[]) => void) => {
|
||||
const handlers = listeners.get(event);
|
||||
if (handlers) {
|
||||
handlers.delete(listener);
|
||||
}
|
||||
return provider;
|
||||
},
|
||||
enable: () => provider.request({ method: 'eth_requestAccounts' }),
|
||||
requestPermissions: () =>
|
||||
Promise.resolve([{ parentCapability: 'eth_accounts' }]),
|
||||
getProviderState: async () => ({
|
||||
accounts: [account],
|
||||
chainId: cidHex,
|
||||
isConnected: connected,
|
||||
}),
|
||||
};
|
||||
|
||||
const announce = () => {
|
||||
const detail = Object.freeze({
|
||||
info: Object.freeze({
|
||||
uuid: walletId,
|
||||
name: walletLabel,
|
||||
icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><circle cx="32" cy="32" r="32" fill="%234f46e5"/><path d="M20 34l6 6 18-18" fill="none" stroke="white" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
||||
rdns: 'org.playwright.wallet',
|
||||
}),
|
||||
provider,
|
||||
});
|
||||
window.dispatchEvent(new CustomEvent('eip6963:announceProvider', { detail }));
|
||||
};
|
||||
|
||||
const requestListener = () => announce();
|
||||
window.addEventListener('eip6963:requestProvider', requestListener);
|
||||
|
||||
Object.defineProperty(window, 'ethereum', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
value: provider,
|
||||
writable: false,
|
||||
});
|
||||
|
||||
provider.providers = [provider];
|
||||
|
||||
announce();
|
||||
window.dispatchEvent(new Event('ethereum#initialized'));
|
||||
console.info('[wallet-provider] Injected test provider for', chainLabel);
|
||||
},
|
||||
{
|
||||
account: address,
|
||||
chainIdHex,
|
||||
chainId,
|
||||
rpcEndpoint: rpcUrl,
|
||||
chainLabel: chainName,
|
||||
walletLabel: walletName,
|
||||
walletId: walletUuid,
|
||||
},
|
||||
);
|
||||
|
||||
return context;
|
||||
}
|
||||
93
tests/verify-swap.sh
Executable file
93
tests/verify-swap.sh
Executable file
|
|
@ -0,0 +1,93 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
RPC_URL="http://127.0.0.1:8545"
|
||||
ACCOUNT="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
|
||||
PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
|
||||
WETH="0x4200000000000000000000000000000000000006"
|
||||
SWAP_ROUTER="0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"
|
||||
KRK="0xe527ddac2592faa45884a0b78e4d377a5d3df8cc" # From bootstrap logs
|
||||
|
||||
# Get Stake contract address dynamically from KRK token
|
||||
PERIPHERY=$(cast call --rpc-url "$RPC_URL" "$KRK" "peripheryContracts()(address,address)")
|
||||
STAKE=$(echo "$PERIPHERY" | tail -1)
|
||||
|
||||
echo "[1/7] Checking initial KRK balance..."
|
||||
INITIAL_BALANCE=$(cast call --rpc-url "$RPC_URL" "$KRK" "balanceOf(address)(uint256)" "$ACCOUNT" | awk '{print $1}')
|
||||
echo "Initial KRK balance: $INITIAL_BALANCE"
|
||||
|
||||
echo "[2/7] Wrapping 0.05 ETH to WETH..."
|
||||
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
|
||||
"$WETH" "deposit()" --value 0.05ether
|
||||
|
||||
echo "[3/7] Approving swap router..."
|
||||
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
|
||||
"$WETH" "approve(address,uint256)" "$SWAP_ROUTER" 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
|
||||
|
||||
echo "[4/7] Executing swap (0.05 ETH -> KRK)..."
|
||||
cast send --legacy --gas-limit 300000 --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
|
||||
"$SWAP_ROUTER" "exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))" \
|
||||
"($WETH,$KRK,10000,$ACCOUNT,50000000000000000,0,0)"
|
||||
|
||||
echo "[5/7] Checking final KRK balance..."
|
||||
FINAL_BALANCE=$(cast call --rpc-url "$RPC_URL" "$KRK" "balanceOf(address)(uint256)" "$ACCOUNT" | awk '{print $1}')
|
||||
echo "Final KRK balance: $FINAL_BALANCE"
|
||||
|
||||
# Convert to human readable (divide by 10^18)
|
||||
FINAL_KRK=$(python3 -c "print(f'{$FINAL_BALANCE / 1e18:.4f}')")
|
||||
echo "Final KRK balance: $FINAL_KRK KRK"
|
||||
|
||||
if [ "$FINAL_BALANCE" -le "$INITIAL_BALANCE" ]; then
|
||||
echo "❌ FAILED: No KRK tokens received"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RECEIVED=$(python3 -c "print(f'{($FINAL_BALANCE - $INITIAL_BALANCE) / 1e18:.4f}')")
|
||||
echo "✅ SUCCESS! Received $RECEIVED KRK tokens from swap"
|
||||
|
||||
# Calculate 1/5 of received tokens for staking
|
||||
STAKE_AMOUNT=$(python3 -c "print(int(($FINAL_BALANCE - $INITIAL_BALANCE) / 5))")
|
||||
echo ""
|
||||
echo "[6/7] Staking 1/5 of received KRK ($STAKE_AMOUNT wei)..."
|
||||
|
||||
# Approve Stake contract to spend KRK
|
||||
echo " → Approving Stake contract..."
|
||||
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
|
||||
"$KRK" "approve(address,uint256)" "$STAKE" "$STAKE_AMOUNT"
|
||||
|
||||
# Stake with tax rate index 5 (18% annual tax), no positions to snatch
|
||||
echo " → Creating staking position (18% tax rate)..."
|
||||
TX_OUTPUT=$(cast send --legacy --gas-limit 500000 --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
|
||||
"$STAKE" "snatch(uint256,address,uint32,uint256[])" \
|
||||
"$STAKE_AMOUNT" "$ACCOUNT" "5" "[]")
|
||||
|
||||
TX_HASH=$(echo "$TX_OUTPUT" | grep "^transactionHash" | awk '{print $2}')
|
||||
echo " → Staking transaction: $TX_HASH"
|
||||
|
||||
echo "[7/7] Verifying staking position created..."
|
||||
# Get the PositionCreated event topic from the transaction receipt
|
||||
# The position ID is the first indexed parameter (topic[1])
|
||||
RECEIPT_JSON=$(cast receipt --rpc-url "$RPC_URL" "$TX_HASH" --json)
|
||||
POSITION_ID_HEX=$(echo "$RECEIPT_JSON" | python3 -c "import sys, json; logs = json.load(sys.stdin)['logs']; print([l for l in logs if len(l['topics']) > 1 and '8f7598451bc034be2bd3fe6e2f06af052c2dc238bb90bc6fb426754f04301462' in l['topics'][0]][0]['topics'][1] if any('8f7598451bc034be2bd3fe6e2f06af052c2dc238bb90bc6fb426754f04301462' in l['topics'][0] for l in logs) else '')" 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$POSITION_ID_HEX" ]; then
|
||||
POSITION_ID=$(python3 -c "print(int('$POSITION_ID_HEX', 16))")
|
||||
STAKE_KRK=$(python3 -c "print(f'{$STAKE_AMOUNT / 1e18:.4f}')")
|
||||
echo "✅ SUCCESS! Staking position created with ID: $POSITION_ID"
|
||||
echo ""
|
||||
echo "Summary:"
|
||||
echo " - Swapped: 0.05 ETH → $RECEIVED KRK"
|
||||
echo " - Staked: $STAKE_KRK KRK (1/5 of received)"
|
||||
echo " - Position ID: $POSITION_ID"
|
||||
echo " - Tax Rate: 18% annual"
|
||||
exit 0
|
||||
else
|
||||
echo "⚠️ WARNING: Could not extract position ID from receipt"
|
||||
echo "But staking transaction succeeded: $TX_HASH"
|
||||
echo ""
|
||||
echo "Summary:"
|
||||
echo " - Swapped: 0.05 ETH → $RECEIVED KRK"
|
||||
echo " - Staked: 1/5 of received KRK"
|
||||
echo " - Transaction: $TX_HASH"
|
||||
exit 0
|
||||
fi
|
||||
Loading…
Add table
Add a link
Reference in a new issue