bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 14쪽 중 6쪽
know what we want to store, we will create a schema on Sign Protocol. We can accomplish this in two ways: first, we can use the [Schema Builder](https://app.sign.global/create-schema). This is perfect for non-coders or setting up a schema quickly, rather than performing the action through code. Second, we can create it by directly interfacing with Sign Protocol's Smart Contract or using the NPM SDK.
The first step is to name your schema, add a description, and choose where to store attestation data. In this tutorial, we will store data on-chain using the Base Sepolia Testnet. Once you choose your configuration, continue to the next step.
{% hint style="warning" %}
NOTE: If you select a data storage option that is not directly on-chain (such as Arweave/IPFS), your schema will require [Hybrid Attestations](https://github.com/EthSign/sign-protocol-docs/blob/main/for-builders/getting-started/advanced-topics/hybrid-attestations.md). Our SDK will handle this for you, but if you are interacting directly with Sign Protocol smart contracts, ensure that you are passing in an encoded Content ID (CID) as `data` when creating a hybrid attestation.
{% endhint %}
### Schema Builder
<figure><img src="https://3152654701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fw182g9YzR34mTxEBTKXX%2Fuploads%2FoikGmNqxFUPWFDDpIGut%2Fimage.png?alt=media&token=0a7feb51-bc64-4afd-bd90-1ef8a58f9141" alt=""><figcaption><p>Schema Builder Metadata</p></figcaption></figure>
The next step is to create the schema's data structure. As stated earlier, we will create two fields: `contractDetails` and `signer`. The Schema Builder allows you to enter fields in a user-friendly UI or manually edit the JSON data structure (click "Input Raw Data"). Once you have entered your schema data structure fields, continue to the next step.
<figure><img src="https://3152654701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fw182g9YzR34mTxEBTKXX%2Fuploads%2Fkzyl2HukKVRkCwv1xgxj%2Fimage.png?alt=media&token=3bb87425-d4f0-4ebb-bdf3-90446b916178" alt=""><figcaption><p>Schema Builder Data Structure</p></figcaption></figure>
When creating a schema, you can designate an additional smart contract address that will be called whenever an event occurs (attestation created, revoked, etc). This can be useful for taking payments or reverting transactions (when some verification fails, i.e. whitelist), but it is outside the scope of this tutorial, so we will leave the field blank for now. We will leave the attestation as non-revocable: Alice cannot make mistakes. Once you have completed this step, press "Create Schema".
<figure><img src="https://3152654701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fw182g9YzR34mTxEBTKXX%2Fuploads%2FCrBnUoOVi7t5fLrOF5Yn%2Fimage.png?alt=media&token=218a79fe-7fc8-499e-8ee7-7c08db5730af" alt=""><figcaption><p>Schema Builder Final Details</p></figcaption></figure>
Success! You have successfully created your schema. Click "View Schema" to go to your schema's page.
<figure><img src="https://3152654701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fw182g9YzR34mTxEBTKXX%2Fuploads%2FcxrZc045SiEKZZqfFSyn%2Fimage.png?alt=media&token=70189187-f89a-43ec-a449-1f84698a6300" alt=""><figcaption><p>Schema Created</p></figcaption></figure>
### NPM SDK
Install the [SDK](#npm-sdk) into your project. Create a SignProtocolClient to make calls that write to the blockchain. The private key field is optional if you are operating from the frontend as the SDK will attempt to use `window.ethereum` if no private key is provided for signing transactions. If you use the SDK from a Node backend, you must provide a private key to make write calls to the blockchain.
{% hint style="warning" %}
NOTE: The `account` variable is marked as optional. If it is not provided, the SDK will use the provider from `window.ethereum` by default to derive an account. If a provider from `window.ethereum` cannot be located when an account is not provided, calls to the SDK will fail.
{% endhint %}
{% hint style="warning" %}
NOTE: You must provide an API key when initializing your SignClient to create offchain attestations. This key is optional for onchain attestations. You can generate a key [here](https://developer.sign.global/). For more information, see [Installation](/for-builders/index-1/npm-sdk/installation).
{% endhint %}
```typescript
const { SignProtocolClient, SpMode, EvmChains } = require("@ethsign/sp-sdk");
const { privateKeyToAccount } = require("viem/accounts");
const privateKey = "0x...";
const client = new SignProtocolClient(SpMode.OnChain, {
chain: EvmChains.baseSepolia,
account: privateKeyToAccount(privateKey), // Optional, depending on environment
apiKey: 'xxx', // Optional for onchain, required for offchain
});
```
Next, you will need to create the schema we described above.
```typescript
const res = await client.createSchema({
name: "SDK Test",
data: [
{ name: "contractDetails", type: "string" },
{ name: "signer", type: "address" },
],
});
```
This will return information from the transaction, including the schema ID and transaction hash. For example, `res` may look like the following:
```json
{
"schemaId": "0x34",
"txHash": "0x..."
}
```
Now that you have created your schema, continue to the next page to create an attestation using this schema.
# Attestation Creation
Great! We now have a schema ready for use. We will refer to this schema throughout the remainder of the project by its ID, so save the ID of the schema you created. If you bypassed the previous step, you can use [this schema](https://testnet-scan.sign.global/schema/onchain_evm_84532_0x34) to continue through this tutorial (Schema ID: `onchain_evm_84532_0x34`). Note that the on-chain ID of the schema is `0x34` and we will use this when creating an attestation.
## Creating an Attestation
You can create an attestation using either our NPM SDK or by directly interacting with the respective Smart Contract for the specific network you are using. 
### Smart Contract Interaction
{% hint style="warning" %}
NOTE: If you selected a data storage option that is not directly on-chain (such as Arweave/IPFS), your schema will require [Hybrid Attestations](/for-builders/advanced-topics/hybrid-attestations). Our SDK will handle this for you, but if you are interacting directly with Sign Protocol smart contracts, ensure that you are passing in an encoded Content ID (CID) as `data` when creating a hybrid attestation.
{% endhint %}
Let's write a function that takes in a contract's message string and the address of the person who signed it. You can get the Contract Address in the [Address Book](/for-builders/address-book) and the latest ABI on Etherscan.
```typescript
import { Web3Provider } from "@ethersproject/providers";
import { BigNumber, Contract, ethers } from "ethers";
function createNotaryAttestation(contractDetails: string, signer: string) {
let address = "0x..."; // Alice's address. Will need Alice's account to send the tx.
let schemaData = ethers.utils.defaultAbiCoder.encode(
["string", "address"],
[contractDetails, signer]
);
// Standard setup for the contract
const provider = new ethers.providers.JsonRpcProvider(
// Get an RPC URL (such as an infura link) to connect to the network
getProviderUrl(84532)
);
// Get the contract address from the Address Book in docs.sign.global
const contract = new Contract(CONTRACT_ADDRESS(84532), ISPABI.abi, provider);
// Get the provider from the currently connected wallet
const library = new Web3Provider(await connector.getProvider());
// Create writable contract instance
const instance = contract.connect(library.getSigner() as any) as Contract;
// Send the attestation transaction
try {
await instance[
"attest((uint64,uint64,uint64,uint64,address,uint64,uint8,bool,bytes[],bytes),string,bytes,bytes)"
](
{
schemaId: BigNumber.from("0x34"), // The final number from our schema's ID.
linkedAttestationId: 0, // We are not linking an attestation.
attestTimestamp: 0, // Will be generated for us.
revokeTimestamp: 0, // Attestation is not revoked.
attester: address, // Alice's address.
validUntil: 0, // We are not setting an expiry date.
dataLocation: 0, // We are placing data on-chain.
revoked: false, // The attestation is not revoked.
recipients: [signer], // Bob is our recipient.
data: schemaData // The encoded schema data.
},
signer.toLowerCase(), // Bob's lowercase address will be our indexing key.
"0x", // No delegate signature.
"0x00" // No extra data.
)
.then(
async (tx: any) =>
await tx.wait(1).then((res) => {
console.log("success", res);
// You can find the attestation's ID using the following path:
// res.events[0].args.attestationId
})
)
.catch((err: any) => {
console.log(err?.message ? err.message : err);
});
} catch (err: any) {
console.log(err?.message ? err.message : err);
}
}
```
### NPM SDK
The SDK simplifies the process rather than directly interacting with the smart contract. To perform the same action as above, we will do the following:
```typescript
function createNotaryAttestation(contractDetails: string, signer: string) {
const res = await client.createAttestation({
schemaId: "0x34",
data: {
contractDetails,
signer
},
indexingValue: signer.toLowerCase()
});
}
```
Note that we can pass in all the attestation information like we did when sending the transaction directly to the smart contract, but we do not need to. The SDK will fill in the blank fields with their respective defaults. `createAttestation` will return data in the following format:
```json
{
attestationId: '0x..',
txHash: '0x..',
indexingValue: '...'
}
```
Now that you have successfully created an attestation, you need to be able to use it! When you're ready, move on to the next page.
# Querying Attestations
So now, how can you verify if Alice attested to Bob's signature? We will be using Sign Protocol's Indexing Service to do exactly that!
## Querying for an Attestation
You can query for an attestation using our NPM SDK or by making requests to our REST API.
### NPM SDK
Our [NPM SDK](#npm-sdk) includes an `IndexService` that you can use to query schemas and attestations.
```typescript
import { IndexService } from "@ethsign/sp-sdk";
async function queryAttestations() {
const indexService = new IndexService("testnet");
const attId = `onchain_evm_${chainId}_${attestationId}`;
const res = await indexService.queryAttestationList({
schemaId: "onchain_evm_84532_0x34", // Your full schema's ID
attester: "0x...", // Alice's address
page: 1,
mode: "onchain", // Data storage location
indexingValue: "0x...".toLowerCase(), // Bob's address
});
return {
success: true,
attestations: response.rows,
};
}
```
### REST API
Alternatively, we will create a helper function that we can reuse to make requests to the Sign Protocol Indexing Service.
```typescript
import axios from "axios";
// Generate a function for making requests to the Sign Protocol Indexing Service
async function makeAttestationRequest(endpoint: string, options: any) {
const url = `https://testnet-rpc.sign.global/api/${endpoint}`;
const res = await axios.request({
url,
headers: {
"Content-Type": "application/json; charset=UTF-8",
},
...options,
});
// Throw API errors
if (res.status !== 200) {
throw new Error(JSON.stringify(res));
}
// Return original response
return res.data;
}
```
Next, we will use this function to query for Alice's attestation of Bob's signature.
```typescript
async function queryAttestations() {
const response = await makeAttestationRequest("index/attestations", {
method: "GET",
params: {
mode: "onchain", // Data storage location
schemaId: "onchain_evm_84532_0x34", // Your full schema's ID
attester: "0x...", // Alice's address
indexingValue: "0x...".toLowerCase(), // Bob's address
},
});
// Make sure the request was successfully processed.
if (!response.success) {
return {
success: false,
message: response?.message ?? "Attestation query failed.",
};
}
// Return a message if no attestations are found.
if (response.data?.total === 0) {
return {
success: false,
message: "No attestation for this address found.",
};
}
// Return all attestations that match our query.
return {
success: true,
attestations: response.data.rows,
};
}
```
Great! So now, we have a list of available attestations that Alice has made, of Bob's signature. If we only need to check for the existence of at least one attestation that matches our criteria, we could stop here. But what if we wanted to validate the message that Alice was attesting? Perhaps there are several different contracts that Alice has notarized for Bob and we are looking for a specific one. When you are ready, move on to the next page where we will parse the attestation data.
# Parsing Attestation Data
Attestation data is encoded into a single hex string and can be decoded if you know the schema used to encode the data. With attestations on Sign Protocol, the attestation object returned also includes the schema's structure, which is exactly what we need.
{% hint style="warning" %}
NOTE: If you selected a data storage option that is not directly on-chain (such as Arweave/IPFS), your schema will utilize [Hybrid Attestations](/for-builders/advanced-topics/hybrid-attestations). Our SDK will handle this for you but note that you will receive an encoded Content ID (CID) as `data` when retrieving a hybrid attestation.
{% endhint %}
We will write a function that takes in a message and the list of attestations returned from our query. This function will find the specific attestation we are looking for and return it with the parsed data object.
{% hint style="info" %}
You can use our NPM SDK's `decodeOnChainData` function to decode your attestation data rather than directly interfacing with viem's `decodeAbiParameters` as shown in this tutorial. For more information and an example, see [here](/for-builders/index/index/indexing-service).
{% endhint %}
```typescript
import { decodeAbiParameters } from "viem";
function findAttestation(message: string, attestations: any[]) {
// Iterate through the list of attestations
for (const att of attestations) {
if (!att.data) continue;
let parsedData: any = {};
// Parse the data.
if (att.mode === "onchain") {
// Looking for nested items in the on-chain schema
try {
const data = decodeAbiParameters(
[att.dataLocation === "onchain" ? { components: att.schema.data, type: "tuple" } : { type: "string" }],
att.data
);
parsedData = data[0];
} catch (error) {
// Looking for a regular schema format if the nested parse fails
try {
const data = decodeAbiParameters(
att.dataLocation === "onchain" ? att.schema.data : [{ type: "string" }],
att.data
);
const obj: any = {};
data.forEach((item: any, i: number) => {
obj[att.schema.data[i].name] = item;
});
parsedData = obj;
} catch (error) {
continue;
}
}
} else {
// Try parsing as a string (off-chain attestation)
try {
parsedData = JSON.parse(att.data);
} catch (error) {
console.log(error);
continue;
}
}
// Return the correct attestation and its parsed data.
if(parsedData?.contractDetails === message) {
return { parsedData, attestation: att };
}
}
// Did not find the attestation we are looking for.
return undefined;
}
```
Now, we can parse the attestations returned from our query to Sign Protocol's Indexing Service, perform additional checks, and utilize the data they contain. In our example, we can perform some action using Alice's attestation of Bob's signature, or display an error if no such valid attestation is found.
If you know the attestation or schema you are looking for, you can also directly request its data from the Sign Protocol Indexing Service. In our case, we were looking for an attestation that met certain criteria. To expand upon our example, if our application was responsible for creating Alice's attestation, it might make sense to store the returned ID in a database for quicker load times (querying will always take longer than direct access with an ID, even if marginally so).
## Finished Tutorial
You can find the finished tutorial implementation [here](https://github.com/EthSign/sign-protocol-sdk-tutorial).
# Delegate Attestation Creation
Through this tutorial, we will utilize direct interaction with the Sign Protocol [Smart Contract](/for-builders/index-1/index/index/index/isp) and the [NPM SDK](/for-builders/index-1/npm-sdk).
### Problem Statement: Delegate Attestation Creation
There are two main reasons for delegate attestation creation: when initiated offchain, delegate attestations allow your backend to pay the gas fees for your users; when initiated onchain, delegate attestations allow your smart contract to create attestations on behalf of wallets interacting with it. This tutorial assumes you have a schema created and know how to create an attestation. Any schema will work; if you need help getting started, refer to [Building a Simple Notary Platform](/for-builders/getting-started/tutorials/building-a-simple-notary-platform).
This tutorial will be split into two parts - a JS backend and a Solidity contract. Both parts will require shared code to be placed into your frontend for requesting a delegate signature from users.
### Finished Code
The finished code from this tutorial can be found in our examples repository [here](https://github.com/EthSign/sign-protocol-examples).
# Express Backend
We will start from a simple Express backend. You can use any backend infrastructure or library of your choosing but note that current library support is limited to JavaScript/TypeScript. Install `express`, `@ethsign/sp-sdk`, and `viem`.
```typescript
import express from "express";
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
```
This boilerplate code is the simplest backend you can create. It creates a new server and listens for requests on port 3000.
## Initializing the Sign Protocol Client
Since we are running this code from a backend server, Sign Protocol's SDK requires you to pass in a private key account when creating your `SignProtocolClient`. Typically, when no account is provided, the client will use `window.ethereum`, which does not exist in a backend environment. Your code should look something like the following, assuming you are building on Sepolia:
```typescript
import {
SignProtocolClient,
SpMode,
EvmChains
} from "@ethsign/sp-sdk";
import { privateKeyToAccount } from "viem/accounts";
const privateKey = "0x..."; // account responsible for paying gas fees
const client = new SignProtocolClient(SpMode.OnChain, {
chain: EvmChains.sepolia,
account: privateKeyToAccount(privateKey) // required in backend environments
});
```
## Setting Up Your Controller
Your controller will be responsible for creating the attestation. Since this is a delegate attestation, it must provide the attestation object and the delegation signature. The backend is not responsible for generating the delegation signature because the user's wallet must sign a message to retrieve the signature. Your controller should look something like the following:
```typescript
app.post(
"/delegate",
async (req: Request<{}, {}, { attestation: Attestation; delegationSignature: string }>, res: Response) => {
try {
const { attestation, delegationSignature } = req.body;
const response = await client.createAttestation(attestation, {
delegationSignature
});
res.status(200).json({ message: response });
} catch (error: any) {
res.status(500).json({
error: {
message: error.message
}
});
}
}
);
```
## (Frontend) Generating a Delegation Signature
This section must be implemented on your frontend. Delegation signatures are a mechanism to allow a third party to upload an attest프로젝트로 돌아가기