What is the best practice to get history random number in Chainlink VRF? - chainlink

In the project, I rely on Chainlink VRF to get a random word to decide a raffle winner, but I failed to keep the minimum LINK balance in my VRF subscription so all requests are pending. (I thought transactions are not sent successfully so I called the function several times by mistake).
After I transfer some Link tokens to my VRF subscription, all the random numbers are sent to my contract. In the scenario, I only need the first one of these random words for the raffle, but I am not sure if the random word stored in the smart contract now is the first one.
If transactions based on random words did not succeed for some reason, where to find random words in history so that these transactions can be re-sent?
So my question is:
What is the best practice to get history random words generated by Chainlink VRF?
Thanks in advance.

After doing some research, I will answer the question.
The best practice is to keep random words in an array in your smart contract or you can add an event in fulfillment function in your consumer smart contract to record requestId and corresponding random words.
But if there is no event or other variables to record the random words in your smart contract, you can do the following:
Get requestId and randomness from event RandomWordsFulfilled in smart contract VRFCoordinatorV2, it can be found in the transaction sent by VRF node.
emit RandomWordsFulfilled(requestId, randomness, payment, success);
Get numWords from event RandomWordsRequested in VRFCoordinatorV2 smart contract.
emit RandomWordsRequested(
keyHash,
requestId,
preSeed,
subId,
requestConfirmations,
callbackGasLimit,
numWords,
msg.sender
);
Random words are generated by randomness and numWords in the following logic that is defined in function fulfillRandomWords in smart contract VRFCoordinatorV2. You can use the same logic to get the history random words.
for (uint256 i = 0; i < numWords; i++) {
randomWords[i] = uint256(keccak256(abi.encode(randomness, i)));
}

Related

Can I trigger an event for only one address in Ethereum network?

I am working on Ethereum smart contract to build a marketplace between sellers and buyers. When someone (y) ask a product from (x), can I trigger an event to let ONLY (x) he has a new request for his product ??
I have done the full code of the smart contract and I have done the event listening as well using web3.py. But what I want is not triggering the event for everyone on the network, only the seller should have a notice, so every seller has his own requests list.
I have no idea if this is possible or not, if yes, could someone please help me what I should update in the event listing code I have
def handle_event(event):
if (event.args['_new_req'] == True ):
print(' New request for the product ')
else:
print (' The request has been failed ')
def log_loop(event_filter, poll_interval):
while True:
for event in event_filter.get_new_entries():
handle_event(event)
time.sleep(poll_interval)
def _new_req_listen():
block_filter = contract.events._new_req.createFilter(fromBlock = 'latest')
worker1 = Thread(target=log_loop, args=(block_filter, 2))
worker1.start()
Could I filter the same event to be triggered in different cases or for different persons in the network ??
Thanks in advance
I'd recommend you think of this from the high level (algorithm) point of view, without dropping down to the code immediately.
For your requirement of having an event raised for a particular person (seller), the way to do this would be either:
One event list. The event data structure contains a "destination" address property. You can set "destination" to a unique value (e.g. 0x000000) than means "everyone", or you can set "destination" to one person (e.g. the address of the seller).
Or, have an unique event list for every seller. Your event processing will need to have an outer loop to iterate over all the event lists. You can also have a 'global' event list which means every seller is sent the event.

do all NEAR blockchain transactions require a receiver account?

