Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/lib/stores/contractStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { persisted } from 'svelte-local-storage-store'
import { v4 as uuidv4 } from 'uuid'
import { Contract, StrKey } from '@stellar/stellar-sdk'
import { error } from '@sveltejs/kit'
import { get } from 'svelte/store'

/**
* @typedef {Object} SavedContract
* @property {string} id Unique identifier for this contract
* @property {string} contractId The Stellar contract ID
* @property {string} name Human-readable name for this contract
* @property {string} [description] Optional description of the contract
*/

function createContractStore() {
/** @type {import('svelte/store').Writable<{savedContracts: SavedContract[], currentContract: SavedContract|null}>} */
const { subscribe, set, update } = persisted('bpa:contractStore', {
savedContracts: [],
currentContract: null
})

return {
subscribe,

/**
* Saves a new contract to the store
* @param {SavedContract} contract Contract details to save
* @throws Will throw an error if the contract ID is invalid
*/
saveContract: (contract) =>
update(store => {
if (!StrKey.isValidContract(contract.contractId)) {
throw error(400, { message: 'Invalid contract ID' })
}

const newContract = {
...contract,
id: contract.id || uuidv4()
}

return {
...store,
savedContracts: [...store.savedContracts, newContract]
}
}),

/**
* Removes a contract from the store
* @param {string} id Unique identifier of the contract to remove
*/
removeContract: (id) =>
update(store => ({
...store,
savedContracts: store.savedContracts.filter(c => c.id !== id),
currentContract: store.currentContract?.id === id ? null : store.currentContract
})),

/**
* Sets the current active contract
* @param {SavedContract|null} contract Contract to set as current, or null to clear
*/
setCurrentContract: (contract) =>
update(store => ({
...store,
currentContract: contract
})),

/**
* Looks up a contract by its Stellar contract ID
* @param {string} contractId Stellar contract ID to look up
* @returns {SavedContract|undefined} The found contract or undefined
*/
lookup: (contractId) => {
const store = get(contractStore)
return store.savedContracts.find(contract => contract.contractId === contractId)
},

/**
* Clears all saved contracts from the store
*/
empty: () => set({ savedContracts: [], currentContract: null })
}
}

export const contractStore = createContractStore()
44 changes: 44 additions & 0 deletions src/lib/utils/contractUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { StrKey, Contract } from '@stellar/stellar-sdk'
import { Server } from '@stellar/stellar-sdk/rpc'

/**
* Generates a contract client for interacting with a Stellar smart contract
* @param {string} contractId - The contract ID to validate and connect to
* @returns {Promise<Contract>} A Contract instance
*/
export async function generateContractClient(contractId) {
const server = new Server('https://soroban-testnet.stellar.org')

// Validate contract ID
if (!StrKey.isValidContract(contractId)) {
throw new Error('Invalid contract ID format')
}

try {
console.log('Fetching WASM for contract ID:', contractId)

// Fetch the contract's WASM using the contract ID
const contractResponse = await server.getContractWasmByContractId(contractId)

// Log the WASM bytecode length or the data for debugging
console.log('Contract WASM length:', contractResponse.length) // Adjust if needed based on actual response structure

// Create a contract instance (you may need to initialize this differently based on your library's requirements)
const contract = new Contract(contractId)

// You might want to add the contract's interface here
// This could involve parsing the WASM to get available methods

return contract // Return the contract instance
} catch (serverError) {
console.error('Error fetching contract WASM:', serverError)

// Handle specific server error responses
if (serverError.response && serverError.response.status === 404) {
throw new Error(`Contract not found: ${contractId}`)
}

// Throw a general error for other server issues
throw new Error(`Failed to fetch contract WASM: ${serverError.message}`)
}
}
1 change: 1 addition & 0 deletions src/routes/dashboard/components/SidebarMenu.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ list of menu links that can be used to navigate throughout the dashboard.
{ route: '/dashboard/assets', text: 'Assets' },
{ route: '/dashboard/contacts', text: 'Contacts' },
{ route: '/dashboard/transfers', text: 'Transfers' },
{ route: '/dashboard/contracts', text: 'Smart Contracts' }
]
</script>

Expand Down
91 changes: 91 additions & 0 deletions src/routes/dashboard/contracts/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<script lang="ts">
import { contractStore } from '$lib/stores/contractStore'
import { generateContractClient } from '$lib/utils/contractUtils'
import { SorobanRpc } from '@stellar/stellar-sdk'

let contractId = ''
let contractName = ''
let error = ''
let loading = false

const server = new SorobanRpc.Server('https://soroban-testnet.stellar.org')

async function handleLoadContract() {
loading = true
error = ''

try {
const contract = await generateContractClient(contractId, server)
$contractStore.setCurrentContract(contract)

// Optionally save the contract
if (contractName) {
$contractStore.saveContract({
id: contractId,
name: contractName,
network: 'TESTNET', // or 'PUBLIC' for mainnet
})
}
} catch (err) {
error = err.message
} finally {
loading = false
}
}
</script>

<div class="container mx-auto p-4">
<h1 class="mb-4 text-2xl font-bold">Stellar Smart Contract Interaction</h1>

<div class="mb-4">
<label class="mb-1 block text-sm font-medium" for="contractId"> Contract ID </label>
<input
id="contractId"
type="text"
bind:value={contractId}
placeholder="Enter contract ID (C...)"
class="w-full rounded border p-2"
/>
</div>

<div class="mb-4">
<label class="mb-1 block text-sm font-medium" for="contractName">
Contract Name (optional)
</label>
<input
id="contractName"
type="text"
bind:value={contractName}
placeholder="Enter a name for this contract"
class="w-full rounded border p-2"
/>
</div>

<button
on:click={handleLoadContract}
disabled={loading}
class="rounded bg-blue-500 px-4 py-2 text-white"
>
{loading ? 'Loading...' : 'Load Contract'}
</button>

{#if error}
<div class="mt-2 text-red-500">{error}</div>
{/if}

<h2 class="mb-4 mt-8 text-xl font-bold">Saved Contracts</h2>
{#each $contractStore.savedContracts as contract}
<div class="mb-2 flex items-center justify-between rounded border p-4">
<div>
<span class="font-medium">{contract.name || 'Unnamed Contract'}</span>
<span class="block text-sm text-gray-500">{contract.id}</span>
</div>
<button
on:click={() => (contractId = contract.id)}
class="rounded bg-gray-200 px-3 py-1"
>
Load
</button>
</div>
{/each}
</div>