reading through some documentation here and saw that part of the definition of a transaction is that all actions are performed "on top of the receiver's account" and also that the receiver account is "the account towards which the transaction will be routed."
also in the nearlib SDK, the transactions interface includes a method called signTransaction that requires receiverId as a parameter
async function signTransaction(receiverId: string, nonce: number, actions: Action[], blockHash: Uint8Array, signer: Signer, accountId?: string, networkId?: string): Promise<[Uint8Array, SignedTransaction]> {
but looking over the list of transactions supported by nearcore I wonder why do some of these transaction require a receiver.
why would any transactions require a "receiver" except for maybe Transfer, AddKey, DeleteKey, and DeleteAccount?
amd I think of the idea of "receiver" too literally, as in "they receive the outcome or impact of the transaction"? and instead it's not the right way to think about it?
or is receiverId optional in some cases but the interface just requires a value to avoid validation cruft?
here's what I believe to be the full list of supported transactions
pub enum Action {
CreateAccount(CreateAccountAction),
DeployContract(DeployContractAction),
FunctionCall(FunctionCallAction),
Transfer(TransferAction),
Stake(StakeAction),
AddKey(AddKeyAction),
DeleteKey(DeleteKeyAction),
DeleteAccount(DeleteAccountAction),
}
Conceptually every transaction always has a sender and a receiver, even though sometimes they might be the same. Because we always convert a transaction to a receipt that is sent to the receiver, it doesn't matter conceptually whether they are the same, even though in implementation there might be a difference.
Unfortunately, we don't have a good name to denote what we call "receiver". In some places in our code, we also call it "actor", because it actually refers to an account on which the action is performed opposed to an account which issued the action to perform (a.k.a "sender").
DeployContract, Stake, AddKey, DeleteKey require receiver==sender, in other words only an account itself can add/delete keys, stake and deploy a contract on itself, no other account can do it for it.
DeleteAccount is the same, it requires receiver==sender with one exception: If account is about to run out of balance due to storage rent and is below certain system-defined treshold any other account can delete it and claim the remaining balance.
CreateAccount, FunctionCall, and Transfer do not require receiver==sender. In case of the CreateAccount receiver should not exist at the moment of execution and will actually be created.
See the code that implements this logic: https://github.com/nearprotocol/nearcore/blob/ed43018851f8ec44f0a26b49fc9a863b71a1428f/runtime/runtime/src/actions.rs#L360

Plivo Bulk SMS destination limits?

I'm testing Plivo for sending bulk SMS. I'm using the .NET REST API to send the messages.
Plivo's documentation for bulk SMS indicates that you can just concatenate numbers with a delimiter. This works fine. Does anyone know how many numbers can be included or can you tell me how many you have successfully sent in one API request?
var plivo = new RestAPI("xxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
var sendData = new Dictionary<string, string>
{
{ "src", "0000000000" },
{ "dst", "00000000000<00000000000<00000000000<00000000000<00000000000<HOW MANY MORE???" },
{ "text", "test sms from plivo" }
};
IRestResponse<MessageResponse> resp = plivo.send_message(sendData);
I couldn't find this information.
According to Plivo support:
"There is no limit to the number of destination numbers you can add in the "dst"parameter of the outbound message API.
However, the outgoing rate limit is 5 messages per second per account."
Regardless of this response, I'm sure there is still some theoretical limit. Based off the other information I've gathered, it's better to split the API calls up anyway using multiple Plivo number (sender id's). If you have a suitable number of long codes, you shouldn't have to worry about this limit.
Related information:
Long code SMS restrictions
How do I send 6000+ messages using a long code?
In other words, use multiple long codes and split up your destination numbers accordingly to send out in parallel.
Edit* Received another response that seems more accurate
"You can add upto 250 numbers per API request. That should be the ideal limit on the destination parameter."
For anyone wondering what the actual bulk-messaging limit is nowadays (2021), it is 1,000 numbers per API call.
Thankfully this is now clearly stated on Plivo's API Docs page in the Bulk Messaging section:
The Message API supports up to 1,000 unique destination numbers.

How would I design this scenario in Twilio?

I'm working on a YRS 2013 project and would like to use Twilio. I already have a Twilio account set up with over $100 worth of funds on it. I am working on a project which uses an external API and finds events near a location and date. The project is written in Ruby using Sinatra (which is going to be deployed to Heroku).
I am wondering whether you guys could guide me on how to approach this scenario: a user texts to the number of my Twilio account (the message would contain the location and date data), we process the body of that sms, and send back the results to the number that asked for them. I'm not sure where to start; for example if Twilio would handle some of that task or I would just use Twilio's API and do checking for smss and returning the results. I thinking about not using a database.
Could you guide me on how to approach this task?
I need to present the project on Friday; so I'm on a tight deadline! Thanks for our help.
They have some great documentation on how to do most of this.
When you receive a text you should parse it into the format you need
Put it into your existing project and when it returns the event or events in the area you need to check how long the string is due to a constraint that twilio has of restricting messages to 160 characters or less.
Ensure that you split the message elegantly and not in the middle of an event. If you were returned "Boston Celtics Game", "The Nut Cracker Play". you want to make sure that if both events cannot be put in one message that the first message says "Boston Celtics Game, Another text coming in 1 second" Or something similar.
In order to receive a text message from a mobile device, you'll have to expose an endpoint that is reachable by Twilio. Here is an example
class ReceiveTextController < ActionController
def index
# let's pretend that we've mapped this action to
# http://localhost:3000/sms in the routes.rb file
message_body = params["Body"]
from_number = params["From"]
SMSLogger.log_text_message from_number, message_body
end
end
In this example, the index action receives a POST from Twilio. It grabs the message body, and the phone number of the sender and logs it. Retrieving the information from the Twilio POST is as simple as looking at the params hash
{
"AccountSid"=>"asdf876a87f87a6sdf876876asd8f76a8sdf595asdD",
"Body"=> body,
"ToZip"=>"94949",
"FromState"=>"MI",
"ToCity"=>"NOVATO",
"SmsSid"=>"asd8676585a78sd5f548a64sd4f64a467sg4g858",
"ToState"=>"CA",
"To"=>"5555992673",
"ToCountry"=>"US",
"FromCountry"=>"US",
"SmsMessageSid"=>"hjk87h9j8k79hj8k7h97j7k9hj8k7",
"ApiVersion"=>"2008-08-01",
"FromCity"=>"GRAND RAPIDS",
"SmsStatus"=>"received",
"From"=>"5555992673",
"FromZip"=>"49507"
}
Source

Twilio multiple treads to have each call have 1 process

Using Ruby, Sinatra, and the Twilio REST API, I'm coding a customer service line for my company. When an incoming call is received, the customer is put on hold in a < Conference > verb, while the application makes an outgoing call to an agent. If he accepts the call, they are then the calls bridged.
I currently have 3 conference rooms (Tech Supp, Sales, and Mobile Supp) created by my fairly linear program. But if a conference room is busy while another call comes in requesting the already occupied room, they can't reach an agent, which is problematic.
My question is : Can I/How do I create a thread in Ruby for each incoming call so that it has its own independent process?
My reasoning behind this is : Once each call has its thread, then I can create a room called "name of department" + "#process.id".
For example : (also adding a randomly generated 7-digit number to make each conference name to make it 100% unique.
#random = Random.rand(10_000_000 - 1_000_000) + 1_000_000
puts #random
< Dial >
< Conference > 'Tech Supp' + PROCESS_ID \ + #random < /Conference >
< /Dial >
Twilio evangelist here.
Two ideas here. Rather than getting into threads, which can get really messy, really quickly, why not just create a different conference room using the inbound callers CallSid. I've created systems similar to what you describe before using that technique. You system just catalogs each CallSid as it arrives so you can go back later and connect and agent to that conference.
Another option might be to use Queue. When a new call dials in, you could just drop them in a queue (or different queues if you want) and they can wait there until an agent is ready. The agent can then pick the next caller out of the queue to speak with.
This HowTo on using <Queue> might be helpful:
http://www.twilio.com/docs/howto/callqueue
Hope that helps.

Resources